user3191005
user3191005

Reputation: 41

Using Ajax to return JQuery

I am using Ajax to call a PHP file to process a from on submit. My JQuery form validation checks the values of variables to determine whether or not to submit the form or return false and display the error messages. How can I return a JQUERY variable and value to the current script from my PHP file on success?

My JQuery and Ajax:

$.ajax({  
    type: "POST",  
url: "validate.php",  
data: dataString,
success: // what do I do here? {
    }
});

Do I just output a script on my PHP page and then return the HTML?

Upvotes: 1

Views: 82

Answers (5)

Innovation
Innovation

Reputation: 1534

I will suggest to send back data in the form of JSON and then on html ajax success parse json and get the values.

Upvotes: 0

pathfinder
pathfinder

Reputation: 1786

You can also return something as simple as "yes" or "no" as html and deal with it that way if you don't want to monkey with json for a simple response. I find json to be buggy and cause me a lot of unnecessary errors at times and why go through a rigamarole if you just need to know yes or no.

$.ajax({
    dataType: 'html',
    type: 'POST',
    data: {formfieldname:formvalue,formfieldname2:formvalue},
    success: function(data){
        if(data == 'yes') {
        // do your success stuff
        }
        else {
        // do your error stuff
        }
    }
});

Upvotes: 1

podperson
podperson

Reputation: 2383

I'm not sure what you think a "JQUERY" variable is. Do you mean JSON?

Assuming you want to send JSON and receive JSON, you would call:

$.ajax({
    dataType: 'json',
    type: 'POST',
    data: data_object, // not string!
    success: function(data){
        // data will be the json data returned by your PHP script
    }
});

In the simple case, in PHP you'd call jsonencode on a PHP array to convert the PHP array to JSON.

e.g. (PHP)

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));

See this answer:

PHP returning JSON to JQUERY AJAX CALL

Upvotes: 1

qqfish
qqfish

Reputation: 201

$.ajax({  
type: "POST",  
    url: "validate.php",  
    data: dataString,
    //you can use json data, it will be easier to tranfer complex data
    dataType: "json",
    success: function(data) {
        //the data will contain the return result
        //for example you have an error message in following format
        //{error:'some error has been occured'}
        if(data.error)
             alert(data.error);
    }
});

Upvotes: 3

tenub
tenub

Reputation: 3446

Your PHP will read the data and you can access it within $_POST. Your script will do something with this data and return some sort of data of its own. You can and should return valid json for your success function to be useful by using json_encode. This is accessible if you write a callback function under: success: function(data) { // do something with data }

Upvotes: 0

Related Questions