New to Ajax and PHP. Am using Ajax on a form originally written in ASP.

User selects options for sponsorships using checkboxes. Each checkbox is linked to a price structure.

If he checks the checkbox, I'm using Ajax to fill in the cost of the sponsorship in a text field next to the checkbox.

This works just fine. My problem is that if the visitor changes his mind and unchecks the checkbox, I have not found a way to dismiss the cost by refilling the text field with a null or empty string. Have tried testing the checkbox value on both server and client side, but I haven't been successful yet in dismissing the price if the box is unchecked.

Can anyone direct me on how this should be done?

    Hi Codeaphobe,

    What you can do is just add an extra condition to your ajax function in javascript to check whether the selected check box is selected or not. If its selected then simply allow the ajax call else just set the text box to empty string without calling the ajax call.

    here an example using jquery..

    eg:

    <script language="javascript">
    
    
    function callAjax(obj)
    {
        if($('#'+obj).is(':checked'))
       {
           // call ajax
       }
       else
       {
           $('#textbox').val('');
       }
    
    
    }
    
    </script>
    
    <input type="checkbox" name="chkOption" id="chkOption" onclick="callAjax('chkOption');" />
    

    Hope this helps.

    Thanks,
    best regards,

    Niroshan

      Thank you for your help niroshan. Your idea made sense, but I'm uncertain about how I pass the parameters for my getData Ajax function when using callAjax to call it.

      Here is the function setup you've suggested:
      function callAjax(obj)
      {
      if($('#'+obj).is(':checked'))
      {
      // call ajax
      getData(dataSource, divID, data);
      }
      else
      {
      $('#textbox').val('');
      }
      }
      Is the above function call syntax correct? (Crux of my question is how to pass actual parameter data as given in an original checkbox definition below).

      And here is the getData function with parameters it uses:
      function getData(dataSource, divID, data)
      {

      Lastly, here is how the parameters were originally successfully passed to the getData function:
      <input name="chk2" type="checkbox" id="chk2" value="1" onclick="getData('dataresponderpost.php?data=1800', 'Eagle', 2)"/>

      I think your idea makes sense; it's just the mechanics I'm a bit unsure of...

      Again, I appreciate your willingness to help.

        Well, I got it working the way I want it to, although it's not "elegant." The check boxes remain checked but the prices are gone if the visitor continues to the last page and then decides to backtrack, but that's not too critical and I've lost enough hair already...

          Hi Codeaphobe,
          Sorry for delayed reply. Well what you need to do is change the parameters in the callAjax as you needed.

          function callAjax(obj, dataSource, divID, data)
          {
              if($('#'+obj).is(':checked'))
             {
                // call ajax
               getData(dataSource, divID, data);
             }
             else   
          $('#textbox').val(''); }

          so when you call it like,

          <input name="chk2" type="checkbox" id="chk2" value="1" onclick="callAjax('chk2', 'dataresponderpost.php?data=1800', 'Eagle', 2)"/>
          
          

          Hope this helps...

          Regards,
          Niroshan

            Thanks for the reply, niroshan. However, I tried the code above and it does not appear to work for me. Odd thing now is that my code from the comment previous to yours, which was working, is now also not working.

            When I click in each box, I get a check mark, but the price does not appear. I saw that your example appears to pass 'chk2' as an additional (4th) parameter, but the callAjax code only states 3 params. I tried adding an additional param name to that and the getData function, but the result is still the same - no price appears.

            My kludgy and redundant code did work yesterday, but tonight it is not. Now I am perplexed as to the reason.

              Hi Codeaphobe,

              That is strange. Can you please show us the error? Are you using jquery library in your code?

              I saw that your example appears to pass 'chk2' as an additional (4th) parameter, but the callAjax code only states 3 params. I tried adding an additional param name to that and the getData function, but the result is still the same - no price appears

              Yes I have added a new parameter. This is actually the ID of the check box. So for each check box you have to change it to relevant ID.
              getData function doesnt need that 4th parameter. If you check the callAjax carefully u`ll see I have used that 4th parameter to check the state of the check box.

              Also please check your dataresponderpost.php code as well to check what kind a output it generates.

              Thanks,
              Best regards,
              Niroshan

                Hello again niroshan...

                I am not seeing any error message. I will post all of the pertinent pieces of the code as it currently exists. (I'm not sure the code for "waking up jQuery" is correct, but I had read that this must be done after declaring it to make it work). Maybe the source of the problem lies there?

                OK, here you go:

                <script type="text/javascript" src="jquery.js"></script>

                <script type="text/javascript">
                $(document).ready(function(){
                $("input.sponsorship")

                .change(function(){

                $("#"+this.value).text(

                !this.checked? "" :

                $(this).next().text().replace(/[\$]+/, "")

                );
                });
                </script>

                <script language="javascript">
                function callAjax(obj)
                {
                if($('#'+obj).is(':checked'))
                {
                // call ajax
                getData(dataSource, divID, data);
                }
                else
                {
                $('#di').val('');
                }

                }
                </script>

                <script language = "javascript">

                var XMLHttpRequestObject = false;
                if (window.XMLHttpRequest) {
                XMLHttpRequestObject = new XMLHttpRequest();
                } else if (window.ActiveXObject) {
                XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
                }

                function getData(dataSource, divID, data)
                {
                if(XMLHttpRequestObject) {
                var obj = document.getElementById(divID);
                XMLHttpRequestObject.open("POST", dataSource);
                XMLHttpRequestObject.setRequestHeader('Content-Type',
                'application/x-www-form-urlencoded');
                XMLHttpRequestObject.onreadystatechange = function()
                {
                if (XMLHttpRequestObject.readyState == 4 &&
                XMLHttpRequestObject.status == 200) {
                obj.innerHTML = XMLHttpRequestObject.responseText;
                }
                }
                XMLHttpRequestObject.send("data=" + data);
                }
                }
                </script>

                The form's HTML:

                  <td valign="middle"><div align="left">
                    <input name="chk1" class="sponsorship" type="checkbox" id="chk1" value="1" onclick="callAjax('dataresponderpost.php?data=3500', 'DoubleEagle', 1)" /><label for="chk1">&nbsp;&nbsp;Double Eagle Sponsor - $3500 - </label><a href="#" onclick="doDetails1()">details</a>

                </div></td>
                <td><div align="right" id="DoubleEagle">&nbsp;</div></td>

                I checked the dataresponder.php file and it is okay. It worked, but I just could not deal successfully with the "If they uncheck the checkbox, dismiss the price" event.

                Now here is the code for the second checkbox. This was my way of making it work originally, and now this does not work either. That I do not understand. It's mysterious...

                HTML:

                <td><div align="left">
                <input name="chk2" type="checkbox" id="chk2" value="1" onclick="DoCheck2()" />
                &nbsp;Eagle Sponsor - $1800 - <a href="#" onclick="doDetails2()">details</a> </div></td>
                <td><div align="right" id="Eagle">&nbsp;</div></td>

                Function called:

                function DoCheck2() {
                if(document.form1.chk2.checked == true) {
                alert('Check1 is checked.');
                dataSource = 'dataresponderpost.php?data=1800';
                divID = 'Eagle';
                data = 2;
                getData(dataSource, divID, data);
                }else {
                //alert('Check1 is unchecked.');
                dataSource = 'datarespondernull.php?data=0';
                divID = 'Eagle';
                data = 2;
                getData(dataSource, divID, data);
                }
                }

                Thanks for your continuing help to a rookie....🙂

                  Hi Codeaphobe,

                  Well Thanks for posting the code. That revealed some of the mistakes you have done. I will list them one by one,

                  $(document).ready(function(){
                  $("input.sponsorship")
                  .change(function(){
                  $("#"+this.value).text(
                  !this.checked? "" :
                  $(this).next().text().replace(/[\$]+/, "")
                  );
                  });

                  • I really dont understand what you trying to do here because your assigning change event to the check box but check box already having a onclick event.
                  • your missing one closing curly brace
                  • this.value will return the value of the check box so in this case it will be 1 and your trying to get the element by placing it as $("#"+this.value). But the element ID 1 doesnt exists.
                  • Frankly speaking I dont think you need this function anyway

                  function callAjax(obj)
                  {

                  and

                  onclick="callAjax('dataresponderpost.php?data=3500', 'DoubleEagle', 1)

                  • By looking at this can you guess the error? look at the passing parameters. your function accept only one parameter but your passing 3 into it. please refer to my old reply for the changes.

                  $('#di').val('');

                  • I hope you have some element as ID di

                  if(XMLHttpRequestObject) {
                  var obj = document.getElementById(divID);
                  XMLHttpRequestObject.open("POST", dataSource);
                  XMLHttpRequestObject.setRequestHeader('Content-Type',
                  'application/x-www-form-urlencoded');
                  XMLHttpRequestObject.onreadystatechange = function()
                  {
                  if (XMLHttpRequestObject.readyState == 4 &&
                  XMLHttpRequestObject.status == 200) {
                  obj.innerHTML = XMLHttpRequestObject.responseText;
                  }
                  }
                  XMLHttpRequestObject.send("data=" + data);
                  }

                  • since your using jquery library why dont you use the jquery ajax calls. Its much simpler and less code. I have changed callAjax function slightly to demonstrate the ajax call. I have removed the getData function as well.
                  function callAjax(obj, dataSource, divID, params)
                  {
                  	if($('#'+obj).is(':checked'))
                  		$.post(dataSource, { data:params }, function(returnData){
                  			$('#'+divID).html(returnData);									
                  		});
                  	else
                  		$('#di').val('');
                  
                  }
                  
                  
                  <input name="chk1" class="sponsorship" type="checkbox" id="chk1" value="1" onclick="callAjax('chk1', 'dataresponderpost.php?data=3500', 'DoubleEagle', 1)" />
                  
                  

                  Hope this helps. Please understand the code before using it.

                  PS: next time when you post the code please use the bbcode

                  Thanks,
                  Best regards,
                  niroshan

                    Write a Reply...