I have made Ajax calls before, and let them return JSON objects, which worked, but I dont seem to get it working anymore.
This is my ajax call:
function sendContactForm() {
var nameInput = $('#nameInput').val();
var emailInput = $('#emailInput').val();
var subjectInput = $('#subjectInput').val();
var msgInput = $('#msgInput').val();
$.ajax({
// Make a POST request to getfile
url: "/service/contactmail",
data: {
nameInput: nameInput,
emailInput: emailInput,
subjectInput: subjectInput,
msgInput: msgInput
},
method: "post",
// And run this on success
success: function (data) {
if (data.send === 1){
// VERZONDEN
}else if(data.send === 2){
// VARS NIET INGEVULT
}else{
// IETS ANDERS FOUT
}
console.log(data);
},
error: function () {
alert("fout");
}
});
}
and this is my php function:
private function sendContactForm() {
$output = array(
"test" => null,
"send" => null
);
if ($this->fillVariables()) {
$this->sendMail();
$output['send'] = 1;
return true;
} else {
$output['send'] = 2;
return false;
}
header("Content-Type: application/json");
echo json_encode($output);
}
but the variable "data" has a value of: "" (empty string) There are no other echo's in my php class, so that should not be the problem.
Thanks in advance,
Mats de Waard
asked Apr 1, 2016 at 9:19
Mats de Waard
1393 silver badges16 bronze badges
1 Answer 1
The return's in your if statements are stopping the execution of this function before you can generate the result back to the page.
private function sendContactForm() {
$output = array(
"test" => null,
"send" => null
);
if ($this->fillVariables()) {
$this->sendMail();
$output['send'] = 1;
//return true;
} else {
$output['send'] = 2;
//return false;
}
header("Content-Type: application/json");
echo json_encode($output);
}
answered Apr 1, 2016 at 9:27
RiggsFolly
94.7k22 gold badges108 silver badges152 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Mats de Waard
Oh my god. I feel stupid. Sorry for the nooby mistake, and I think I need to take a break :P Thanks for the help!
RiggsFolly
We have all been there pal. Dont let it worry you.
default
returnfrom inside the if's and then it will get to the header and the echo of your results. Currently it never gets to execute anything after thereturnpublic