I have a mail.php file that gets called by an ajax script. For completeness, the ajax script is attached below. All the mail.php file does is perform some server-side validation, and if everything passes, sends an email with mail() and the data sent from the ajax request.
What I want to do is perform some additional javascript actions based on the response of the request. You can see that at its current state, the response of the request is simply echo’d to the screen, which is fine. But now I want to modify HTML elements based on the response.
For example, say I want to append an image called “OK” to the page if the mail was sent, and else append an image called “FALSE” to the page if the mail was not sent. What I’d like to do (in pseudocode) is this:
if ( request is OKAY ) $('.contact').append('<img src"OK"');
else ( $('.contact').append('<img src="BAD'');
Is there any way to perform this?
Thanks!
The ajax script is shown below:
$('.submit').click(function() {
$('div.load').html('<img src="images/load.gif" alt="Loading..." id="loading" />');
//creation of variables to send
var name = $('#name').val();
email = $('#email').val();
phone = $('#phone').val();
$.ajax({
url: 'mail.php',
type: 'POST',
data: 'name=' + name + '&email=' + email + '&phone=' + phone,
success: function(result) {
$('p.error,p.correct').remove();
$('.contact').append(result);
$('#loading').fadeOut(500, function() {
$(this).remove();
});
}
});
return false;
});
Assuming your PHP responds with the text “OKAY”:
Or:
An alternative is to update your PHP so that it returns html that includes both a message and the image, e.g., on success it could return:
“I should mention that I’d like to keep the current response there as well to make sure that non-JS users also get the appropriate message”
Non-JS users will not be getting anything because your Ajax code uses JS…