ajax response data is undefined - javascript

i have problem with ajax post submit
here is my script
function postad(actionurl) {
if (requestRunning) return false ;
if (! $("#editadform").valid()) {
validator.focusInvalid();
return false ;
}
$('#ajxsave').show() ;
requestRunning = true ;
var postData = $('#editadform').serializeArray();
$.ajax(
{
url : actionurl,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$('#diverrors').html(data.errors) ;
$('#divalerts').html(data.alerts) ;
if (data.status=='success') { alert(data.status);
$('#siteid').val(data.siteid) ;
if ($('#adimager').val())
$('#divlmsg').html(data.alertimage) ;
$('#editadform').submit() ;
} else {
$('#ajxsave').hide() ;
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$('#ajxsave').hide() ;
},
complete: function() {
requestRunning = false;
}
});
$('.btn').blur() // remove focus
return false ;
}
This works on if (textStatus=='success') {
but when the action fails, alert(data.status) shows Undefined.
Using FireBug, I can see that the data is correctly returned. Why is data.status "Undefined" then?

If you don't specify the dataType field of an $.ajax() call in jQuery, it formats the response as plain text. A workaround to your code would be to either include dataType: "JSON" into your $.ajax() parameters, or alternatively, in your success function, parse the plain text response as a JSON object, by using the folllowing:
data = JSON.parse(data); // You can now access the different fields of your JSON object
UPDATE:
yes i have not status field in action url, how to add data status field in php code?
When creating your PHP script that is intended to return the JSON data, you first need to build an array and then encode it as JSON.
So, suppose you have a PHP script that either succeeds and produces some data that you put into a $data variable, or fails, then the following style could be adopted:
<?php
// ^^ Do your PHP processing here
if($success) { // Your PHP script was successful?
$response = array("status" => "success!", "response" => $data);
echo json_encode($response);
}
else {
$reponse = array("status" => "fail", "message" => "something went wrong...");
echo json_encode($response);
}
?>

Related

My AJAX function keeps getting error as result

I'm new using AJAX or jQuery and I'm trying to insert some data in a table whitout loading another page, I can't tho.
Here is my AJAX func:
Edit:
function SumbitAction(act_id) {
$.ajax({
dataType: 'json',
type: "POST",
url: 'Accion.php',
data: {Action:act_id},
success: function (obj, textstatus) {
if(obj.status==='FAIL') {
console.log(obj.message);
}
else {
console.log("ok");
}
}
});
}
And in my PHP I'm giving no arguments at the moment to test a full null insert query: Edit:
$consultaAcciones= "INSERT INTO acciones VALUES (NULL, NULL, NULL, NULL, NULL, NULL, NULL)";
$ejecAcciones = mysqli_query($conn, $consultaAcciones);
if($ejecAcciones===false){
$response = [
'status' => 'FAIL',
'message' => 'Accion no registrada correctamente'
];
}
else {
$response = [
'status' => 'OK',
'message'=> 'Accion registrada'
];
}
header("Content-type: application/json");
echo json_encode($response);
I am getting "Error" in the console logs and I don't know what's wrong. Edit: No longer
Edit:
Now it doesn't display any error, it's okay, but also doesn't show my console logs for when everything's okay, also am getting a warning message:"Cross-Origin Read Blocking (CORB) blocked cross-origin response"
and a log: XHR finished loading: POST "http://url...".
may it be is not correct to specify the callers of my function this way?
function addListener(id,num)
{
var target= document.getElementById(id);
if(target){
target.addEventListener("click",SumbitAction(num),false);
}
else{
//console.log("Nel",id);
}
}
There are 2 problems in the code.
First, if(('error')) { will always evaluate as true. 'error' is just a string, and that is truthy.
You probably meant to compare that string against something, maybe (also removing doubled parentheses):
if (textstatus === 'error') {
Next, textstatus is the status of the request, not of your code. It will be error when, for eg, there is a 404, or a 500 response from the server. If your INSERT fails, the http request will still be successful, and textstatus will not be error.
You might want to check textstatus in an error() callback, if you want to add one. But within the success() callback, you probably want to be checking what your code returned. In this case, that is obj.
But looking at the PHP, it does not return anything predictable that the JS can use. It returns nothing if the query works. If it fails, it returns a string that begins with Error but then shows a MySQL error, which we won't know ahead of time, so you can't test for it in JS.
It would be better to simply return some true/false, OK/fail type msg, for eg:
// ... rest of your code
$result = mysqli_query($conn, $consultaAcciones);
if ($result === false) {
echo "FAIL";
} else {
echo "OK";
}
And in your JS:
if (obj === 'FAIL') {
// ... etc
If you actually want to pass a message back from the PHP, you should have it echo out a JSON object, eg:
$result = mysqli_query($conn, $consultaAcciones);
if ($result === false) {
$response = [
'status' => 'FAIL',
// You shouldn't reveal internal details about errors
// so don't return mysqli_error(). Maybe log it, and
// display something generic to your users.
'message' => 'There was a problem'
];
} else {
$response = [
'status' => 'OK',
'message'=> ''
];
}
header("Content-type: application/json");
echo json_encode($response);
In your JS:
$.ajax({
// ...
// specify we will get a JSON response
dataType: 'json'
// ...
success: function (obj, textstatus) {
if (obj.status === 'FAIL') {
alert(obj.message);
} else {
// all ok ...
}
});

Access JSON Ajax Response data

I have added a property to a JSON data but I cannot access the data on JS it does not show. I am not new to Ajax and JSON but it is a apparent that I still have gaps in my knowledge when it comes to Ajax. Please help me understand how i can append data to my Ajax response.
I have this in a PHP controller class:
$x = '5';
if($request->ajax()){
return response()->json([
'total_questions' => $x,
'responseText' => $e->getMessage(),
], 500);
}
I want to access the total_questions property with JS/JQuery..
My JS AJAX callback is here:
console.log('errors -> ', data.total_questions); - returns undefined
$.ajax({
type:"POST",
url: APP_URL+"selfEvaluation/save",
data:$(this).serialize(),
dataType: 'json',
success: function(data){
console.log(data);
},
error: function(data){
var errors = data.responseJSON;
console.log('data -> ', data);
console.log('errors -> ', data.total_questions);
if(data.status == 422){
// alert('422');
}
}
});
This is my console result
error: function(data){
is an incorrect method signature. See the definition at http://api.jquery.com/jquery.ajax/.
It should be
error: function(jqXHR, errorThrown, textStatus){.
You'll need to access the jqXHR.responseJSON property. So:
console.log('errors -> ', jqXHR.responseJSON.total_questions);
But I would question why you're returning a "500" status code for this request, when it appears to be a valid response. "500" means "Internal Server Error", which implies the server crashed, when it appears that it did not. If you return a "200" ("OK") status, your ajax code will go into the "success" callback and you can directly reference the "data" object in the callback to read your data.
try this if you will get a json response from your browser.
if($request->ajax()){
$result = array(
'total_questions' => $x,
'responseText' => $e->getMessage(),
], 500);
}
echo json_encode($result);

Retrieve JSON return from PHP called from AJAX

I'm trying to call an PHP file via POST and retrieve its result back in the calling AJAX code. But unfortunately it doesn't seem to work. After fiddling around with my code I either get "undefined", "a page reload" or "an error in the console that my parameter used in the success function isn't defined"
Here's the ajax code:
function postComment(formdata) {
if (formdata.comment != '') {
$.ajax({
type: 'POST',
url: '../../includes/post_comment.php',
data: formdata,
headers: {
'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'
},
success: postSuccess(data), // function to handle the return
error: postError // function to handle errors
});
} else {
alert('Empty please write something!');
}
}
function postSuccess(data) {
console.log(data);
$('#commentform').get(0).reset();
displayComment(data);
}
and here is my PHP handler:
$ajax = ($_SERVER['REQUESTED_WITH'] === 'XMLHttpRequest');
$added = add_comment($mysqli, $_POST); // contains an array
if ($ajax) {
sendAjaxResponse($added);
} else {
sendStandardResponse($added);
}
function sendAjaxResponse($added)
{
header("Content-Type: application/x-javascript");
if ($added) {
header('Status: 201');
echo(json_encode($added));
} else {
header('Status: 400');
}
}
this is what added looks like in PHP:
$added = array(
'id' => $id,//integer example: 90
'comment_post_ID' => $story_ID, //integer example: 21
'comment_author' => $author, //String example: Dominic
'comment' => $comment, //String example: This is a comment
'comment_date' => $date); //DateTime/String example: 08/02/2016 1970-01-01 00:00:00
UPDATES
I changed the ajax code to the following:
$.ajax({
type: 'POST',
url: '../../includes/post_comment.php',
success: postSuccess,
data: formdata,
headers: {
'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'
},
error: postError,
});
Now I get the full HTML-Code of the page calling this ajax function
I tried to set aysnc: false in the ajax request but it didn't help, always getting the html code of the source (calling the ajax function).
As for now I´m moving to a different approach which doesn´t need the return data. But thanks for the help
The browser tries execute server response because of
header("Content-Type: application/x-javascript");
change to
header("Content-Type: application/json");

Acces response value returned as json using ajax

From my database i fetched some data as json string.But unfortunately i can't access the data which is returned as response. Following is my php page to fetch data:
require_once '../core/init.php';
$answer=$_POST['answer_body'];
$post_id=$_POST['userpost_post_id'];
$answerer=$_POST['users_user_id'];
if(isset($answer,$post_id,$answerer)){
if(!empty($answer) && !empty($post_id) && !empty($answerer)){
$db=DB::getInstance();
if($result=$db->post_and_fetch("CALL login.post_and_fetch_ans(?,?,?)",array($answer,$post_id,$answerer))->result()){
echo json_encode($result);
}else{
echo 'there was a problem';
}
}
}
It returned as following:
and in the receiving part is following:(it currently prints undefined)
$.ajax('../includes/verifyanswer.php',{
data:data,
type:"POST",
datatype:'json',
success:function(response){
alert(response['answer_body']); // prints undefined
},
error:function(response){
alert(response);
}
})
Your response is a string, not an array. You should use getJSON() to make sure the response is parsed into an object :
$.getJSON(
'../includes/verifyanswer.php',
data,
function(response) {
alert(response.answer_body);
}
);

Retrieving posted data from ajax using php

I have a problem retrieving the posted data from an ajax call, not sure what is wrong. The console output from the script below shows everything as expectred before the ajax call, but the data is not available in the connector
function updateOptions(data){
console.log(data);
console.log(data.id);
console.log(data.action);
var data = {id: data.id, action : data.action};
console.log(data);
$.ajax({
type: 'POST',
url: 'ajax.connector.php?action=updateOptions',
data: JSON.stringify(data),
cache: false,
dataType : "json",
success: function(data, status) {
if(data.status == 'success'){
console.log('success');
console.log(data);
}else if(data.status == 'error'){
console.log('selects not updated');
}
},
error: function(data){
console.log('an error has occurred');
},
});
}
So the first 4 console.log entries show the data correctly, the first console.log in the success condition shows correctly. The second, shows:
Object {status: "success", msg: "Category added successfully", id: null, action: null, post: Array[0]}
the connector [more like a director]
case 'updateOptions':
error_log('Running updateOptions function ' . print_r($_POST, TRUE), 0);
$output = $sbb->updateOptions($_POST);
break;
Logs this:
Running updateOptions function Array\n(\n)\n,
if I try to echo $_POST['action'] or $_POST['data'] or something to the log I get an undefined index.
I am forcing the ajax call to return success in the class that the php case function is calling:
public function updateOptions($data){
$output = array(
'status' => 'success',
'msg' => 'Category added successfully',
'id' => $data['id'],
'action' => $data['action'],
'post' => $data,
);
return $output;
}
So the ajax call itself does work, it's the data that's not being passed.
Somehow I am not getting [or correctly retrieving] the data from the ajax post.
What is the problem here?
You're posting JSON, $_POST is populated with key=value pairs, don't mix up JSON with application/x-www-form-urlencoded or multipart/form-data (which is what php uses to populate $_POST.
To send application/x-www-form-urlencoded data with jQuery.ajax pass an object with the data as the data parameter
data: data, // removed JSON.stringify

Categories

Resources