Hi all,

Submitting forms to PHP is easy with Ajax. But what if I wanted to design my website to allow for JS-free web browsers?

If I call a PHP file with Ajax, I might get an error message in return to dynamically add to the page, but if I POST data to a PHP form without Javascript, I need to get a whole page of HTML back. Therefore, to allow for both, i would need a way for the PHP code to detect whether a request was an AJAX request or not.

How do I do this?

You can put one more hidden variable in your form. Like type of post

<input type=hidden name=method id=method value=''>

before submitting set appropriate value whether method is post or ajax, same can be captured in your php handler.

Therefore, to allow for both, i would need a way for the PHP code to detect whether a request was an AJAX request or not.

I don't know how you are submitting the ajax requests, but if you are using jQuery, it already contains a header named X-Requested-With which is set to XMLHttpRequest. So, on the server, you should be able to see if the header exists in the $_SERVER variable:

if(array_key_exists('HTTP_X_REQUESTED_WITH',$_SERVER) && 'XMLHttpRequest'==$_SERVER['HTTP_X_REQUESTED_WITH'])
{
  //process ajax request here
}

If you are not using jQuery, then once you have the ajax object call the setRequestHeader() method - ex:

//here xhttp is an instance of the XMLHttpRequest object
xhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");

Very informative post.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.