Perkin5
Perkin5

Reputation: 399

How does jquery ajax actually work

Say I have a form like this (taken from a book on jquery):

<body>
<form>
<label>Enter your Name</label>
<input type="text" name="uname" class="uname"/> <br/>
<input type="submit" id="submit"/>
</form>
<div id="message"></div>
</body>

and an ajax function like this:

$(document).ready(function() {
   $('#submit').click(function () {
   var name = $('.uname').val();
   var data = 'uname=' + name;
      $.ajax({
         type:"POST",
         url:"welcome.php",
         data: data,
         success: function (html) {
            $('#message').html(html);
         }
      });
      return false;
   });
});

and the script file looks like this:

<?php
$name = $_POST['uname'];
echo "Welcome ". $name;
?>

it will work but here's what I can't understand. If the welcome.php script gets the value of $name from the POST array, why does it need to have the data sent to it by the ajax request? The POST array already contains that information surely?

Also, my understanding is that the ajax request is in the form of key/value pairs but the data is sent in the form uname=name but key/value pairs don't normally have an equals sign.

What's going on here - it works but it doesn't make sense to me and I hate just punching in code I have learnt by rote.

Upvotes: 1

Views: 4304

Answers (2)

Salahuddin Khan
Salahuddin Khan

Reputation: 26

Issue is with your code
var data = 'uname=' + name;
use
var data = '{uname:' + name + '}';
because its a post method

Upvotes: 0

Mathijs Flietstra
Mathijs Flietstra

Reputation: 12974

jQuery AJAX works asynchronously. The form does not get posted, as you can see it does not have an action or method attribute set on the form tag.

jQuery intercepts the button click and sets up a new asynchronous request and then adds the data to that request and posts it to the server.

Upvotes: 2

Related Questions