Tag Archives: ajax

The New Ajax

Okay, as a developer, I've been using Ajax for years. To be honest, it gives me a new ulcer every time I have to use it. Well, it still does lol, but not quite as bad. Today Ajax technology mixed with jQuery makes it almost tolerable to code with. Also, what's important, is that it is a very necessary technique if you want to go anywhere at all with your coding skills. Let me demonstrate how to make it easier for everyone. It is not really that hard if you break it down into the simplest form possible and then expand from there. Here is a simple Ajax call to get the results of a PHP script:

Update - I've decided to expand this article to include just about every way possible to send data to a PHP script and get a response, so I've include the JavaScript/Ajax method, the jQuery/Ajax method and the CURL method of sending data to a PHP script and getting back other data or manipulated data.

Simple JavaScript Ajax call to PHP script:

<!DOCTYPE html>
<html>
<head>
<script>
function get_txt(){
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }else{// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function(){
  if (xmlhttp.readyState==4 && xmlhttp.status==200){
    var returnval=xmlhttp.responseText;
alert(returnval);
    }
  }
xmlhttp.open("GET","phpscript.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<input type="button" value="TEST" onclick="get_txt()" />
</body>
</html>

The above Ajax example will only retrieve data from the declared file. It could be altered to send data to it and receive a response, but I'm saving that gem for my next example using jQuery and Ajax to send a variable to a PHP file and get back a response.

Simple jQuery Ajax call to PHP Script that Returns Data:

The following jQuery and Ajax script will send the "user" variable holding the text "Ian" to the PHP script which will read the "user" variable with $_POST['user'] and send the results of the PHP code back to the Ajax script!

<script type="text/javascript" src="jquery.js"></script>
<div id="status"></div><hr>
<div id="rez"></div>
<script>
//var $j = jQuery.noConflict();//use j. instead of $ if needed

$.ajax({               
    type: "POST", // the kind of data we are sending
    url: "update_scores.php", // this is the file that processes the form data
    data: {user:'ian'}, // this is our serialized form-like data to pass to php
    success: function(msg){    // this function runs when the data has been successfully processed
        // this sets up our notification area for error / success messages
        $( document ).ajaxComplete(function( event,request, settings ) {
            $( "#status" ).append( "<p>Request Complete.</p>" );
            preresult = msg;
            $( "#rez" ).append( "<p>"+msg+"</p>" );
        });
            

    }
});
</script>

Sending Data to a PHP script and getting a response using CURL

Note that you could use CURL to do the same thing still using:

        $data = array('username' => 'ian');
        $results= curlPost('http://www.jafty.com/job.php', $data);

function curlPost($url, $data){
// check for URL and data:
    if(empty($url)){
        return 'Error: missing URL';
    }
    if(empty($data)){
        return 'Error: missing Data';
    }
//get the data for the POST and put in URL:
$fields_string = '';
foreach($data as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
$fields_string = rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//Set the URL, no. of POST vars and POST data:
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($data));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//timeout after 10 secs(change as needed):
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,10);
//curl_setopt($ch,CURLOPT_HEADER,false);
//Set to return data instead of printing:
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
//pass user agent:
curl_setopt($ch,  CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//execute post:
$result = curl_exec($ch);
//close connection:
curl_close($ch);
return $result;
}//end curlPost function

...to pass a variable to a PHP script and save the PHP script's results in $results.

Simple Ajax Example

Here is a simple Ajax example to grab a value from a PHP file. The same method would be used for a .txt file or a json request value.

JavaScript Code:

function get_txt(){
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }else{// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function(){
  if (xmlhttp.readyState==4 && xmlhttp.status==200){
    var returnval=xmlhttp.responseText;
alert(returnval);
    }
  }
xmlhttp.open("GET","phpscript.php",true);
xmlhttp.send();
}

PHP Code:

<?php

echo "This text came from a PHP file!";

?>

To test, simply save the JavaScript code in an HTML file in the header and save the PHP code in a PHP file named phpscript.php. Then add the following button in the body of the HTML file:

<input type="button" value="TEST" onclick="get_txt()" />