Question

  1. The function/ajax request below refuses to work/'post' and I cannot figure out why.

  2. I assume any data variables a PHP script receives from my Ajax request should reference those as $_POST['sday'] and $_POST['sdate']?

  3. PS how should success function handle a JSON encode response from my PHP script?

My Code:

<html>
<head>
    <title></title>
</head>
<body>
<h1>Welcome to Richmond nursing app, you have successfully logged in!</h1>
<hr>
<form id="idForm" name="idForm">
<input type="text" size="8" id="date" name="date"><br>
<input type="hidden" size="8" id="reversedate" name="reversedate"><br>
<input type="hidden" size="1" id="dow" name="dow"><br>
<input type="submit" id="submitbutton" name="submitbutton">
</form>
<div id="report" name="report">
</div>  
<br><br><br>
<br>
<br>
<p id="p1">x</p>
<br>
<a href="logout.php">log out</a>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">  </script>
<script type="text/javascript" src="js/jquery-ui.js"></script>
<script type="text/javascript" src="js/ui.js"></script>
<script>
        $('#submitbutton').click(function(){
                  var fulldate=$('#date').datepicker('getDate');
                  var date=fulldate.getDate();
                  var day=fulldate.getDay();
                  var month=fulldate.getMonth()+1;
                  var year=fulldate.getFullYear();

                  if (month<10) 
                    {month="0"+month};
                  if(date<10)
                    {date="0"+date};

                 var selecteddate=year+"-"+month+"-"+date;
              
                 var url = "fetchsimple.php"; // the script where you handle the form input.
                  $.ajax({
                      type: "POST",
                      url: url,
                      data: {sdate: selecteddate, sday:day}, // serializes the form's elements.
                      success: function(data)
                      {
                          alert(data); // show response from the php script.
                      }
                    });
                });
</script>
</body>
</html>
Was it helpful?

Solution

Handle Submit event in jquery code like below:

$('#submitbutton').click(function(e){
    e.preventDefault();
    .......
    .......

}

For JSON response add

dataType: 'json'

to ajax request and then you can use encoded data with period(.) sign. for example:

alert(data.msg);

OTHER TIPS

Instead of handling a click on the submit button, handle the submit event of the form:

$('#idForm').submit(function() {

...
...

  return false;
}

the return false will cancel the form submit letting your AJAX call finish.

for the JSON response you want to specify the data type in the AJAX call.

dataType: 'json'

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top