Reputation: 139
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
Upvotes: 1
Views: 909
Reputation: 94642
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);
}
Upvotes: 1