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.;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…