Why is this object parse returning undefined? - javascript

Sorry about this nth version of object grabbing, but I just don't see it.
I am returning a JSON object from a db to my Javascript, and I see the returned object (below) just fine in the console. But the moment I attempt to put a child in the console I get "undefined". I should be able to see result.bills, or result["bills"] and just to be sure I've tried result[0].bills, etc. all of which are undefined. This seems so basic but I can't see why I can't make this work.
My PHP (after db stuff):
if ($result) {
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[bills] = $r;
}
echo json_encode($rows);
} else {
echo "Unknown Error";
}
//all done
My AJAX:
$.ajax({
type: 'get',
url: 'GetBills.php',
success: function(result) {
var thebills = result.bills;
console.log(thebills);
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
});
and I get back:
{
"bills": {
"ID": "3",
"State": "MD",
"Title": "Maryland Android Project Act (S.1196 H.2057)",
"HouseNum": "H 2057",
"SenateNum": "",
"Session": "189th"
}
}

You're getting undefined because jQuery doesn't know that it's actually receiving JSON back. It is detected and automatically parsed if you send JSON headers with your php file, OR if you set the dataType to 'json'.
So, currently you're accessing a string:
var result = '{"bills":{"ID":"3","State":"MD","Title":"Maryland Android Project Act (S.1196 H.2057)","HouseNum":"H 2057","SenateNum":"","Session":"189th"}}'
BUT you're attempting to access STRING functions (specifically bills which is undefined).
If you choose to not change the dataType or add headers, you could also do result = JSON.parse(result) which would also give you the same thing.
Doing one of the three above solutions will give you the object you're looking for, and access its children:
//Javascript
result = JSON.parse(result);
//In Console
Object {bills: Object}
bills:
ObjectHouseNum: "H 2057"
ID: "3"
SenateNum: ""
Session: "189th"
State: "MD"
Title: "Maryland Android Project Act (S.1196 H.2057)"
__proto__: Object
__proto__: Object

add dataType to your ajax request object:
...
type: 'get',
url: 'GetBills.php',
dataType: 'json',
...

You can either force the content type to be JSON in your AJAX call, or even better, set the correct content type in your PHP and let jQuery detect it automatically. Imagine accessing your data from another tool different from jQuery, e.g. a mobile app or some REST-tool. If you set your Content Type properly, most tools/languages will detect it automatically and you don't have to parse it manually over and over again.
// Set the content type correctly
header('Content-Type: application/json');
if ($result) {
$rows = array();
while ($r = mysqli_fetch_assoc($result))
{
$rows[] = $r; // Notice how to append the row to the array
}
http_response_code(200); // PHP >= 5.4
echo json_encode([
'success' => true,
'bills' => $rows
]);
}
else {
http_response_code(500); // Your status code here
echo json_encode([
'success' => false,
'message' => 'Something went wrong',
]);
}
And your JavaScript:
$.ajax({
type: 'get',
url: 'GetBills.php',
success: function(result) {
var thebills = result.bills;
console.log(thebills);
},
error: function(response) {
console.log('Error', response.message);
}
});

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

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

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

AJAX form not submitting that gives error

I have my AJAX code here
$("#add-student").click(function(e) {
e.preventDefault();
formData = $("#student-form").serialize();
if (cleanFormInput()) {
sendTheInfo(formData);
} else {
shakeForm();
}
});
function sendTheInfo(formData) {
$.ajax({
type: "POST",
url: "../classes/ajax/postNewStudent.php",
data: formData,
statusCode: {
404: function() {
alert( "page not found" );
}
},
success: function(formData) {
console.log("New student submitted:\n" + formData);
//clearForms();
},
error: function(result, sts, err) {
console.warn("Connection error:\n" + err + " : " + sts);
console.log(result);
shakeForm();
},
complete: function() {
console.log("Everything complete");
}
});
}
Always without fail outputs this error:
Connection error:
SyntaxError: Unexpected end of input : parsererror
But still gives the complete message: Everything complete
Update, PHP code here:
require '../../core/init.php';
require '../../classes/Config.php';
header('Content-Type: application/json');
if (!empty($_POST)) {
$id = $_POST["sid"];
$first = $_POST["first"];
$last = $_POST["last"];
$fav = "0";
$sql = "INSERT INTO `students` (`id`, `first`, `last`, `active`) VALUES ('{$id}', '{$first}', '{$last}', '{$fav}')";
$link = mysql_connect(Config::get('mysql/host'),Config::get('mysql/username'),Config::get('mysql/password')) or die("could not connect");;
mysql_select_db(Config::get('mysql/db'), $link);
$result = mysql_query($sql, $link);
if ($result) {
header('Content-Type: application/json');
$student_data = $id . $first . $last . $fav;
echo json_encode($student_data);
}
}
I'm a bit confused, am I doing my ajax set up wrong? Or is it something else in by backend code wrong? I'm using MySQL and jQuery 2.0.3
Updated code here: here
I have had a look at your code. I saw that from the PHP side you are sending a JSON object. but you didn't specified the return dataType for the response. Try to add the dataType in the ajax call. Maybe that will solve the problem
function sendTheInfo(formData) {
$.ajax({
type: "POST",
url: "../classes/ajax/postNewStudent.php",
data: formData,
dataType : 'json',
statusCode: {
404: function() {
alert( "page not found" );
}
},
success: function(formData) {
console.log("New student submitted:\n" + formData);
//clearForms();
},
error: function(result, sts, err) {
console.warn("Connection error:\n" + err + " : " + sts);
console.log(result);
shakeForm();
},
complete: function() {
console.log("Everything complete");
}
});
}
It should be noted that the Ajax COMPLETE method will fire even if the back end does not return a result.
complete: function() {
console.log("Everything complete");
}
will thus show the log'ed entry every time an ajax call is 'finished executing', even if the submit failed.
I would also suggest NOT having 2 headers or the same declaration (you have one up top, and one in the if(result) call.
In a comment thread, you pointed out that you're working on the server but not locally, And thus that implies you have some pathing issues. Check your
../
relative path style urls and make sure that you have the same basepoints.
removed my old answer. I don't think it is an ajax/javascript error. it's definitely a PHP error. It's this lines:
$student_data = $id . $first . $last . $fav;
echo json_encode($student_data);
You $student_data is not an array, it's just a string. You need to pass an array into the json_encode function

$_POST empty after ajax post called

So the purpose of me using this ajax post is to use some JS variables in a wordpress loop, so I can call a custom loop depending on what the variables are in the ajax post.
Below is the ajax call.
$('.collection-more').click(function() {
$.ajax({
type: 'post',
url: 'http://tmet.dev/wp-content/themes/muban-trust/single-collection.php',
data: { "test" : "hello" },
success: function( data ) {
console.log( data );
}
});
})
Currently I'm sending hard-coded data.
In my single-collection.php page:
<?php
print_r($_POST);
if(isset($POST['filters[Artist]']))
{
$filters_obj = $_POST['filters[Artist]'];
$filters_array = json_decode($filters_obj, TRUE);
for($i = 0; $i < sizeof($filters_array); $i++)
{
echo '<p>h'.$obj->name.'</p>';
}
}
?>
I'm using the print_r just to debug the problem, currently it returns:
Array()
The problem is that I cannot access the Json object called "test" within the single-collection.php
How do I access it?
Thanks in advance!
EDIT: Screenshot of firebug
From ajax to php :
this is the conventional way
var payload = {
smth1: "name",
smth2: "age"
};
and then when calling ajax
$.ajax({
url: "somephp.php",
type: 'POST',
data: payload,
dataType: 'json',
crossDomain: true
})
From phpPost to javascript:
right way getting the post parameters:
$fields = $_POST['fields'];
$usernameGiven = $fields['smth1'];
$passwordGiven = $fields['smth2'];
and when returning smthn to javascript
$result = array(
"something" => "something",
"something2" => $something2
);
echo json_encode($result);
Use $_POST['test'] to access the test parameter. Your print_r() shows that it is filled in correctly.
Your PHP code is accessing $_POST['filters[Artist]'] but there is no such parameter in the Javascript. If you pass:
data: { 'filters[Artist]': somevalue }
you can access it in PHP as $_POST['filters']['Artist'].

Categories

Resources