views:

28

answers:

4

I think this is easy, but I'm not sure what the right syntax is. I am posting a form via JQuery ajax - you know

    $j.ajax({ 
    type: "post", etc.....

But I need to make sure the form is capable of being processed if Java is disabled. Is there a "header" in the ajax send that can be used to identify it as aposed to a normal post so that on completion whether ajaxed or normal php post I can return to the sending page. If not ajaxed I can use if($update): header('location: ...'); endif; but if I use that with the ajax request it stops the ajax success function. Hope makes sence

A: 

Don't really know about the headers, but maybe the easier solution is to simply call the url of the processing page with an extra parameter when you're doing it in an ajax context?

The page can then simply check if the parameter is present or not and take appropriate action, depending on it.

Sam
Thanks Sam thought of that one as it's obvious, just wondered if tere was a "cleaner" way to do it
Please see my answer. There is no need to set an extra parameter
Razor
A: 

You'll have to do a lot or working around, but you can use a combination of <noscript> and javascript code to get what you need.

See WWW FAQs: How do I detect JavaScript in the user's browser?

Hope that helps you get started.

Codesleuth
A: 

Yes, jQuery sets a custom header when doing an AJAX request:

X-Requested-With : XMLHttpRequest

EDIT russp's server side PHP code:

define('IS_AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
    strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if( IS_AJAX_REQUEST )
    { //This is an AJAX request, do AJAX specific stuff }
else
    { //This is not an AJAX request }
Razor
Thanks Razor, but any reason why if($_SERVER['X-Requested-With']=='XMLHttpRequest'): does not work?
Hi again Razor - got it .... me being thick as usual. Here is a useful "piece" for others will accept your answer, but here is a bit of code: define('IS_AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) if(IS_AJAX_REQUEST) { //This is an AJAX request, do AJAX specific stuff}else { //This is not an AJAX request }
A: 

The usual way to handle ajax form requests is to write the form to work without any kind of JS so if you are in a basic php file you would start with

<?php
if(count($_POST) > 0) {
    //process form entries
} else {
    //output form
}
?>

Then you would add some jQuery to hijack the submit click so

$('input[type=submit]').live("click", function(e) {
     e.preventDefault();

     //ajax post here

     //IE
     return false;
});
MRW