tags:

views:

48

answers:

4
+1  Q: 

Ajax with jQuery

Hello! I'm very new to jQuery and AJAX.

i read a bit of the API provided by jquery on their website which said :

Example: Alert out the results from requesting test.php (HTML or XML, depending on what was returned).

$.post("test.php", function(data){
   alert("Data Loaded: " + data);
 });

Now,i'd like to know how exactly test.php returns some data . I mean,could someone provide a sample "test.php" here

Thanks! :D

+2  A: 

You could just return a simple string. Whatever the output is of the URL parameter will be captured by the particular ajax method you are using:

<?php echo 'this is a test'; ?>

If you want to return a more complex structure (such as json) you could do:

<?php 

$data = array('foo' => 'bar');
echo json_encode($data);

?>

and on the client:

$.post("test.php", function(json){
   alert("Data Loaded: " + json.foo);
}, "json");
karim79
so,whatever is echoed,is the returned data, is it ?
Anant
You request the contents of which the URL (and headers) points to, so yes.
Harmen
PHP files don't return data - they produce pages. The output of a PHP file is just like a plain text file - you could replace `test.php` with `test.txt` and put whatever XML you want in the text file.
Skilldrick
thanks. suppose i want to send some data,and depending on that request say a set of variables $name,$dob,$address from the PHP file,how would i do that?
Anant
A: 

test.php could look like this:

<tag>Data!!!</tag>

No <?php tags necessary.

If you're using JSON (which is a good choice for a lot of things) you can create a PHP object or array and then do:

<?php echo json_encode($my_object); ?>
Skilldrick
A: 
<?php echo 'return data'; ?>

What happens is that the browser will make a request to the given URL, much like any other web request, with the exception that the browser doesn't render the result; it hands it to you so that you may do with it what you wish.

For returning complex php-objects as JSON objects, for your javascript to interact with, check out json_encode()

David Hedlund
A: 

Lets say if you have some code in test.php

<?php
 echo "test data from test.php"
?>

The message is passed to data variable of javascript and will be alerted finally.

Some useful links

Here is example and simple application

index.php

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title><!-- Insert your title here --></title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt;

<script type="text/javascript">

    function register(){
        $.ajax({
            type: "POST",
            url: "submit_data.php",
            data:   "username=" + document.getElementById("username").value + 
                    "&email=" + document.getElementById("email").value,
            success: function(html){
                $("#response").html(html);
            }
        });

        }

    </script>
</head>
<body>
    <form action="" method="post">
          <p>
            <label for="name">Name:</label><br />
            <input type="text" name="username" id="name" size="25" />
          </p>
          <p>
            <label for="email">Email:</label><br />
            <input type="text" name="email" id="email" size="25" />
          </p>
          <p>
            <input type="button" name="submit" id="submit" value="Subscribe" onclick="register()"/>
          </p>

    </form>
    <div id="response">
        <!-- Our message will be echoed out here -->
    </div>
</body>
</html>

submit_data.php

<?php 

        // Variables 

                $db_host = 'localhost'; 
                $db_user = 'user'; 
                $db_pass = 'pass'; 
                $db_name = 'db'; 

        $Username = $_POST['username']; 
        $Email    = $_POST['email'];     

        // DB 

        $connect = mysql_connect( $db_host, $db_user, $db_pass ) or die( mysql_error() ); 
        $connection = $connect; 

        mysql_select_db( $db_name, $connect ) or die( mysql_error() ); 

        // Inserting into DB 

        $qInsertUser = mysql_query(" INSERT INTO `database` (`id`, `username`, `email`) 
                                     VALUES ( ``, `$Username`, `$Email`) 
                                  "); 

        if ($qInsertUser){ 
            echo "You are now subscribed to our newsletter. Thank you!"; 
        } else { 
            echo "Error!"; 
        } 

    ?>
JapanPro