Access JSON Ajax Response data - javascript

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

Related

Data is empty when passing a variable from JS to PHP with Ajax

I'm trying to pass a simple string variable with an onclick event, the request is successful but I get an empty response on the console, and the xvar variable is no coming through so I get the "NO DATA" p tag. This is my first time using Ajax so I tried to make it very simple to start. Here's my code:
JS
var xvar = 'D';
$('.test').click( () => {
$.ajax({
data: { xvar : xvar },
type: "POST",
url: 'test.php',
success: function(data, textStatus, XMLHttpRequest)
{
console.log('Success: '+data)
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log("The request failed."+errorThrown);
}
});
});
test.PHP
$xvar = (isset($_POST['xvar'])) ? $_POST['xvar'] : '<p>NO DATA</p>';
echo $xvar;
I'm using JQuery 3.5.1 that is included with Wordpress. I'll appreciate any feedback.
EDIT
I managed to get the response on test.php as seen
here:
But I when I try to render the value with print_r is not shown.
$res = $_POST;
print_r($res);
On the data of your Ajax, try to add the quotes in the key of the data. Like this:
data: { "xvar" : xvar },

ajax response data is undefined

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);
}
?>

Ajax response status 200 but shows error message

I'm getting status as 200 but it's printing message present inside error message alert("error...");. Why so?
function makeSelect() {
var blouseoption = document.querySelector('input[name="blouseoption"]:checked').value;
var url = "http://dukano.co/sakhidev/retailon/productoption/values";
alert(url);
var jsondata = $j('#customoption').serialize();
alert("jsondata: " + JSON.stringify(jsondata));
$j.ajax({
type : 'POST',
url : url,
data : jsondata,
dataType : 'json',
success : function(response) {
console.log("calling");
console.log(response);
alert("call success");
alert("response data:" + JSON.stringify(response));
if (response.status == 200) {
console.log("yes");
} else if (response.status == "error") {
console.log("no");
}
},
error : function(response) {
alert("error...");
alert("response:" + JSON.stringify(response));
console.log(response);
}
});
}
Magento's controller function returning json value
public function valuesAction(){
$blouseoption = $this->getRequest()->getParam('blouseoption');
$sareefinishing = $this->getRequest()->getParam('sareefinishing');
$data = array( 'sfinishing' => $sareefinishing, 'layout' => $this->getLayout());
Mage::dispatchEvent('product_custom_option', $data);
$jsonData = json_encode(array($blouseoption, $sareefinishing));
$this->getResponse()->clearHeaders()
->setHeader('Content-type','application/json',true);
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($jsonData));
$this->getResponse()->sendResponse();
}
As you are using
dataType: "json"
this evaluates the response as JSON and returns a JavaScript object.any malformed JSON is rejected and a parse error is thrown.
This means that if server returns invalid JSON with a 200 OK status then jQuery fires the error function and set the textStatus parameter to "parsererror".
Make sure that the server returns valid JSON. empty response is also considered invalid JSON; you could return {} or null for example which validate as JSON.
try to check the textStatus in the error.
error : function(jqXHR,textStatus,errorThrown)
{console.log(textStatus)}
if this prints "parsererror" then of course you have problem with your returning json. please check that.
More Info
Alternative answer
Instead of returning status 200 with empty response, you can return status 204 and not return any response. Status 204 is for No Content. JQuery should not throw any error in this case.

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

send data to json from php

my json script is:
// add button .click
$('a.add').click(function(){
$('#loader').show();
var url = "/?"+$("form[name='jsms_add']").serialize();
ajx = $.ajax({
url: url,
type: 'post',
data:{ajax:1},
dataType: 'json',
success: function(r) {
$('#loader').hide();
if(r.r != 0){
alert("ok");
jsmsalert($('#alert_add'),'success',r.m);
apendtable(r.r)
$("tr").removeClass("odd");
$("tr.viewrow:odd").addClass("odd");
$("tr.editrow:odd").addClass("odd");
$('td[colspan="7"]').remove();
}
else{
jsmsalert($('#alert_add'),'error',r.m,0);
}
},
error: function(request, status, err) {
$('#loader').hide();
jsmsalert($('#alert_add'),'error','error...');
alert( "ERROR: " + err + " - " );
}
});
and in my php file i have
$data = array(
'r' => '1',
'm' => '1',
);
json_encode($data);
now i want to know that how can i send a value to json that r.r != 0 be true and my success code execute?
In Firefox the error is "SyntaxError: JSON.parse: unexpected character"
this code used by another site by i don't know what happend in php file
my problem is that how can i send some data (for example r=1) to my json, because i want to check that if r=1 (means success) do something and show text from m (message) in my page
please help me to correct php file
thank
In your php file make sure you are echoing the encoded data,
like so:
$data = array(
'r' => '1',
'm' => '1',
);
echo json_encode($data);
If you don't echo the data it will not make it back to your JavaScript.
If your JavaScript is what's throwing the errors try commenting out the dataType: 'json', and console logging the return. It might be php is throwing errors that jquery is refusing to parse.
$.ajax({'url': url,type: 'post',data:{ajax:1}, success: function(returnData){
console.log(returnData);
}});

Categories

Resources