Associative array from PHP to Javascript using JSON - php

I'm trying to send an associative array from PHP to Javascript. But, for some reason, the output is Undefined. Here's the code:
PHP (Suppositional array):
$validationErrors = array("unregisteredName" => NULL,
"unregisteredEmail" => "Invalid e-mail", "unregisteredUsername" => NULL,
"unregisteredPassword" => NULL);
$log = array("errors" => $validationErrors);
echo json_encode($log);
Javascript:
var addUserCallback = function(data) {
if(data.errors && data.errors.length) {
$.each(data.errors, function(index, error) {
console.log(error);
$("#"+index).attr("placeholder", error);
});
}
else {
window.location="/users/success/";
}
};
var errorCallback = function(xhr, status, error) {
console.log(arguments);
};
self.addUser = function() {
var data = {
unregisteredName: $("#unregisteredName").val(),
unregisteredEmail: $("#unregisteredEmail").val(),
unregisteredUsername: $("#unregisteredUsername").val(),
unregisteredPassword: $("#unregisteredPassword").val()
};
$.post(addUserUrl, data).success(addUserCallback)
.error(errorCallback);
}
And here is what I get from Chrome's Inspector:
data: "↵{"errors":{"unregisteredName":null,"unregisteredEmail":"Invalid e-mail.","unregisteredUsername":null,"unregisteredPassword":null}}"
data.errors: Undefined
So, what's happening is that, even getting data on "data" variable, because of the fact that it is unformatted it always redirects to the "success" page.
Any ideas?

You need to tell jQuery to parse the JSON string.
$.post(addUserUrl, data, 'json').success(addUserCallback).error(errorCallback);
Though I usually pass the success callback to $.post
$.post(addUserUrl, data, addUserCallback, 'json').error(errorCallback);

Related

my ajax call is getting correct response but isn't doing anything

I'm trying to make a like/dislike button in ajax. The ajax is sending my data to a separate file where it is saved in a database and that file sends back the successful response {"status":"success","message":"Like has been saved.","data":{"like":"1"}} that I got from the chrome network response window. However the code in $ajax(...).done isn't working
I have console.logged and var.dumped every bit of code i possibly could. my data IS being sent to my database which should mean that the SQL and the like class is correct. I've also tried simply console.log 'ging the response "res" and putting the rest in comments, but that again gives me nothing
<div>
Like
Dislike
<span class='likes' data-id="<?php echo $post->id ?>"><?php echo $post->getLikes(); ?></span> people like this
</div>
$("a.like, a.dislike").on("click",function(e){
var postId = $(this).data("id");
if($("a.like")){
var type = 1;
}else if($("a.dislike")){
var type = 0;
}
var elLikes = $(this).siblings(".likes");
var likes=elLikes.html();
$.ajax({
method: "POST",
url: "ajax/postlike.php",
data: {postId: postId, type:type},
dataType: "json",
})
.done(function( res ) {
console.log(res);
if(res.status=="succes"){
console.log(res);
if(res.data.like=="1"){
likes++;
elLikes=html(likes);
$("a.like").css("display","none");
$("a.dislike").css("display","inline-block");
} else if(res.data.like=="0"){
likes--;
elLikes=html(likes);
$("a.dislike").css("display","none");
$("a.like").css("display","inline-block");
}
}
});
e.preventDefault();
});
if(!empty($_POST)){
try {
$postId=$_POST['postId'];
$type=htmlspecialchars($_POST['type']);
$userId=$_SESSION['user_id'];
$l = new Like();
$l->setPostId($postId);
$l->setUserId($userId);
$l->setType($type);
$l->save();
$res = [
"status" => "success",
"message" => "Like has been saved.",
"data" =>[
"like" => $type
]
];
}catch (trowable $t) {
$res = [
'status' => 'failed',
'message' => $t->getMessage()
];
}
echo json_encode($res);
var_dump($res);
}
what I expected to happen was that Ajax sent the JSON data to the php code, that put it in a database, which works. Then gives a successful response to the Ajax, also works. The Ajax would then switch out the like/dislike buttons whilst adding or taking 1 like from the span "likes". It however does absolutely nothing
I'm almost 100% certain that the problem is something stupid that I'm overlooking, but i really can't find it.
Typo in 'success' in on line: if(res.status=="succes"){
you can try with this:
error: function(xhr, status, error) {
console.log(error)
},
success: function(response) {
console.log(response)
}
in your Ajax function, to know what happen in the server side with the response.
If you specify a return data type for the ajax request to expect, and the actual returned value isn't what you specified, then your error/fail function will be triggered if you have one. This is because adding dataType: "json" causes you're ajax try and parse your return value as json and when it fails, it triggers your error handler. It's best to omit the dataTaype and then add a try catch with JSON.parse in your done function, to get around this.
E.G
.done(function (string_res) {
console.log(string_res);
try {
var json_obj = JSON.parse(string_res);
console.log(json_obj);
} catch (e) {
console.log('failed to parse');
}
// do work/operations with json_obj not string_res
})
.fail(function (jqXHR, textStatus) {
console.log('failed')
});

how can I access json data from another url inside a html page

here is my php code which would return json datatype
$sql="SELECT * FROM POST";
$result = mysqli_query($conn, $sql);
$sJSON = rJSONData($sql,$result);
echo $sJSON;
function rJSONData($sql,$result){
$sJSON=array();
while ($row = mysqli_fetch_assoc($result))
{
$sRow["id"]=$row["ID"];
$sRow["fn"]=$row["posts"];
$sRow["ln"]=$row["UsrNM"];
$strJSON[] = $sRow;
}
echo json_encode($strJSON);
}
this code would return
[{"id":"1","fn":"hi there","ln":"karan7303"},
{"id":"2","fn":"Shshhsev","ln":"karan7303"},
{"id":"3","fn":"karan is awesome","ln":"karan7303"},
{"id":"4","fn":"1","ln":"karan7303"},
{"id":"5","fn":"asdasdas","ln":"karan7303"}]
But how can I access this data in html, that is, I want particular data at particular position for example i want to show 'fn' in my div and 'ln' in another div with another id
Before trying anything else I tried this
$.ajaxSetup({
url: 'exm1.php',
type: 'get',
dataType: 'json',
success: function(data){
console.log(data);
}
});
but it shows that data is undefined I don't know what I am doing wrong
What you've got should kind-of work if you swapped $.ajaxSetup (which is a global configuration method) with $.ajax. There are some significant improvements you could make though.
For example, your PHP does some odd things around the value returned by rJSONData. Here's some fixes
function rJSONData($result) {
$sJSON = array();
while ($row = mysqli_fetch_assoc($result)) {
$sJSON[] = array(
'id' => $row['ID'],
'fn' => $row['posts'],
'ln' => $row['UsrNM']
);
}
return json_encode($sJSON);
}
and when you call it
header('Content-type: application/json');
echo rJSONData($result);
exit;
Also make sure you have not output any other data via echo / print or HTML, eg <html>, etc
In your JavaScript, you can simplify your code greatly by using
$.getJSON('exm1.php', function(data) {
console.info(data);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.error(jqXHR, textStatus, errorThrown);
});
Use $.ajax instead of $.ajaxSetup function.
Here is a detailed answer from another SO post how to keep running php part of index.php automatically?
<script>
$.ajax({
// name of file to call
url: 'fetch_latlon.php',
// method used to call server-side code, this could be GET or POST
type: 'GET'
// Optional - parameters to pass to server-side code
data: {
key1: 'value1',
key2: 'value2',
key3: 'value3'
},
// return type of response from server-side code
dataType: "json"
// executes when AJAX call succeeds
success: function(data) {
// fetch lat/lon
var lat = data.lat;
var lon = data.lon;
// show lat/lon in HTML
$('#lat').text(lat);
$('#lon').text(lon);
},
// executes when AJAX call fails
error: function() {
// TODO: do error handling here
console.log('An error has occurred while fetching lat/lon.');
}
});
</script>

jQuery AJAX request returns NULL from PHP

Here is the code I am working on for my Wordpress site:
jQuery:
jQuery(document).ready(function($)
{
var actionValue;
$(".tabRow li").on('click', function(event)
{
event.preventDefault(); //override default behaviour
var clicked = $(this); //caches click so we don't scan DOM again
if(clicked.attr('id')=="tabAddData") //tab1 clicked
{
actionValue = "tab1Clicked";
}
$("li").removeClass("selected");
clicked.addClass("selected");
alert ('starting ajax call');
$.ajax(
ajaxObject.ajaxurl, //request gets sent to this url
{ //start of [options]
type: 'POST',
dataType: 'json', //type of data expected back from server
//data to send to server (JSON format)
data:
{
action: 'ajaxAction',
nonce: ajaxObject.nonce,
actionName: actionValue
}
} //end of [options]
) //end ajax(), the other fuctions are chained to it (.done .fail .always)
.done (function(data)
{
alert ('success function');
if(actionValue == "tab1Clicked") //tab1 clicked
{
$('#dataSection').empty();
$('#dataSection').append(data);
}
}) //end of done (success) function
.fail (function(xhr, desc, err)
{
alert ('error function');
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}) //end of fail (error) function
}); //end of onclick
});
PHP:
<?php
$my_action='ajaxAction';
if(defined('DOING_AJAX') && DOING_AJAX)//check if AJAX is loaded and working
{
//for logged in users
add_action('wp_ajax_'.$my_action, 'ajaxResponse');
}
function ajaxResponse()
{
if(wp_verify_nonce($_POST['nonce'], 'ajaxAction'))
{
if($_POST['actionName'] == "tab1Clicked")
{
$addDataSection = getAddDataSection();
$response=array(
'status' => 'success',
'addDataSection' => $addDataSection
);
header('Content-type:application/json;charset=utf-8');
echo json_encode($response);//encodes the jQuery array into json format
die;
}
}
}
function getAddDataSection()
{
//lots of echo statements which builds the html code
}
?>
When I first load my page, my PHP function getAddDataSection() generates the HTML inside my <div id='dataSection>. This works fine.
When I click on tab1, my jQuery AJAX call is supposed to reuse the same PHP function to generate my HTML. This is not working fine.
After I click on tab1, the jQuery fail function is triggered.
When I check Firebug, the response data contains the html generated by my PHP function getDataSection(), followed by a JSON string
{"status":"success","addDataSection":null}
When replying, keep in mind I'm a newbie. Thanks :)
Updated to include Console error:
Details: parsererror
Error:SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data
I think I found a solution.
In my jQuery, I changed the dataType from json to html.
Then in my PHP, I changed this:
if($_POST['actionName'] == "tab1Clicked")
{
$addDataSection = getAddDataSection();
$response=array(
'status' => 'success',
'addDataSection' => $addDataSection
);
header('Content-type:application/json;charset=utf-8');//still works without this line
echo json_encode($response);//encodes the jQuery array into json format
die;
}
to this:
if($_POST['actionName'] == "tab1Clicked")
{
$addDataSection = getAddDataSection();
echo $addDataSection;
die;
}

jquery ajax not parsing json data from php

I'm facing a strange problem for the last 10 hours and its really very annoying. The problem is with jquery printing json data from php. The php script is running fine, but when the ajax call returns in complete: event i'm not getting any valid otput.
here is the jquery code::
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST',
dataType: 'json',
complete: function(data) {
console.log(data['message']['Album_Name']);
}
});
return false;
});
});
i had to use complete: event as success: didn't worked at all. Atleast i'm getting some sort of output from the complete: event, although its giving undefined or [object][Object] which is totally ridiculous.
here is the retrieveFileFront.php:
<?php
require './retrieveFiles.php';
$type = $_POST['type'];
$nav_text = $_POST['navtext'];
$ret_files = new retrieveFiles($type, $nav_text);
$data = $ret_files->retFiles();
if ($data['success'] == FALSE) {
$data = array('success' => FALSE, 'message' => 'Sorry an Error has occured');
echo json_encode($data);
} else {
echo json_encode($data);
}
?>
and here is the /retrieveFiles.php
<?php
class retrieveFiles {
public $content_type;
public $list_nav;
public $connection;
public $result;
public $result_obj;
public $tags_array;
public $query;
public $row;
public function __construct($type, $nav_text) {
$this->content_type = $type;
$this->list_nav = $nav_text;
}
public function retFiles() {
#$this->connection = new mysqli('localhost', 'usr', 'pass', 'data');
if(!$this->connection) {
die("Sorry Database connection could not be made please try again later. Sorry for the inconvenience..");
}
if ($this->content_type == "Artists") {
$this->query = "SELECT album_name, album_art FROM album_dummy NATURAL JOIN album_images_dummy WHERE artist_name LIKE '$this->list_nav%'";
try {
$this->result = $this->connection->query($this->query);
$this->row = $this->result->fetch_row();
if (isset($this->row[0]) && isset($this->row[1])) {
$this->tags_array = array("success" => true, "message" => array("Album_Name" => $this->row[0], "Album_Art" => $this->row[1]));
return $this->tags_array;
}
} catch (Exception $e) {
echo 'Sorry an Error has occurred'.$e;
return false;
}
}
}
}
?>
I'm getting a 200 response in console in firebug, which indicates that its running okay.
<!DOCTYPE HTML>
{"success":true,"message":{"Album_Name":"Streetcleaner","Album_Art":"\/var\/www\/html\/MusicLibrary\/Musics\/1989 - Streetcleaner\/folder.jpg"}}
Now this is making me even more confused as i can see that the json is formatted properly. Please provide any sort of suggestion on how to solve this problem.
Thanks in advance..
JSON encoded data is usually not sent like
data['message']['Album_Name']);
But rather like:
data.message.Album_Name;
You're calling your results the wrong way. These are not associative arrays anymore but are now objects, as the name JSON (JavaScript Object Notation) suggests.
You need to parse the json response using
data = $.parseJSON(data)
Use success event instead of complete in ajax and we can able to parse JSON encoded data in javascript/jQuery by using JSON.parse
well after a long period of trauma, i finally found a solution, turns out that i needed to parse the response text and then access the objects, individually.
Here is the working code
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$('#loading').css('visibility', 'visible');
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST'
dataType: 'json',
complete: function(data) {
var res = data.responseText;
res = res.replace(/<!DOCTYPE HTML>/g, "");
res = res.trim();
console.log(res);
var arr = JSON.parse("[" + res +"]"); //needed to parse JSON object into arrays
console.log(arr[0].message.Album_Name);
console.log(arr[0].message.Album_Art);
$('#loading').css('visibility','hidden');
}
});
return false;
});
This works fine and gives the desired response. Anyways thanks for the help, guys.

Iterate over json array using jquery

There have been some post with my similar problem: How do I iterate over a JSON array using jQuery/AJAX call from PHP? but not quite the same.
I'm getting and error from jquery:
a is null
It is because of the code I've added to loop through the json data:
$(function ()
{
$.ajax({
url: 'ajax_dashboard/api.php', //the script to call to get data
data: "",
dataType: 'json',
success: function(data)
{
$.each(data, function() {
$.each(this, function(k, v) {
$('#output').append("<b>key: </b>"+k+"<b> value: </b>"+v)
.append("<hr />");
});
});
}
});
});
And here is the php file (which I did verify gives valid JSON format):
$query_camera_name = "SELECT camera_name, camera_status, camera_quality, email_notice, camera_hash, camera_type FROM #__cameras WHERE user_id=".$user->id." AND camera_status!='DELETED'";
$db->setQuery($query_camera_name);
//get number of cameras so we can build the table accordingly
$db->query();
$num_rows = $db->getNumRows();
// We can use array names with loadAssocList.
$result_cameras = $db->loadAssocList();
echo json_encode($result_cameras);
?>
This returns this json formatted data:
[
{
"camera_name": "ffgg",
"camera_status": "DISABLED",
"camera_quality": "MEDIUM",
"email_notice": "DISABLED",
"camera_hash": "0d5a57cb75608202e64b834efd6a4667a71f6dee",
"camera_type": "WEBCAM"
},
{
"camera_name": "test",
"camera_status": "ENABLED",
"camera_quality": "HIGH",
"email_notice": "ENABLED",
"camera_hash": "6ab000ef7926b4a182f0f864a0d443fc19a29fdd",
"camera_type": "WEBCAM"
}
]
If I remove the loops the "a is null" error is gone. What am I doing wrong?
Your iteration code works just fine: http://jsfiddle.net/SuyMj/
The error is elsewhere.
Edit:
Try this to help debug.
success: function(data, textStatus, xhr) {
console.log(xhr);
...
}
xhr will contain a lot of information about the request being made. What does the responseText contain? What is the statusText?
Your code works fine:
http://jsfiddle.net/QSvNy/
So the error is not there.
I don't see that you set the Content-Type of your response from php. Possibly the mime type of your response is incorrect and so jQuery does not parse the response as json.
Try this in your php before you echo your json:
header('Content-Type: application/json');

Categories