Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Returning a boolean variable in Ajax

Options
  • 30-06-2008 9:48pm
    #1
    Registered Users Posts: 4,037 ✭✭✭


    I have an ASP page with two calendars on it. I want use Ajax to check if one date is greater than the other (a start date and an end date).

    This is the javascript function I am calling from a button:
    
    function btnCompareDates_OnClick(startdate,enddate)
    	
    	{
    	startdate=document.getElementById("ctl00_mainContentPlaceHolder_txtCheckInDate").value;
    	enddate=document.getElementById("ctl00_mainContentPlaceHolder_txtCheckOutDate").value;
    	
    
    	requestUrl="";  
    
    	AjaxPage = "ActivateAjax.aspx";
    	
    	var requestUrl =AjaxPage  += "?Action=CompareDates&hotelstartdate=" + encodeURIComponent(startdate)+"&hotelenddate="+encodeURIComponent(enddate);
    	
    	CreateXMLHTTP();
    
    	// If browser supports XMLHTTPRequest object
    	if(XMLHTTP)
    	{
    		
    		XMLHTTP.onreadystatechange = ShowSuccessMsg;
    		
    		XMLHTTP.open("POST", requestUrl,  true);
    		
    		//Sends the request to server
    		XMLHTTP.send(null);	
    		
    		
    		
    	}
    
    


    It takes the start date and end date from two text boxes "ctl00_mainContentPlaceHolder_txtCheckInDate").value" and "ctl00_mainContentPlaceHolder_txtCheckOutDate").value" .
    It assign them to two variables (startdate and enddate)
    It passes these two variables to the method above and they get passed to an ASP page ("ActivateAjax.aspx") which has C# code as the code behind.
    There is a function in the C# page called CompareDates() which compares the two dates passed to it.

    That is easy enough, I can get the two dates into the C# page to do the comparison check but how do I pass the result back to the client page?
    I know it has to be encoded in HTML when it is passed back.
    The C# function from ActivateAjax.aspx's back-end code is below:
    public Boolean CompareDates(DateTime date1, DateTime date2)
    
            {
                if (date1 > date2)
                {
    
             
                    return false;
    
                }
                else
                {
                    return true;
                }
    
            }
    

    I won't be able to respond to this thread until tomorrow night (or maybe the night after) so apologies if you need ask me for more info and don't get it straight away.
    Thanks to anyone who does reply though.


Comments

  • Registered Users Posts: 1,045 ✭✭✭Bluefrog


    2 options, either change the return type of your date comparison function there to int and return either 1 or 0 or check for a response of 'true' or 'false' on the return of your ajax function.

    For maximum efficiency in terms of bandwidth I would go for the 1 and 0.


  • Closed Accounts Posts: 81 ✭✭dzy


    This is a check that does not rely on server side info so I'd do it client side.


  • Registered Users Posts: 21,257 ✭✭✭✭Eoin


    dzy wrote: »
    This is a check that does not rely on server side info so I'd do it client side.

    Yeah, I would look at doing this client side.

    I don't think you need any HTML encoding to return a result. You just write out the result of the function to the page and check for that value in your JavaScript.


  • Registered Users Posts: 4,037 ✭✭✭lukin


    eoin_s wrote: »
    Yeah, I would look at doing this client side.

    I don't think you need any HTML encoding to return a result. You just write out the result of the function to the page and check for that value in your JavaScript.

    I presume you mean the C# page?


  • Registered Users Posts: 21,257 ✭✭✭✭Eoin


    lukin wrote: »
    I presume you mean the C# page?

    Yeah, the page that your AJAX request is calling - just Response.Write the result of the function.


  • Advertisement
  • Registered Users Posts: 1,045 ✭✭✭Bluefrog


    Well you can do the validation client-side but best practice would be to validate everything on the server side anyway once the form is submtted and since you already have a function written...

    Apart from anything else its a nice little AJAX learning exercise.

    I suppose where you do validation depends on your app and what those dates will be used for but in any production app I would never trust what comes to me from the client without checking it server-side.


  • Registered Users Posts: 21,257 ✭✭✭✭Eoin


    Bluefrog wrote: »
    Well you can do the validation client-side but best practice would be to validate everything on the server side anyway once the form is submtted and since you already have a function written...

    Apart from anything else its a nice little AJAX learning exercise.

    I suppose where you do validation depends on your app and what those dates will be used for but in any production app I would never trust what comes to me from the client without checking it server-side.

    There should definitely be server side validation as well, but for this scenario it's client side validation, but using a server side method that doesn't do anything that a client couldn't do.


  • Registered Users Posts: 4,037 ✭✭✭lukin


    eoin_s wrote: »
    There should definitely be server side validation as well, but for this scenario it's client side validation, but using a server side method that doesn't do anything that a client couldn't do.

    Well originally I wanted to validate the date using a Javascript method. I saw one or two on the 'net but I didn't want to just use someone else's code.
    I am doing all my other validation in Javascript (checking to see if text boxes are text when they should be numeric etc.).
    I haven't got around to trying your solution yet, I saw another one where apparently the line
    XMLHTTP.readyState==4. means that data has been returned and I can then get the return value with the line XMLHTTP.responseText.

    I'll try it and see how I get on.

    Edit:there's supposed to be an ASP Compare Validator control too? Dunno if it works on dates. Sounds a bit too easy though so I won't use it.


  • Registered Users Posts: 1,045 ✭✭✭Bluefrog


    It's not a question of functionality of the validation - more of control. For the overhead of a couple of bytes I think it's a nice usabiltiy feature. Probably wouldn't have done it myself to be honest but since the OP has the code written...

    And yes, you can run a while loop to check when the xmlhttp status is 4 - different browsers get to 4 in different ways but they all get there - from there you can check your value in the response and call your callback function appropriately - if all is correct maybe put focus on the next input, if wrong display an error message etc.


  • Closed Accounts Posts: 81 ✭✭dzy


    Its a nice exercise. But isn't it easier just to have a Javascript function?
    function compareDate(d1, d2)
    {
      var date1 = new Date(d1);
      var date2 = new Date(d2);
      return date1 > date2;
    }
    


  • Advertisement
  • Registered Users Posts: 4,037 ✭✭✭lukin


    Sorry about the delay but I didn't get back to the problem until now:
    I sorted it like so:

    The Javascript function btnCompareDates_OnClick is called from a button to validate the dates in two text boxes (ctl00_mainContentPlaceHolder_txtCheckInDate and ctl00_mainContentPlaceHolder_txtCheckOutDate)

    The JScript is below:
    function btnCompareDates_OnClick(startdate,enddate)
    	
    	{
    	startdate=document.getElementById("ctl00_mainContentPlaceHolder_txtCheckInDate").value;
    	enddate=document.getElementById("ctl00_mainContentPlaceHolder_txtCheckOutDate").value;
    	
    
    	requestUrl="";
     
    	AjaxPage = "ActivateAjax.aspx";
    	
    	var requestUrl =AjaxPage  += "?Action=testDates&hotelstartdate=" + encodeURIComponent(startdate)+"&hotelenddate="+encodeURIComponent(enddate);
    	//calling the function that creates the XMLHTTPRequest object
    	CreateXMLHTTP();
    	if(XMLHTTP)
    	{
    
        XMLHTTP.onreadystatechange = CompareDates;
        XMLHTTP.open("POST", requestUrl,true);
    
        XMLHTTP.send(null);	
     
    		
        }
    	  
    }
    
    
    function CompareDates()
    {
    
        //receiving response from server	
    	if(XMLHTTP.readyState == 4)
    	{
    	
    
    		//If a valid Response is received
    		if(XMLHTTP.status == 200)
    		{	
    		    if(XMLHTTP.responsetext=="True")
    		    {
    		    alert("Check in is greater than check out")
    		    
    		    }
    		    
    		    else
    		    {
                alert("Check out is greater than check in")
    
    		    }
    				
    
    		}
    		else  
    		{
    			//if a valid response could not be retrieved from server
    			alert("Could not retrieve data from server");
    			
    		}
    		
    	}
    	
    	else
    	{
    	   //Waiting for response for server 
    	}
    }
    
    
    

    The ActivateAjax.aspx page that contains the C# code behind has two functions (CompareDates and testDates) which are shown below:
    public void testDates(DateTime startDate, DateTime endDate)
            {
    
                string ren = CompareDates(startDate, endDate).ToString();
    
                Response.ContentType = "text/plain";
                Response.Write(ren);
            }
    
    
            public Boolean CompareDates(DateTime date1, DateTime date2)
    
            {
               
                if (date1 > date2)
                {
    
    
                    return true;
    
                }
                else
                {
                   return false;
                }
    
    
                
               
           
    
            }
    
    


    As you can see I did have to encode the response from the server ( Response.ContentType = "text/plain";).
    Maybe there is an easier way of doing it but it works and that's all I care about.


  • Registered Users Posts: 7,468 ✭✭✭Evil Phil


    Seeing as its Asp.Net wouldn't the simplest way to do this be with a compare validator? That way you get both javascript *validation* on the clientside and you get full server validation on postback, and they appear seamless to genuine users.

    [html]
    <asp:CompareValidator ID="cvDates" runat="Server" ErrorMessage="Failed" Display="static"
    ControlToCompare="txtCheckInDate" ControlToValidate="txtCheckOutDate" Operator="GreaterThan"
    Type="date"></asp:CompareValidator>
    [/html]

    While it doesn't have the learning exercise of doing this in Ajax it is pretty much the best way to do a date compare of this kind in Asp.net

    As an aside when referencing asp.net controls from javascript best practice is to use the ClientID
    startdate=document.getElementById('<%= txtCheckInDate.ClientID %>').value;
    

    This means that no matter how the container controls change you'll always have the correct id in your rendered script. I've been lambasted before for suggesting this by designer types as their scripts looks less pwetty but it will always work regardless of whats happening further up the control heirarchy.


  • Registered Users Posts: 7,468 ✭✭✭Evil Phil


    One more minor thing, bit of a pet hate for myself, but Asp and Asp.net are two different distinct technologies. Referring to asp pages is referring to classic asp, not .Net.


  • Registered Users Posts: 4,037 ✭✭✭lukin


    Evil Phil wrote: »
    One more minor thing, bit of a pet hate for myself, but Asp and Asp.net are two different distinct technologies. Referring to asp pages is referring to classic asp, not .Net.

    Yeah I should have made that clear. I think classic ASP pages end with a .asp extension and ASP.NET pages end with a .aspx extension.
    I didn't know there was such a thing in ASP.NET as a compare validator, thanks for the tip but I wanted to do it in Ajax as I wanted to see it working that way.
    Using ClientID to identify text boxes etc. in Javascript is a good idea too, must keep that in mind for the future.
    About validation, most of mine is done client-side (in javascript) as I wanted to find out a few things in javascript, (which I have).
    The site is just something to put on my CV so in other pages I might well do my validation on the server just to show I can do it.
    I have no preference for one or the other.


  • Registered Users Posts: 21,257 ✭✭✭✭Eoin


    lukin wrote: »
    The site is just something to put on my CV so in other pages I might well do my validation on the server just to show I can do it.
    I have no preference for one or the other.

    Validation absolutely must be done on the server. If you do it on the client, it should just be in addition to the server side checks.


  • Registered Users Posts: 4,037 ✭✭✭lukin


    eoin_s wrote: »
    Validation absolutely must be done on the server. If you do it on the client, it should just be in addition to the server side checks.

    The validation I'm doing in javascript is checking if fields are blank and if fields are not numeric when they should be.
    It seems a bit unnecessary to send a text field back to the server to check something like that when it can be done in jscript?
    I worked in a reputable software company for a while and all their validation was done in jscript.
    I have to do other validation like checking if a number entered into a text box is greater or less than another number etc. I will send that to the server as well as any stuff to do with dates. I wouldn't trust jscript for stuff like that.


  • Registered Users Posts: 21,257 ✭✭✭✭Eoin


    Sorry, but that is very poor design. How do you know that JavaScript is enabled on the browser? You just can't leave that to chance. There is no excuse for not validating on the server, bar the minimal initial overhead in development time. Anything else is lazy design.

    By the way, JavaScipt can compare dates as easily as numerics or strings. If in doubt, just convert to milliseconds and do a numeric comparison.


  • Registered Users Posts: 9,579 ✭✭✭Webmonkey


    Validation using Javascript alone is simply not enough - End of.


  • Registered Users Posts: 4,037 ✭✭✭lukin


    eoin_s wrote: »
    Sorry, but that is very poor design. How do you know that JavaScript is enabled on the browser? You just can't leave that to chance. There is no excuse for not validating on the server, bar the minimal initial overhead in development time. Anything else is lazy design.

    By the way, JavaScipt can compare dates as easily as numerics or strings. If in doubt, just convert to milliseconds and do a numeric comparison.

    But even if I validate with server side code I am still going to need to use javascript to some degree, like if I want to send a textbox value to the server I will have to get the value of that textbox using "getElementbyID" or ".innerHTML"?


  • Registered Users Posts: 21,257 ✭✭✭✭Eoin


    lukin wrote: »
    But even if I validate with server side code I am still going to need to use javascript to some degree, like if I want to send a textbox value to the server I will have to get the value of that textbox using "getElementbyID" or ".innerHTML"?

    No, there is no need for client side script at all. The ASPX page knows what form fields have been added, so when the page is loaded, or the button clicked you just do something like this:
    if (txtName.Text.Equals(""))
    {
        lblError.Text = "please enter your name";
    }
    else
    {
        //do stuff
    }
    

    Client side scripting is only a "nice to have", which can stop or reduce round trips to the server. However they will never be a substitute.

    Edit: Just to clarify that, you would need to use JavaScript if you are doing an AJAX call to the server, however that would not be considered sufficient validation.


  • Advertisement
  • Closed Accounts Posts: 81 ✭✭dzy


    I think there are 2 things here.

    - There is the validation you do before data is sent by the client. This you can do with some Javascript checking or if you rely on server side info (for example, when checking the uniqueness of a username in a registration form) you can use AJAX. Client side validation works on the principal of 'why bother sending data to the server if you already know its invalid'.

    - Then there is the validation you do when data is submitted to the server. This validation is essential since you cannot rely on client side validation. Clients may have Javascript disabled in their browser or may not even have sent their request through the browser at all.


  • Registered Users Posts: 4,037 ✭✭✭lukin


    eoin_s wrote: »
    No, there is no need for client side script at all. The ASPX page knows what form fields have been added, so when the page is loaded, or the button clicked you just do something like this:
    if (txtName.Text.Equals(""))
    {
        lblError.Text = "please enter your name";
    }
    else
    {
        //do stuff
    }
    

    That's server-side code though which means it will cause a page refresh?
    In my site, when incorrect data is entered into a text box it makes an asterix appear beside it so I do it all in JScript.

    Just one question about the point people have made about users having javascript disabled in their browsers;doesn't this mean that Ajax won't work at all so? The XMLHttp object won't be able to send stuff to the back-end code.


  • Closed Accounts Posts: 81 ✭✭dzy


    lukin wrote: »
    Just one question about the point people have made about users having javascript disabled in their browsers;doesn't this mean that Ajax won't work at all so? The XMLHttp object won't be able to send stuff to the back-end code.

    Yep. AJAX stuff won't work.


  • Registered Users Posts: 21,257 ✭✭✭✭Eoin


    lukin wrote: »
    That's server-side code though which means it will cause a page refresh?
    In my site, when incorrect data is entered into a text box it makes an asterix appear beside it so I do it all in JScript.

    That's correct, it is server side. The point is that you must do all important validation on the server side. Whether you choose to also do this client side to provide a better user experience is optional. If you use the ASP.net validators, then you get client and server side validation automatically (though you do have to check the condition of the validator in your .net code).

    I would summarise it like this:

    Use client side to validate fields have been populated, compare two fields against each other etc.

    Use AJAX to check if fields match a condition that can only be verified by the server. For instance, has a desired username already been taken? This is by no means all AJAX can be used for; I am just talking about field validation.

    Use Server side to check all of the above again.


Advertisement