Search code examples
phpjqueryajaxsuperglobals

about the jquery ajax and with php


After reading ajax from:

http://api.jquery.com/jquery.ajax/ I am totally confused.

It was so complex and I don't know anything about xml I just know few about php and jquery but I was confused a lot.

i don't know how to work ajax with php...

and people talk about handlers call backs etc i don't know anything what are they talking..

and when i work with php and submit thorugh php what is going to be $_POST["name"] is there $_COOKIE or some super globals

I just wanna know what should go in PHP files


Solution

  • Here is a basic example that will let input your name, and PHP will return it in a sentence and let it be displayed.

    Here is the html that I name foo.html:

    <html>
    <head>
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script type="text/javascript">
    function callPHP() {
            $.ajax({
                    type: "POST",
                    url: "foo.php",
                    data: { name: $('#namefield').val() }
            })
              .done(function(response) {
                    $('#response').html(response);
            });
    }
    </script>
    </head>
    <body>
    <span id="response"></span>
    <br/>
    Name: <input id="namefield" type="text"><button onclick="callPHP()">Submit</button>
    </body>
    

    Here is the PHP code that I named foo.php:

    <?php
    if(!empty($_POST['name'])) {
            echo 'Your name is '.$_POST['name'];
    } else {
            echo 'I did not get anything';
    }
    ?>
    

    The callPHP function takes the value of the input field and assigns it to post value with data: { name: $('#namefield').val() } and assign it to the POST field of name. The response is handled with the done(function(response){}) anonymous function and assigns the span value to it.

    I hope this helps.