views:

65

answers:

2

Hello,

I am trying to use jquery to do a client side validation to do a check and return with a error or success.

I know how to echo text/html back as the response, but here's what I am trying to do.

On Error, send back a message, so the user can re-submit a form. On Success, re-load the page.

I am not sure how to get it to send a variable which I think will let me do either condition in jquery.

Any suggestions??

+1  A: 

Check out the documentation, http://api.jquery.com/jQuery.ajax/ you will find a success and error option which you provide a function to be called when the request is successful or fails.

$.ajax({
    url: 'ajax/test.html',
    success: function(data) {
        //reload your page
    },
    error: function(data) {
        alert("Resubmit the form!");
    }
});
Flash84x
How do you get your ajax file to go to the error function? I have never seen this before. I thought the error function was only if something happend in between the connection (like the ajax page was missing/wrong). Also, what if there is something wrong with the connection? The user will think the form failed and will not understand whats wrong.
Metropolis
That's what I thought, the error function was if the ajax call was in error, the error I am speaking of is server side validation.
matthewb
I see, I misunderstood your question in that case. I would have the page your are posting to send back a JSON object with the results of what happened on the back end. Then I would have the function defined in the success option handle that JSON object to determine what to do next.
Flash84x
I am not 100% clear on how to do a json object
matthewb
I posted a json example above. Theres really a bunch of ways to do this, I wouldnt say that one is really better than another. They all take about the same amount of code. But json does give you more control over the information passed back from the ajax script.
Metropolis
@matthewb what is language are you using for the backend?
Flash84x
+1  A: 

The javascript could be somthing like this

$.ajax({
    type: 'POST',
    url: ajaxPage,
    data: postContent,
    success: function(response) {
        //Assume that the php failed
    },
    error: function() { alert("Ajax request failed."); }
});

Now in the ajax PHP file you could have this

<?php
    //Check for validation

    if(validation == 'success') {
        header('Location: '.FILE_LOCATION);
    }
    else {
        exit('Form submit failed. Please try again');
    }
?>

Hope this helps! Metropolis

EDIT SINCE NEW INFO

If you would like to use a json object you could do it like the following

<?php
    $response = array('validationStatus' => true);
    exit(json_encode($response));
?>

Its not really a big deal if you use json or not, you can still pass a string back either way. I think json is really better for more complicated data that you need to pass back, but theres probably 10 different ways to do this.

Metropolis