Question

I'm still learning ajax and I'm trying to get my php file to communicate with the ajax file but I can't get it to work. I might be overlooking something but this is the code:

global.js file:

$('input#testbutton').on('click', function() {
   var id = $('[name="selectedPatient"]').val();
   $.post('ajax/selection.php', {id: id}, function(data) {
       alert(data);
   });  
});

my selection.php file just echo's "15", but when I press the testbutton, i get no alert. I tested if the button works without the $.post function, by just alerting with an on.click and that works just fine. The var id also works ( alert tested that aswell ).

selection.php :

<?php 
   echo "test";
?>
Was it helpful?

Solution

when i press it the firebug console shows POST ajax/selection.php for one second then its empty again –

Aaaah, the page gets reloaded. You should listen to the submit event of the <form>, and be sure to call event.preventDefault() inside the handler.

HTML:

<form action="ajax/selection.php" method="post" id="yourForm">
  <input name="selectedPatient" type="text">
  <input type="submit" value="Submit">
</form>

JS:

$('#yourForm').submit(function(event){

  // this prevents the page from being reloaded
  event.preventDefault();

  $.post(
    $(this).attr('action'), // gets action from the form itself
    $(this).serialize() // serializes the whole form
  ).done(function(data){ // do your business here });

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