Parsing JSON objects to post - javascript

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

Related

Fetching a single record is outputting more than the records contents and json.parse not logging the correct data

I set up a new table called triggers. What I am doing is setting up a simple binary system that triggers things from showing or not showing. The code below is from an attempt I just made at doing this.
I'm running into two issues with the code below.
The echo json_encode is actually echoing onto the file's page. I have never had this happen before, so I'm unsure why it is doing so.
The echoed result is this:
{"specialPopStatus":{"setting":"1","0":"1"}}
The only number that should be showing up is 1. I don't understand where the trailing 0 and 1 are coming from.
The console.log results from the JSON.parse is [object Object]. I don't understand why, if at the very least, the 1, 0 and 1 isn't outputting.
Ultimately, all I am wanting is the setting result from the db for the single record I indicate by the name. Then I want to fetch this record via my ajax function. It will always be either 0 or 1.
What am I doing wrong?
PHP
try {
$con = getConfig('pdo');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$special_pop_sql = "
SELECT setting
FROM triggers
WHERE trigger_name = 'Special Pop'
LIMIT 1
";
if ($special_pop_stmt = $con->prepare($special_pop_sql)) {
$special_pop_stmt->execute();
$special_pop_row = $special_pop_stmt->fetch();
}
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
echo json_encode(['specialPopStatus' => $special_pop_row]);
JS
var status2 = 0;
function ajaxSpecialPopTrigger() {
$.ajax({
url: '/php/triggers.php',
datatype: 'json',
success: function (data) {
obj = JSON.parse(data);
specialPopStatus = obj.specialPopStatus;
status2 = specialPopStatus;
console.log(status2 + ' This is the status');
}
});
}
ajaxSpecialPopTrigger();
EDIT - New JS:
var status2 = 0;
function ajaxSpecialPopTrigger() {
$.ajax({
url: '/php/triggers.php',
datatype: 'json',
success: function (data) {
//obj = JSON.parse(data);
//Catalog Requests
specialPopStatus = data.specialPopStatus;
status2 = specialPopStatus;
console.log(status2 + ' This is the status');
}
});
}
ajaxSpecialPopTrigger();
The reason for the extra data in the json string is that you use
$special_pop_row = $special_pop_stmt->fetch();
the default of which is to return an assoc array AND a numeric array, notice the data value is 1 in both cases.
So fix that by doing this small mod
$special_pop_row = $special_pop_stmt->fetch(PDO::FETCH_ASSOC);
Also in the javascript because you have given
datatype: 'json',
as the paramter, you dont have to parse the json as jQuery will do that for you
So the javascript code be written
var status2 = 0;
function ajaxSpecialPopTrigger() {
$.ajax({
url: '/php/triggers.php',
datatype: 'json',
success: function (data) {
//obj = JSON.parse(data);
specialPopStatus = data.specialPopStatus;
//status2 = specialPopStatus;
console.log(specialPopStatus + ' This is the status');
}
});
}
ajaxSpecialPopTrigger();

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

creating query from data recived from javascript via ajax

I have the following javascript:
function update_number_of_adds_found(field_dropdown, selected_value) {
selected_value="";
for(i=0; i<document.submitadd.elements.length; i++){
if(document.submitadd.elements[i].value !='' && document.submitadd.elements[i].value != 'Αναζήτηση' && document.submitadd.elements[i].checked !=''){
selected_value += (document.submitadd.elements[i].name +'-' + document.submitadd.elements[i].value +' ');
}
}
var result5 = $.ajax({
'url': '<?php echo site_url('search/findNumberOfAdds'); ?>/' + selected_value,
'async': false
}).responseText;
$('#totalNumOfAdds').empty();
$("#totalNumOfAdds").append(result5);
}
This script send the data in the following format:
addtypeid-1%20isnew-1%20geographicareaid-3
I am a bit restriced in which symbols i can use, because I am using codeigniter, and if I use & for example i get message that i use dissalowed characters in my url.
My question is how can i transform this data in the format $key['fieldname'] = $value['fieldvalue'] so i can built my where clausule?
I was trying something with explode or replace, but without success so far. Any help will be deeply appreciated.
Regards, John
Just following up on my comment above ... You can try something like this ... I haven't tested it but should give you ideas to how to go about ...
jQuery('.submit').click(function(){
var str = $("#myForm").serialize();
str += '&serialize=' + encodeURIComponent(str);
str += '&action=myformsubmit';
jQuery.ajax('phpscripturl.php', {
method: 'POST',
data: str,
success: function(response) {
alert('Got this from the server: ' + response);
},
beforeSend: function(){
alert('Sending...');
}
});
return false;
});
By serializing the form inputs with jQuery's serialize you create a string like:
a=1&b=2&c=3&d=4&e=5&postID=10
So you can fetch this serialized data as
$data = $_POST['serialize'];
foreach($data as $key => $value) {
if($value == '') continue; //skip empty values as per your request
//else save in db etc ...
}
Build an JSON object then Stringify and post it in one variable. Then use json_decode($_POST['key']) to create a PHP object and can access the values easily.
In JS
var ValueToSend = new Object();
ValueToSend.field1 = value1;
var postString = JSON.stringify(ValueToSend)
In PHP
$Object = decode_json($_POST['key']);

parse JSON object passed through Ajax

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'])
});
}
});

Categories

Resources