Reminder : $.ajax() – Passing variables with Ajax and PHP using JQuery

1. Create ajax.php

<?php

if ($_SERVER[‘REQUEST_METHOD’] === ‘POST’) { //Check if method used is GET or POST 🙂
$n1 =$_POST[‘newvar1′].’ welcome to php’;
$n2 =$_POST[‘newvar2’] + 20500;
$n3 =$_POST[‘newvar3′].’ goodbye to php’;
}else{
$n1 =$_GET[‘newvar1′].’ welcome to php’;
$n2 =$_GET[‘newvar2’] + 20500;
$n3 =$_GET[‘newvar3′].’ goodbye to php’;
}

echo $n1.’-‘.$n2.’-‘.$n3;   //this will be returned as data to the ajax calling function

?>

2. Create html

<html>
<head>
</head>

<body>
<div id=”d1″></div>
<div id=”d2″></div>
<div id=”d3″></div>

<a href=”#” onclick=”javascript:run_ajax()”>Click Me to Run Ajax</a>
</body>
</html>

3. Create the javascript within your html file.<head>
<title>Testing JQuery</title>
<script type=”text/javascript” src=”js/jquery-1.9.1.js”>
</script>

<script type=”text/javascript”>

function run_ajax() {
$.ajaxSetup({
//”type”:”POST”,
“url”:”ajax.php”,
“success”:function(data) {
test_ajax(data);
}
});

$.ajax(
{    “type”:”GET”,
“data”:{
“newvar1″:”new Value 1”,
“newvar2”: 10000,
“newvar3″:”new Value 3”
}
}
);
}

//This function will distribute the datas returned
//to the div(s) (d1,d2,d3)

function test_ajax(data) {
var n=data.split(“-“);
for(i=0;i<n.length;i++) {
$(‘#d’+(i+1)).text(n[i])
.css({‘width’:’200px’,’border’:’1px solid black’});
}
}
</script>
</head>

//THEN CLICK on “Click Me to Run Ajax” Link to RUN

ajaxtest

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Up ↑

%d bloggers like this: