![Creative The name of the picture]()
jQuery post method ignores returned value
I have a form on a site that will either return "invalid email" and reveal a div, or it will be successful, hide the form and reveal a different div. When I console.log the data returned from the form I get a 0 or a 1, 0 being invalid and 1 being success, but when I pass this into an if statement, it is ignored and the "else" statement is triggered. What am I doing wrong?
$("#contact-form").submit(function(e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
$.post("contact_form.php", {
name1: name,
email1: email,
message1: message
}).done(
function(data) {
if (data == "1") {
$("#invalid").hide();
$("#contact-form").fadeOut();
$("#returnmessage").fadeIn();
} else if (data == "0") {
$("#invalid").fadeIn();
} else {
console.log('neither');
}
});
});
HTML is as follows:
<div id="about-form">
<form id="contact-form">
<fieldset>
<input id="name" name="name" placeholder="your name" class="about-input" required="" type="text">
<input id="email" name="email" placeholder="your email" class="about-input" required="" type="text">
<textarea id="message" name="message" placeholder="your message" class="about-input message" required=""></textarea>
<input type="submit" class="about-submit" name="submit" value="Submit" id="submit">
</fieldset>
</form>
<div id="returnmessage">Thanks for your interest! We will get back to you in a jiffy.</div>
<div id="invalid">Invalid Email</div>
data
typeof data
1 Answer
1
include dataType if your respose is string. like:
dataType
$.post(
"contact_form.php",
{
name1: name,
email1: email,
message1: message
},
function(data) {
if (data == "1") {
$("#invalid").hide();
$("#contact-form").fadeOut();
$("#returnmessage").fadeIn();
} else if (data == "0") {
$("#invalid").fadeIn();
} else {
console.log('neither');
}
},
'text'
);
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Use the console to print out
data,typeof datain the ajax callback. Could you please add the html to your question ?– collapsar
19 hours ago