parse JSON object passed through Ajax - javascript

I'm trying to parse a information that gets returned from a DB and encoded into a JSON object.
this is the code that retrieves the information:
private function retrieve_standards_one(){
$dbh = $this->connect();
$stmt = $dbh->prepare("SELECT code, standard_one_id
FROM standard_one
WHERE grade_id = :grade_id
ORDER BY standard_one_id");
$stnd = array();
for($x = 0; $x < (count($this->grades)); $x++){
$stmt->bindParam(':grade_id', $this->grades[$x], PDO::PARAM_STR);
$stmt->execute();
$stnd[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
$json = json_encode($stnd);
return $json;
}
and this id how I'm trying to parse the information:
$.ajax({
type: "POST",
url: "lib/search/search.standards_one.php",
async: "false",
data: {subjects: subjects, grades: grades},
success: function(response){
$("#standards_results").html("");
var obj = $.parseJSON(response);
$.each(obj, function(){
alert(this['code'] + ", " + this['standard_one_id'])
});
}
});
I've tried a number of different ways to do this, but I only ever get [object][object] as a response.
this is the response:
http://i.imgur.com/E5Hux.png

Use
console.log(this['code'] , this['standard_one_id'])
Instead of
alert(this['code'] + ", " + this['standard_one_id'])

Add dataType attribute to your AJAX call.
$.ajax ({
type: "POST",
dataType: "JSON",
url: "lib/search/search.standards_one.php",
async: "false",
data: {subjects: subjects, grades: grades},
success: function(response){
$("#standards_results").html("");
var obj = $.parseJSON(response);
$.each(obj, function(){
alert(this['code'] + ", " + this['standard_one_id'])
});
}
});

Related

pass php array to javascript using ajax

I try to get array from sql server using php , and parsing these array to javascript using ajax.
However , I have tried many solution by google , I can't get the array.
This is my php code:
<?php
include 'Connect.php';
$Store_int = $_GET['num'];
$sql = "SELECT * FROM `store` WHERE `Place_int` = " . $Store_int;
mysqli_select_db($link, "web");
$link->set_charset("utf8");
$result = mysqli_query($link, $sql);
$arr = array();
while ($row = mysqli_fetch_object($result)) {
$p = (string)$row->Name;
$arr[] = $p;
}
//print_r($arr);
$jsonArr = json_encode($arr, JSON_UNESCAPED_UNICODE);
echo $jsonArr;
mysqli_free_result($result);
mysqli_close($link);
?>
Array in php will encode and display:
["pen","pencil","apple","cat","dog"]
and the .js file
function getArr(store_int) {
var jsArray = new Array();
$.ajax({
url: "fromSQL_store.php",
data: {
num: $("#store_int").val()
},
type: "GET",
dataType: "json",
success: function (data) {
alert(num);
jsArray = JSON.parse(data.jsonArr);
}, error: function (data) {
alert("123");
}
});
//alert(jsArray.length);
return jsArray;
}
In .js , I will always get empty response(undefined) from php.
Because the ajax will answer "error" function..., and the error status is 200.
Your array will always return undfined as the AJAX call is async, your function returns jsArray before it is set. and You don't need JSON.parse() as you have defined dataType as json in your ajax call. Pass a function to your getArr() function and use your data in that function.
function getArr(store_int, outputFn){ // what do you use store_int for?
$.ajax({
url: "fromSQL_store.php",
data: {
num: $("#store_int").val()
},
type: "GET",
dataType: "json",
success: function(data) {
outputFn(data)
},error: function(data){
alert("123");
}
});
}
Then use it like
getArr('5', function (data) {
console.log(data)
})
Console output
Your problem lies here. You are attempting to access data.jsonArr which is always undefined. The JSON data sent is actually embodied by data variable.
success: function(data) {
alert(num);
jsArray = JSON.parse(data.jsonArr); // Replace by jsArray = data;
}
NOTE, You might also need to specify that the MIME media type that is being outputted is JSON. Putting this at the top of your PHP script should solve your problem.
<?php
header('Content-Type: application/json');

Send fetchAll array via ajax

I have this method that retrieves a list of dates from my database.
function getdate($id) {
$select = $this->db->query("select * from dates where user_id= '$id' ");
$row = $select->fetchAll(PDO::FETCH_COLUMN);
return $row;
}
And I have a model file "load calendar.php" which calls the method getdate:
$dates = $user->getdate($id);
echo $dates;
I want to be able to store the array $dates in an array my js file:
$(document).ready(function() {
var dbdates = new Array();
$.ajax({
type: 'POST',
url: 'loadcalendar.php',
data: { dates:dates },
success: function(response) {
dbdates = response;
alert(dbdates);
}
});
However, when I alert dbdates, nothing comes out. My 'getdate' method works. I only need help with the Ajax call. Thank you in advance!
Analyze these statements here,
$dates = $user->getdate($id);
echo $dates;
getdate() method actually returns an array, and what you're trying to do with echo $dates; is, you're trying to convert an array to a string, which won't work.
Instead, json_encode the array and echo it, like this:
$dates = $user->getdate($id);
echo json_encode($dates);
Also, add dataType: 'json' setting in your AJAX request, like this:
$(document).ready(function() {
var dbdates = new Array();
$.ajax({
type: 'POST',
url: 'loadcalendar.php',
data: { dates:dates },
dataType: 'json',
success: function(response) {
dbdates = response;
console.log(dbdates);
}
});
});

AJAX request error despite data is being updated successfully. "Unexpected Token <"

The question is very specific to my code written, and not able to find any solution.
I have an AJAX request that is sending some data to the server and updating the contents on the database. On firing the AJAX, the data is being updated in the database correctly, but AJAX displays error on the screen.
This is my AJAX request:
$.ajax({
type: "POST",
dataType: "json",
url: "update.php",
data: {'postData':JSON.stringify(postData)},
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function(data) {
successmessage = 'Data was succesfully updated';
$("#contentID").html(successmessage);
},
error: function(data) {
successmessage = 'Error';
$("#contentID").html(successmessage);
},
});
My PHP request is this:
if(isset($_POST['postData'])){
$jsonData = json_decode($_POST['postData'],true);
$length = count($jsonData['ID']);
$ID = $jsonData['ID'];
$fieldText = $jsonData['fieldText'];
for($j=0;$j<$length;$j++) {
$langText = $fieldText[$j];
$id = (int) $ID[$j];
$update = "UPDATE mytable SET myText = '$langText'
WHERE ID = $id";
$mysqli->query($update) or die(mysql_error());
}}
On debugging, I found the error message "Unexpected Token <".
The json that is being sent to "update.php" is valid json as I have tested this before. I'm posting the code that is capturing the values and creating a json before stringify it.
var node_list = document.getElementsByTagName('input');
var c = 0;
var fieldName = [];
var fieldText = []
var ID = [];
for (var i = 0; i < node_list.length; i++) {
var node = node_list[i];
if (node.getAttribute('type') == 'text') {
fieldName[c] = node.name;
fieldText[c] = node.value;
ID[c] = node.id;
c++;
}
}
var postData = {
fieldName: fieldName,
fieldText: fieldText,
ID: ID
};
var dataString = JSON.stringify(postData);
console.log(JSON.stringify(postData));
Can someone please help.
Fixed it by changing the
dataType:"json"
to
dataType: "html"
thanks

Parsing JSON objects to post

I am learning to build a simple API, I have the following code creating the following json:
Code:
$sql = "SELECT * FROM posts WHERE `user_id` = '$user_id' AND post_date > CURDATE() - INTERVAL 2 YEAR ORDER BY post_date DESC ";
$result = $dbc->query($sql);
$rows = array();
while ($row = mysqli_fetch_array($result))
{
$rows["posts"][$row['post_date']] = $row['post_content'];
}
echo json_encode($rows);
JSON created:
{"posts":{"2015-03-03":"33","2014-03-03":"33 33"}}
How do I parse this? I know the following code is a good start, but have not been able to go anywhere from there with success:
$.ajax({
url : "http://localhost:8888/290_project/api_write.php",
dataType: 'json',
type: 'get',
cache: false,
success : function(data){
}
});
Maybe I should then do something like in this w3 schools example?
var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
I have yet to have luck thus far with this though, but I know I am so close!
To have a clearer interface to interact with, you may consider changing your script to return data in a form that is easier to work with:
while ($row = mysqli_fetch_array($result))
{
$post = array();
$post['date'] = $row['post_date'];
$post['content'] = $row['post_content'];
$rows["posts"][] = $post;
}
In your success function, you have access to the data as a javascript object
success : function(data){
alert(data.posts[0].date);
alert(data.posts[0].content);
}
You can manipulate this data here any way you like without parsing it.
I think $.parseJSON is your solution. You can do this in your success event:
$.ajax({
url : "http://localhost:8888/290_project/api_write.php",
dataType: 'json',
type: 'get',
cache: false,
success : function(data){
var data = $.parseJSON(data);
console.log(data);
}
});
You actually don't even need to parse it if you use
$.getJSON('http://localhost:8888/290_project/api_write.php', function(alreadyParsedJsonData) {
// do stuff
});

Ajax post - POST array is returning empty on server side

I have an js function that is collecting data and sending it to a php file.
I am trying to submit an array as part of the post:
function send_registration_data(){
var string = "{username : " + $('#username').val() + ", password : " + $('#pass1').val() + ", level : " + $("#userrole").val() + ", 'property[]' : [";
var c = 0;
$('input[name=property]:checked').each(function(){
if( c == 0){
string +="\"" +this.value+"\"";
c=1;
} else {
string +=",\""+this.value+"\"";
}
});
string+="]}";
$('#input').html( JSON.stringify(eval("(" + string + ")")) );
$.ajax({ url: './php/submit_registration.php',
//data: { username : $('#username').val() , password : $('#pass1').val() , email : $('#email').val() , level : $("#userrole").val() },
data: JSON.stringify(eval("(" + string + ")")) ,
type: 'post',
success: function(output) {
$('#output').html( output );
}
});
};
On submit my php file returns an the POST array as NULL. I am not sure what I am doing wrong here.
EDIT: IT is the same weather I try to convert the string to json or not.
ALso, the inputs contain just text names.
string keyword
Do not use the "string" keyword.
eval
Eval is evil - use it with caution.
strict mode
Make sure always to work in the "strict mode" by placing this line at the beginning of your code:
'use strict'
Building your response object
You do not have to glue your post object manually. Just do it this way:
var post = {
'username': $('#username').val(),
'password': $('#password').val(),
'myArray[]': ['item1', 'item2', 'item3']
};
jQuery the right way
Avoid messing up with unnecessary syntax.
$.post(url, post)
.done(function(response){
// your callback
});
Conclusion
'use strict'
var url = './php/submit_registration.php'; // try to use an absolute url
var properties = {};
$('input[name="property"]:checked').each(function() {
properties.push(this.value);
});
var data = {
'username': $('#username').val(),
'password': $('#pass1').val(),
'level': $('#userrole').val(),
'property[]': properties
};
// submitting this way
$.post(url, data)
.done(function(response) {
// continue
})
.fail(function(response) {
// handle error
});
// or this way
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify(data), // you'll have to change "property[]" to "property"
contentType: "application/json",
dataType: 'json',
success: function(response) {
// continue
}
});
You need to get from php://input if you are not using multipart/form-data, so, application/json
$myData = file_get_contents('php://input');
$decoded = json_decode($myData);
If you're sending this up as json, your $_POST variable will continue to be NULL unless you do this.

Categories

Resources