jQuery post method ignores returned value

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>





Use the console to print out data, typeof data in the ajax callback. Could you please add the html to your question ?
– collapsar
19 hours ago




data


typeof data





Added HTML above. The data is a string.
– steve
19 hours ago




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'
);





I'm not sure what this is supposed to achieve, but it doesn't trigger either of the if statements. I changed the last one to console.log(data) and it returns 0, but still (even with your 'text') doesn't trigger the 2nd else if statement.
– steve
1 hour ago






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.

Popular posts from this blog

How to scale/resize CVPixelBufferRef in objective C, iOS

Stripe::AuthenticationError No API key provided. Set your API key using “Stripe.api_key = ”

SVG with two text elements. When one resizes due to textLength - how to resize the other one to the same character size