I am trying to submit a form using jquery and the $.ajax () method. When submitting the information to the server I want only the result to remain and the rest of the page to be hidden. Am I able to add a conditional in the ajax method that states " if(success) then display the result while hiding the h1, h2, and p elements (leaving only the returned text; else if (error) then just display the error message inside my div place holder at the bottom of the page without .hide()-ing any element. So upon success of the ajax method, I want all elements to hide except for the text returned in the div placeholder. If an error occurs (the form is left blank) then display the error message in the div place holder while leaving all elements in place.
UPDATE:
When I use the alerts in my example, they always come out as success. The ajax/jquery is not recognizing my if statements. Any idea what may be going on here?
HTML:
<form id="form" action="form.php">
<label for="name">Name: </label>
<input type="text" id="name" name="name">
<label for="phone">Phone: </label>
<input type="text" id="phone" name="phone">
</form>
<input type="submit" id="clickMe" value="Send" class="clear">
<p id="display"> </p>
jQuery/Ajax
$(document).ready(function() {
$("#clickMe").click(function(event){
event.preventDefault();
var myData = $('#form').serialize();
$.ajax({
url: 'form.php',
data: myData,
success: function (result) {
$('#display').html(result);
if(myData.indexOf("Thank")){
alert("success")
}
},
error: function (xhr, status, error) {
$('#display').html("Error: " + xhr.status + " " + xhr.statusText);
if(myData.indexOf("Something went wrong")){
alert("error");
}
}
});
});
});
PHP
if(!empty($_GET['name'])
echo "Thank you for your messsage ";
else {
echo "Something went wrong.;
}
result
– Taraxacumajax.php
file to doe your validations, or maybevalidate-form.php
file. Just to keep things organized a little bit (always good to do). Don't forget to update in that case yoururl: 'form.php',
tourl: 'validate-form.php',
– TaraxacummyData.indexOf
withresult.indexOf
because myData will only contain the form data submitted by the user, not the result that ajax call gives you back, in your example theresult
parameter is parsed and you can use that to callindexOf
on :) – Taraxacumresult
is by doing a simpleconsole.log(result)
then analyse it in browser console. And then see what's happening. That's what I would do in such situations – Taraxacumsuccess: function (result) {....}
is is always executed upon a successful200 OK
request send back by the server (which is your ajax call). Theerror: function...
part is only fired when the server did not send back a succesfull response e.g: error50x
. There is another callback calledcomplete
which is always fired no matter what :) Hope you understand :) Reference here (which you should definitely read for better understanding): api.jquery.com/jquery.ajax – Taraxacum