Forum Moderators: open

Message Too Old, No Replies

JQuery and AJAX - Getting back values

         

realestatesteve

6:59 pm on Dec 24, 2008 (gmt 0)

10+ Year Member



Hi everyone. :)

I have a form that submits via AJAX to a PHP page which enters information into a database.

The result from that PHP page is a message (echo) detailing what happened.

I'm currently using the $('#form')[0].reset(); method to clear the form when ajax comes back as a success, but what if I want that to be conditional?

Example: Person is entering contacts, and if the contact is entered, there is a successful entry and the form is cleared and message displayed.

But what if the person tries to enter a duplicate? I want the echo to say this in the PHP page (I got that fine), but I also want to let JQuery know NOT to reset the page. (I want them to confirm the details before submitting to confirm they want a duplicate entry).

How could I do this?

ashish21cool

6:24 am on Dec 26, 2008 (gmt 0)

10+ Year Member



What u need to do is:

Check the result returned from the JQuery with some conditional operations like if this then this......

What are u using in jquery to send data to the database?

$get,$post or $getjson.

Let me know and i can give you more insights.

Best Regards

realestatesteve

5:26 pm on Dec 26, 2008 (gmt 0)

10+ Year Member



Thanks ashish21cool,
I'm sending the data using the AJAX function like this:

[I set all vars first using the .val() technique, then...]

$.ajax({
url: 'includes/process/add_contact_to_db.php',
type: 'POST',
data: 'firstname=' + firstname + '&lastname=' + lastname + '&phone=' + phone + '&email=' + email + '&address_1=' + address_1 + '&city=' + city + '&state=' + state + '&zip=' + zip,

success: function(result) {
$('#response').remove();
$('div.forms').prepend('<p id="response"><span>' + result + '</p>');
$('#form_add_contact')[0].reset();
$('#loading').fadeOut(500, function() {
$(this).remove();
});
}
});

In the PHP file, I use a prepared statement to add the POST values to the database, and check to make sure there was an affected row in an IF statement.

At the moment, I'm just echoing a string, which is sent back to JQuery as result (see above), but I want to be able to assign a value to a variable, send that back to JQuery, and then use an IF statement inside of JQuery to customize the actions taken on the form. That's possible?

ashish21cool

4:25 am on Dec 27, 2008 (gmt 0)

10+ Year Member



Go like this.
Once you get the values in "result", set it to a variable.
The result returned will be either a Json String or Json object.

a)You can use the following if its a string
u can split it and save it in array.

b) If its an object then do the following:
Use eval function or use json.stringify.

Hope this works for you and then based on the a or b above u can check the values.

Let me know if its still an issue.

Thanks.