Undefined value for response.message in AJAX - php

I'm trying to display response.message as content to a tag with id test. It's getting displayed as undefined.
success:function(response){
console.log("response"+response); // works
var msg = response.message;
if(response.status=="success"){
console.log("response1"+msg);
document.getElementById('test').innerHTML = msg; //undefined
} else {
jQuery('#test').contents(msg);
document.getElementById('test').innerHTML = msg; //undefined
}
}

The way I normally handle this is parsing the JSON response for it to be made into a JavaScript object (Using JSON.parse), try this code below.
success: function(response) {
console.log("response" + response);
response = JSON.parse(response);
var msg = response.message; // works
if (response.status == "success") {
console.log("response1" + msg); // prints/works
document.getElementById('test').innerHTML = msg; //undefined
} else {
jQuery('#test').contents(msg);
document.getElementById('test').innerHTML = msg; //undefined
}
}
Alternatives
You should also be able to set the content type on the PHP page itself before the output using headers
header("Content-type:application/json");
You can also set the datatype to json in your ajax call which is pretty standard
$.ajax({
type: "POST",
url: "",
dataType: "json",
success: function(msg) {
//process success
}
...
});

The undefined isn't msg, the undefined is probably being return from document.getElementById('test').

Related

PHP JSON not returning value from php function

Say I have a function as following. alert_danger returns the error message in red box. check_empty checks if a value posted from form is empty or not.
function alert_danger($msg){
$alert = "<div class='alert alert-danger' id='responseBox'>".$msg."</div>";
return $alert;
}
function checkEmpty($postValue, $msg){
if($postValue == null){
echo alert_danger($msg);
exit();
}
}
Now when I want to return the function value using jSON it's not returning the same. The following error is occuring:
// It returns this
$msg = alert_danger("Ah! Hello Adventurer, and welcome to the town of Honeywood!");
echo json_encode(array('status' => $msg));
// But it does not returns this
$msg = checkEmpty($state, "Ah! Hello Adventurer, and welcome to the town of Honeywood!");
echo json_encode(array('status' => $msg));
What seems to be the problem here?
Here is my jQuery if needed!
$(".action").click(function() {
var form = $(this).closest("form");
var type = form.find(".type").val();
var dataString = form.serialize();
var btnValue = $(".action").html();
var btnElement = $(".action");
var url = form.attr("action");
$.ajax({
type: "POST",
dataType : "json",
url: url,
data: dataString,
cache: true,
beforeSend: function(){
$('.message').hide();
$(".overlay").show();
$(".wickedpicker").hide();
btnElement.html('Please wait...');
},
success: function(json){
$('.message').html(json.status).fadeIn();
// $('#content').html(json.result).fadeIn();
$(".overlay").hide();
$("html, body").animate({ scrollTop: $(".message").offset().top }, "slow");
btnElement.html(btnValue);
if(type == 'admin'){
if($('.message').find('#responseBox').hasClass('alert-success')){
setTimeout(function(){
$(".overlay").hide();
window.location.replace("dashboard.php");
}, 1000);
}
}
}
});
return false;
});
Consider the following.
PHP
<?php
function checkEmpty($postValue, $msg){
return $postValue == null ? array("status" => "error", "message" => "Empty Value") : array("status" => $postValue, "message" => $message);
}
header('Content-Type: application/json');
echo json_encode(checkEmpty($state, "Ah! Hello Adventurer, and welcome to the town of Honeywood!"););
?>
JavaScript
function redirectTo(url, time) {
if (!url) {
return false;
}
time = time != undefined ? time : 0;
setTimeout(function() {
window.location.href = url;
}, time);
}
$(".action").click(function() {
$(this).closest("form").submit();
});
$("form").submit(function(event) {
event.preventDefault();
var type = $(this).find(".type").val();
var dataString = $(this).serialize();
var btnValue = $(".action").html();
var btnElement = $(".action");
var url = $(this).attr("action");
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: dataString,
cache: true,
beforeSend: function() {
$('.message').hide();
$(".overlay").show();
$(".wickedpicker").hide();
btnElement.html('Please wait...');
},
success: function(json) {
if (json.status == "error") {
$(".message").html("<div class='alert alert-danger error'>" + json.message + "</div>").fadeIn();
} else {
$('.message').html("<div class='alert alert-danger'>" + json.message + "</div>").fadeIn();
$("html, body").animate({
scrollTop: $(".message").offset().top
}, "slow");
btnElement.html(btnValue);
if (type == 'admin') {
if ($('.message').find('#responseBox').hasClass('alert-success')) {
redirectTo("dashboard.php", 1000);
}
}
}
}
});
return false;
});
Typically, it is bad practice to use language X to generate code in language Y. Try decoupling the two languages by making data their only interface -- don't mingle the code.
https://softwareengineering.stackexchange.com/questions/126671/is-it-considered-bad-practice-to-have-php-in-your-javascript
You have to be careful to not confuse echo and return, they do very different things.
https://www.php.net/manual/en/function.echo.php
https://www.php.net/manual/en/function.return.php
Since you're passing back JSON data to the AJAX Call, I would advise wrapping your HTML inside the callback versus sending it back inside the JSON.
I think you should take a look at your success function. I think it normally runs before the page loads. So, its possible none of the html your referencing in there exists yet. So move it out to a function like this:
success: function(json) {
doSomething();
}
function doSomething(json){
$( document ).ready(function() {
console.log('page has loaded now modify your html with jquery'+json);
}
}

Save Ajax JQuery selector in an array

I'm very new with Ajax and I need help to store the data from an Ajax request into an array. I looked at answers here at the forum, but I'm not able to solve my problem.The Ajax response is going into $('#responseField').val(format(output.response)) and I'm want store "output.response" into an array that can be used outside of the Ajax. I tried to declare a variable outside of the Ajax and call it later, but without success. I'm using $json_arr that should get the data. How do I do to get the data from the Ajax and store it in a variable to be used outside of the Ajax? This variable will an array that I can access the indexes.
function sendRequest(postData, hasFile) {
function format(resp) {
try {
var json = JSON.parse(resp);
return JSON.stringify(json, null, '\t');
} catch(e) {
return resp;
}
}
var value; // grade item
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) { //data= retArr
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
data = $.parseJSON(output.response)
$json_arr=$('#responseField').val(format(output.response));
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
}
window.alert($json_arr);
let promise = new Promise(function(resolve, reject) {
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) { //data= retArr
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
data = $.parseJSON(output.response)
resolve(format(output.response));
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
});
promise.then(
function(result) { /* you can alert a successful result here */ },
function(error) { /* handle an error */ }
);
The issue is you are calling asynchronously.
You call the alert synchronously, but it should be called asynchronously.
A little snippet to help you see the difference:
// $json_arr initialized with a string, to make it easier to see the difference
var $json_arr = 'Hello World!';
function sendRequest() {
$.ajax({
// dummy REST API endpoint
url: "https://reqres.in/api/users",
type: "POST",
data: {
name: "Alert from AJAX success",
movies: ["I Love You Man", "Role Models"]
},
success: function(response){
console.log(response);
$json_arr = response.name;
// this window.alert will appear second
window.alert($json_arr);
}
});
}
sendRequest();
// this window.alert will appear first
window.alert($json_arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Ajax query, php file is getting read but can't enter success function

so I have the following code that is calling a CheckEmail2.php. I know what I want to do in CheckEmail2.php but because my Ajax success is not working, I have minded the scope to just return a Json. below is my java script. When I launch my console, I see my string coming through that I am echoing in my CheckEmail2.php. so I know my php file is getting read but why won't my success function hit if my string is getting read? I can't get my success function to get called. It always goes to error.
<script type="text/javascript">
function validateForm(){
var email = document.forms["signupform"]["email"].value;
var result = false;
if (email != ""){
$.ajax({
type: "POST",
url: "/CheckEmail2.php",
data: { "User_Email": email },
dataType: "json",
success: function(resp){
console.log(resp);
if(resp == "Not Found"){
result = true;
}
else
{
result = false;
}
},
error: function(data, status){
console.log(data, status);
}
}); //end Ajax
}
return result;
}
</script>
here is my PHP
<?php
header("Content-type:application/json");
echo json_encode("Not Found");
?>
why is error always getting called?

Get JSON responce from ajax call to PHP script

I have been successful in returning the json responce from the ajax call to my php script that sends messages. When submitting data to the PHP script, if successful it should return a json string like the following...
{"status":"valid","message":"Your message was send successfully."}
I would like to check if the "status" equals valid and then show a div showing that the message has been sent. How would i go about doing this and this is the code i have so far...
$("#send").click(function() {
var complete = true;
$('input#fullname, input#email, input#subject, textarea#message').each(function() {
if ($(this).val()) {
$(this).css("background","#121212").css("color","#5c5c5c");
} else {
$(this).css("background","#d02624").css("color","#121212");
complete = false;
}
});
if (complete == true){
var name = $("input#fullname").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
var data = 'name='+name+'&email='+email+'&subject='+subject+'&message='+message;
$.ajax({
type:"POST",
url:"resources/includes/contact.php",
data:data,
success:function(data){
alert(data);
}
});
}
});
Thanks,
Nathaniel Blackburn
you can do it like this
$.ajax({
type:"POST",
url:"resources/includes/contact.php",
data:data,
dataType: 'json',
success:function(response){
if(response.status="valid"){
......
}
}
});
In your success callback function, add
data = $.parseJSON(data);
if (data.status == "valid"){
//do stuff
}
change your success function to look like this:
success:function(data)
{
jsonObject = JSON.parse(data);
alert(jsonObject.status);
}

How to return an error callback in php?

I was wondering if I can return an error callback back to my jquery from my php page that I created, which will then display an alert based upon the actions that happen in my php page. I tried creating a header with a 404 error but that didn't seem to work.
Sample JQuery Code:
$(document).ready(function()
{
var messageid= '12233122abdbc';
var url = 'https://mail.google.com/mail/u/0/#all/' + messageid;
var encodedurl = encodeURIComponent(url);
var emailSubject = 'Testing123';
var fromName = 'email#emailtest.com';
var dataValues = "subject=" + emailSubject + "&url=" + encodedurl + "&from=" + fromName + "&messageID=" + messageid;
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
url: 'http://somepage.php',
success: function(){
alert('It Was Sent')
}
error: function() {
alert('ERROR - MessageID Duplicate')
}
});
return false;
});
});
Sample PHP Code aka somepage.php:
<?php
include_once('test1.php');
include_once('test2.php');
if(isset($_GET['subject']))
{
$subject=$_GET['subject'];
}
else
{
$subject="";
}
if(isset($_GET['url']))
{
$url=$_GET['url'];
}
else
{
$url="";
}
if(isset($_GET['from']))
{
$from=$_GET['from'];
}
else
{
$from="";
}
if(isset($_GET['messageID']))
{
$messageID = $_GET['messageID'];
}
else
{
$messageID="";
}
$stoqbq = new test2($from, $messageID);
$msgID = new stoqbq->getMessageID();
if($msgID = $messageID)
{
header("HTTP/1.0 404 Not Found");
exit;
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new test1($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
}
?>
-EDIT-
If you get the invalid label message when using json this is what I did to fix this problem:
Server Side PHP Code Part-
if($msgID == $messageID)
{
$response["success"] = "Error: Message Already In Quickbase";
echo $_GET['callback'].'('.json_encode($response).')';
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new SendToQuickbase($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
$response["success"] = "Success: Sent To Quickbase";
echo $_GET['callback'].'('.json_encode($response).')';
}
Client Side JQuery Part-
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
cache: false,
contentType: "application/json",
dataType: "json",
url: "http://somepage.php?&callback=?",
success: function(response){
alert(response.success);
}
});
return false;
});
You can a return a JSON response from your PHP with a success boolean.
if($msgID = $messageID)
{
echo json_encode(array('success' => false));
}
else
{
$userID = $stoqbq->getUser();
$stoqb = new test1($subject,$url,$messageID,$userID);
$stoqb->sendtoquickbase();
echo json_encode(array('success' => true));
}
and in your Javascript:
$.ajax({
type: 'GET',
dataType: 'json',
data: dataValues,
url: 'http://somepage.php',
success: function(response){
if(response.success) {
alert('Success');
}
else {
alert('Failure');
}
}
});
There is an accepted q/a with the same thing: How to get the jQuery $.ajax error response text?
Basically you need to grab the response message from the error callback function:
$('#myForm').submit(function(){
$.ajax({
type: 'GET',
data: dataValues,
url: 'http://somepage.php',
success: function(){
alert('It Was Sent')
}
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
return false;
});

Categories