0

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?

4
Contributors
3
Replies
28
Views
1 Year
Discussion Span
Last Post by jacks009
0

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.

0

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");
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.