Jump to content

Ajax Post Examples?


Guest FirefoxRocks

Recommended Posts

Guest FirefoxRocks

I am trying to use AJAX in my application, but mostly I can only examples of using AJAX to request information from XML, databases, etc. I would like to know how to use AJAX to post something (e.g. a comment to an article).I have tried using AJAX post before but 2 problems arise:

  1. The page still refreshes even with the blank action attribute.
  2. It doesn't work half the time even when I clear the cache.

Can anyone get me some example code so I can see what I'm supposed to do?

Link to comment
Share on other sites

Guest FirefoxRocks

Ok I understand the bottom 2 functions. Then there's this function:

function sendRequest(url,callback,postData) {  var req = createXMLHTTPObject();  if (!req) return;  var method = (postData) ? "POST" : "GET";  req.open(method,url,true);  req.setRequestHeader('User-Agent','XMLHTTP/1.0');  if (postData)	req.setRequestHeader('Content-type','application/x-www-form-urlencoded');  req.onreadystatechange = function () {	if (req.readyState != 4) return;	if (req.status != 200 && req.status != 304) {	  //alert('HTTP error ' + req.status);	  return;	}	callback(req);  }  if (req.readyState == 4) return;  req.send(postData);}

I get to the method variable and I'm totally lost. Can someone explain how this function works to post data?

Link to comment
Share on other sites

It's an all-purpose function, so it needs to work if there is data to post, and also if there is no data. It needs to work if the programmer wants to use the GET method or the POST method. So you're getting lost in all the conditionals.Do you understand the ternary (conditional) operator?var method = (postData) ? "POST" : "GET";This statement works like this. If a value has been assigned to postData, set method equal to "POST"; otherwise, set method equal to "GET".The function also sets some headers. This is one of justsomeguy's functions, so you he'll be thorough.req.setRequestHeader('User-Agent','XMLHTTP/1.0');You can survive without a User-Agent header, but this function sends one anyway, and doing so is easy, so why not?req.setRequestHeader('Content-type','application/x-www-form-urlencoded');The W3C strongly recommends sending a content header if you are using the POST method to send data. So this function checks for data and sets that header also. In my experience, servers get upset if they do NOT get that header, so treat this as a requirement.AJAX needs a a callback function to respond when data comes back from the server. This gets assigned to onreadystatechange.req.onreadystatechange = function () { // etc.JSG's function handles this in two parts. The first part is an anonymous function that checks for server errors. Then it calls a callback function (called callback) that you must specify when you call sendRequest(). So you need to create a callback function in your script, and it must be prepared to receive a XMLHTTPObject. But it does not have to check the ready state or check for errors.

Link to comment
Share on other sites

Guest FirefoxRocks

Ok now I understand the question mark operator. What is a callback function? Is that the part where you put the document.getElementById('blah').innerHTML = "Request successful"; ?

Link to comment
Share on other sites

A callback is whatever you want to run when the response comes back from the server. You either give it the name of a function you already defined:

function handle_response(resp){  document.getElementById('blah').innerHTML = "Request successful";}sendRequest(url, handle_response, data);

or you can also give it an anonymous inline function:

sendRequest(url, function(resp){  document.getElementById('blah').innerHTML = "Request successful";}, data);

Link to comment
Share on other sites

Guest FirefoxRocks

Ok I think I get it now. Does the resp variable in your example above contain whatever data you requested? If so, what will it contain if I posted information (e.g. a comment) to the server/database?This is because the main goal is to post information, not get information. I will use AJAX GET somewhere else probably, but I'm having trouble with the POST part.

Link to comment
Share on other sites

If you look at this section of JSG's code:

function sendRequest(url,callback,postData) {  var req = createXMLHTTPObject();  ...  callback(req);  ...}

you'll see that the function calls your specified callback function and passes it a reference to the XMLHttpRequest object.So, in the case of the examples provided in this post, you can do this:

function handle_response(resp){  document.getElementById('blah').innerHTML = resp.responseText;}sendRequest(url, handle_response, data);

Link to comment
Share on other sites

If you want to examine resp to see everything it contains, load up Firebug and use console.log to inspect it in the debug console:

function handle_response(resp){  console.log(resp);  document.getElementById('blah').innerHTML = resp.responseText;}

You'll be able to see all of the properties of the resp object and what data they contain. If you're only worried about submitting, then the response will probably only be useful for error checking. You can validate your data on the server and send back an error if something happened, and check for the error in Javascript. e.g.:

<?php$data = $_POST['data']; // whatever your post var is calledif ($data == ''){  echo 'The data was empty';  exit();}// do database stuff or whateverecho 'success';exit();?>

function handle_response(resp){  if (resp.responseText != 'success')	alert(resp.responseText);}

Link to comment
Share on other sites

the main goal is to post information, not get information. I will use AJAX GET somewhere else probably, but I'm having trouble with the POST part.
Depending on your application, you'll still want some notification that the PHP operation succeeded, even if all you're returning is a "1" or a "0". mysql errors in particular do not generate a server error, so req.status can be 200 even when things went bad. (You already know that. I'm just showing how it works in the AJAX context.) If your user expects something to happen, and it doesn't, your user may need to know.You should also get in the habit of sending back a message if the POST values don't make it through your filters (e.g., someone is trying to crack your system).
Link to comment
Share on other sites

Guest FirefoxRocks

Somehow my data isn't posting. Firebug and Safari do not report any JavaScript errors. Here are my 3 test pages:TEST_AJAX.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html lang="en-CA" dir="ltr"><head>	<title>Test AJAX</title>	<script type="application/javascript" src="TEST_AJAX.js"></script></head><body>	<h2>Testing AJAX POST</h2>		<div><textarea rows="10" cols="72" id="commentFor"></textarea></div>		<p id="url"></p>	<p id="postData"></p>	<p id="method"></p>	<p id="status"></p>		<p><a href="java script:sendRequest('post.php',handleRequest,'some text');">Post the data</a></p></body></html>

post.php

function sendRequest(url,callback,postData) {	/*DEBUG*/ document.getElementById("url").innerHTML = "<strong>URL to send to:</strong> " + url;	/*DEBUG*/ document.getElementById("postData").innerHTML = "<strong>Data:</strong> " + postData;		var req = createXMLHTTPObject();	if (!req) return;	var method = (postData) ? "POST" : "GET";	/*DEBUG*/ document.getElementById("method").innerHTML = "<strong>Method:</strong> " + method;		req.open(method,url,true);	req.setRequestHeader('User-Agent','XMLHTTP/1.0');	if (postData)		req.setRequestHeader('Content-type','application/x-www-form-urlencoded');	req.onreadystatechange = function () {		if (req.readyState != 4) return;		if (req.status != 200 && req.status != 304) {//			alert('HTTP error ' + req.status);			return;		}		handleRequest(req);	}	if (req.readyState == 4) return;	req.send(postData);}var XMLHttpFactories = [	function () {return new XMLHttpRequest()},	function () {return new ActiveXObject("Msxml2.XMLHTTP")},	function () {return new ActiveXObject("Msxml3.XMLHTTP")},	function () {return new ActiveXObject("Microsoft.XMLHTTP")}];function createXMLHTTPObject() {	var xmlhttp = false;	for (var i=0;i<XMLHttpFactories.length;i++) {		try {			xmlhttp = XMLHttpFactories[i]();		}		catch (e) {			continue;		}		break;	}	return xmlhttp;}function handleRequest(req) {	var writeroot = document.getElementById("status");	writeroot.innerHTML = "<strong>$_POST Array: (server response)</strong> " + req.responseText;}

The data gets to the function but doesn't get sent to the server for some reason.

Link to comment
Share on other sites

The data gets to the function but doesn't get sent to the server for some reason.
Are you sure? You can also use Firebug to look at AJAX requests, the Net tab will show you every request going out and the response, including headers. You can also use PHP to write information to log files. You can use file_put_contents, or if you set the error handling to use an error log you can use the error_log function to write whatever you want to it.
Link to comment
Share on other sites

Guest FirefoxRocks
Are you sure? You can also use Firebug to look at AJAX requests, the Net tab will show you every request going out and the response, including headers. You can also use PHP to write information to log files. You can use file_put_contents, or if you set the error handling to use an error log you can use the error_log function to write whatever you want to it.
Ok now I see that the data is sent to the server, but the server isn't doing anything with it (it isn't in the $_POST superarray for some reason).With the code I have above, what is the POST variable called that contains the text "some text"?
Link to comment
Share on other sites

You didn't set up your data to be read into the $_POST array correctly. You need to create a data string that would look just like a GET string:val1 = encodeURIComponent(val1); val2 = encodeURIComponent(val2); my_data = "key1=" + val1 + "&key2=" + val2;sendRequest('post.php', handleRequest, my_data);Now look for your data in $_POST['key1'] and $_POST['key2'].What you need to do in AJAX, in other words, is to duplicate the steps your browser would take if it were preparing form data.

Link to comment
Share on other sites

Guest FirefoxRocks

I tried a slightly different method using your information and it worked!! Here is my HTML code:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html lang="en-CA" dir="ltr">	<title>Test AJAX</title>	<script type="application/javascript" src="TEST_AJAX.js"></script>	<script type="text/javascript">	function safeInput() {		comment = document.getElementById("cf").value;		var safeComment = escape(comment);				return safeComment;	}	</script>	<h1>Testing AJAX POST</h1>		<div><textarea rows="10" cols="72" id="cf"></textarea></div>	<input type='hidden' id='cid' value='3'>		<p id="url"></p>	<p id="postData"></p>	<p id="method"></p>	<p id="status"></p>		<p><a href="java script:sendRequest('post.php','txt='+safeInput()+'&cid='+document.getElementById('cid').value);">Post the data</a>

.Gosh it would be nice for a live working example to be posted somewhere along with the code.

Link to comment
Share on other sites

Guest FirefoxRocks

Now that I have worked with this more, I find that it is unreliable for some reason. Sometimes it triggers the blank text error (nothing goes through), but sometimes it posts 2 times.I know Facebook uses AJAX to post content on walls, comment on wall posts, photos, videos, etc. I have seen comments being posted 3 times, but that was only once (extremely rare). Other errors include "Transport error", which was my Internet connection.My application works properly less than half the time with these errors. How do I prevent them?

Link to comment
Share on other sites

Guest FirefoxRocks

Well, sometimes when I click "Post", Firebug shows that nothing goes through even though there is text in the textbox.

Link to comment
Share on other sites

If it's not going through at all, you probably need to add some debugging in the sendRequest function. Check things like the XHR object is getting created, and check the readyState and status properties before and after trying to send the request.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...