Sven
Sven

Reputation: 13275

Ajax form: Fallback styling

I have an Ajax form. Now I want to supply a solid fallback if the user has JavaScript deactivated.

So far it works also without JavaScript, but the user then simply sees the JSON string as a result printed on blank white without styling because of

echo json_encode( $arr );

How do I add styling to this? Do I have to echo a whole HTML page? Is it possible to enable a redirect for JS disabled or something?

The whole PHP bit looks like this:

if ( !empty( $invalidFieldArray ) ) {     
    // validation errors
    $arr = array( "status" => "error" , "data" => $invalidFieldArray );
    echo json_encode( $arr );      
} else {
    // all ok
    $arr = array( "status" => "success" );
    echo json_encode( $arr );
}

Upvotes: 1

Views: 255

Answers (2)

Alexander
Alexander

Reputation: 23537

HTML and AJAX

You could use a different action URL in your <form> than the one used by AJAX. That way, you can have a normal working <form> fallback which outputs HTML.

X-Requested-With

Or, if you want to use only one URL for both methods, then you can have a look at the X-Requested-With header sent, and identify an AJAX request by checking it against the value XMLHttpRequest.

if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
  /* It's AJAX */
} else {
  /* HTML fallback */
}

Upvotes: 3

Musa
Musa

Reputation: 97672

Try something like

<form action="some.url?js=false"...

set the action with a flag saying there is no JavaScript available

Then use JavaScript to remove it

$('form').attr('action', "some.url");

Then on the server side you can check for $_GET[js] if its not set just echo the json otherwise a full page.

Upvotes: 1

Related Questions