I have the next code in javascript:
$.ajax({
type : "POST",
url : "get_link.php",
data: {
},
success:function (data) {
links = data; -> Here needs to be the first line of the query
seconds = data2; -> Here needs to be the second line of the query
}
});
I want to get the information from get_link.php, get_link.php is something like this:
["http://stackoverflow.com", "http://mywebsite.com"]
[10, 100]
I want to get the information in plain because i want to define a variable with the links the first line and the seconds, the second line.
Thanks
Split the response on the newline character:
success: function(data) {
var lines = data.split('\n');
var links = JSON.parse(lines[0]);
var seconds = JSON.parse(lines[1]);
...
}
But it would be better if you returned a single JSON containing a 2-dimensional array.
$seconds = array();
$links = array();
while ($row = mysqli_fetch_assoc($result)) {
$seconds[] = $row['seconds'];
$links[] = $row['links'];
}
echo json_encode(array('seconds' => $seconds, 'links' => $links));
Or even better, keep the related data together:
$results = array();
while ($row = mysqli_fetch_assoc($result)) {
$results[] = array('seconds' => $row['seconds'], 'link' => $row['link']);
}
echo json_encode($results);
This will produce:
[{"seconds": 10, "link": "http://stackoverflow.com"},
{"seconds": 100, "link": "http://mywebsite.com"}]
If the response is 1 array of array you can access it with data[0] and data[1].
If the response just contains 2 (or several) objects, I think you can just define your success function like so:
success:function (dataLinks, dataSeconds) {
links = dataLinks;
seconds = dataSeconds;
}
Related
<?
$cl = $row["saved_json_string_column"];
?>
expecting this output from the db query to create a new array
//cl = '[{"ifeid":1,"ans":"Yes","type":"SkipTo","target":"2"},{"ifeid":2,"ans":"Yes","type":"SkipTo","target":"5"}]';
cl = '<? echo $cl;?>';
// I would like to start with the saved 'cl' array and push new items to it.
skptoQarry = new Array();
//javascript function loop (not shown) generates vars and pushes to new array.
thisItem_eid = 1;
yes_no_is_this = 'No';
SkipToTartgetEID = 5;
var skptoQarry_temp = {
"ifeid" : thisItem_eid,
"ans" : yes_no_is_this,
"type" : "SkipTo",
"target" : SkipToTartgetEID
};
skptoQarry.push(skptoQarry_temp);
cl = JSON.stringify(skptoQarry); //for ajax post to php for saving
//this is what is in saved the DB via ajax post
[{"ifeid":1,"ans":"Yes","type":"SkipTo","target":"2"},{"ifeid":2,"ans":"Yes","type":"SkipTo","target":"5"}]
//...but when PHP echos it out only this comes out: cl = "[,]"
// I think i'm saving it wrong or echoing the column data the wrong way.
//read text from mysql and append where needed.
cl = $.parseJSON(cl);
jQuery.each(cl, function (i) {
jQuery.each(this, function (key, value) {
if (key == "ifeid") {
$('div').append('if this id: '+value+'<br>');
} else if (key == "ans") {
$('div').append('is: '+value+'<br>');
} else if (key == "type") {
$('div').append('then: '+value+'<br>');
} else if (key == "target") {
$('div').append('this id: '+value+'<br><br>');
}
});
});
function saveit(){
saved_logic_dialog = JSON.stringify(skptoQarry);
var posturl = "myurl?event=save&saved_logic_dialog="+saved_logic_dialog;
jQuery.ajax({
traditional: true,
type: "POST",
url: posturl,
success: function(data) {
//messages and stuff
}
});
}
//php
$loadvfsql = "SELECT `saved_logic_dialog` FROM `questions` WHERE `id` = '{$id}' ORDER BY `questions`.`question_order` ASC";
$loadv_result=mysql_query($loadvfsql);
while($rows=mysql_fetch_array($loadv_result)){
$clc = $rows['current_logic_cont'];
$cl = $rows['saved_logic_dialog'];
//more stuff
}
This will ensure your array of objects is properly encoded - jQuery will not encode the URL for you.
var posturl = "myurl?event=save&saved_logic_dialog=" + encodeURIComponent(saved_logic_dialog);
When saving to DB - check for properly escaping the value (as it will certainly contain quotes);
When echoing the value back into HTML - use htmlspecialchars($cl) to properly escape the symbols which might have special meaning in HTML.
Before using the value in JavaScript - use JSON.parse(cl) to convert from String into Array.
I have an array in PHP and I would like to loop through it.
Unfortunately, the array gives back this in JavaScript:
Array
(
[data] => 12,11,2,5,6,7,8,9,10,13,14,15,16,17,18
[0] => 12,11,2,5,6,7,8,9,10,13,14,15,16,17,18
)
And not:
var myvar = [10, 11, 12, ...];
So I cannot loop through it. Any suggestions?
<?php
include("connection.php");
$query = $handler->query(' SELECT data FROM lista where id=1;');
$query->setFetchMode(PDO::FETCH_BOTH/*, 'CreaPrezzi'*/);
$r = $query->fetch();
print_r($r);
$.ajax({
type:"POST",
url:"getSortable.php"
}).done(function (list) {
var sortedList = list;
sortedList.forEach(function(id) {
$("#" + id).appendTo("#sortable")
})
})
That kind of output is indeed what you get with print_r. Instead use json_encode as follows:
echo json_encode($r[0]);
Then in JavaScript indicate that your are expecting JSON:
$.ajax({
type:"POST",
url:"getSortable.php",
dataType: "json" // <!-- add this
}).done( // ...etc
As $r[0] (in PHP) is a plain string, you'll need to split it into an array, either in PHP, or in JavaScript. In PHP that could be done with explode:
echo json_encode(explode(",", $r[0]));
Or with JavaScript (but then use the first PHP version) you can use split:
var sortedList = list.split(',');
<?php
include("connection.php");
$query = $handler->query(' SELECT data FROM lista where id=1;');
$query->setFetchMode(PDO::FETCH_BOTH/*, 'CreaPrezzi'*/);
$r = $query->fetch();
echo json_encode($r);
$.ajax({
type:"POST",
url:"getSortable.php"
}).done(function (list) {
var sortedList = list;
sortedList.forEach(function(id) {
$("#" + id).appendTo("#sortable")
})
})
I am need to directly get the variable from the response.php which contains the needed value. How can I the filter that JSON variable separately? Or if i merge both array into 1 JSON call then how do i get the different value
AJAX
function getMaleRanking(){
var mr = 'maleRangking';
var mf = 'femaleRangking';
$.ajax({
url : 'ajax/ajax_drill.php',
type : 'post',
cache : false,
data :{ mr : mr , mf : mf , event_id : event_id},
success:function(data){
var rankings = data;
//get the first json
//get the sencod json
}
});
}
getMaleRanking();
My php
echo json_encode(resultMergeMale, JSON_NUMERIC_CHECK);
echo json_encode(resultMergeFem, JSON_NUMERIC_CHECK);
You have to give response in json format for fetching valued in multiple paramater. Your php code should be
$response=array('mr'=>'','mf'=>'');
if(isset($_POST['mr'])){
foreach ($resultMergeMale as $key => $value) {
$firstval = $value;
//get this first val
$response['mr'] . =$firstval;
}
}
if(isset($_POST['mf'])){
foreach ($resultMergeFem as $key => $value) {
$secondval = $value
//get this seaond val
$response['mf'] .= $secondval ;
}
}
echo json_encode($response);
die();
You have to pass dataType:'json', so Jquery automatically convert JSON string into JSON object and you can access by its property. Your Ajax code should be
function getMaleRanking(){
var mr = 'maleRangking';
var mf = 'femaleRangking';
$.ajax({
url : 'ajax/ajax_drill.php',
type : 'post',
cache : false,
dataType:'json',
data :{ mr : mr , mf : mf , event_id : event_id},
success:function(data){
alert(data.mr);
alert(data.mf);
}
});
}
getMaleRanking();
Comma delimit the values, like this
if(isset($_POST['mr'])){
foreach ($resultMergeMale as $key => $value) {
$firstval = $value;
//get this first val
}
}
if(isset($_POST['mf'])){
foreach ($resultMergeFem as $key => $value) {
$secondval = $value
//get this seaond val
}
}
echo $firstval.",".$secondval
And then in your Ajax call,
success:function(data){
var rankings = data.split(",");
var firstval = rankings[0];
var secondval = rankings[1];
//your logic here
}
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I am using PHP and MySQL to swap out some content.
A click handler sends an AJAX request to the PHP script which performs a query, then encodes and prints the result as a JSON object.
All that seems to work, but I seem to be stuck on the most silly thing:
I can't work out how to actually use the result, as in set the individual values to JavaScript variables.
Edit: I added a couple more things I tried, to get a specific value to print out to the console, no luck thus far.
Edit: Found the correct syntax:
response[0].foo
javascript:
var listId = $(this).children('.hidden-id').html();
var options = new Object();
options.data = listId;
options.dataType = 'json';
options.type = 'POST';
options.success = function(response) {
console.log(response[0].foo);
};
options.url = './inc/change_list.php';
$.ajax(options);
the PHP script:
$list_id = $_POST['list_id'];
$q = "SELECT id, title, description, position FROM items WHERE list_id=$list_id ORDER BY position ASC";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) > 0) {
$result = array();
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$add_result = [
'id' => $row['id'],
'title' => $row['title'],
'description' => $row['description']
];
$result[] = $add_result;
}
$result = json_encode($result);
echo $result;
} else {
echo '{"result":"failure"}';
}
The JSON response will automatically be parsed to a Javascript object. So you can just do:
options.success = function(response) {
console.log(response.foo); // logs "bar"
// or
var foo = response.foo; // foo now holds "bar" as it's value
};
I'm having a little trouble figuring out how to fix this error I'm getting. My code is as follows.
It all starts with a AJAX request whenever the user moves their mouse on the webpage.
$('body').mouseover(function() {
$.ajax({
url: '/core/home.php',
data: {action: 'refresh'},
type: 'post',
Next, the PHP file (home.php) executes a couple methods to get all the needed data and sends it back to AJAX Request.
require_once 'init.php';
if(isset($_POST['action']) && !empty($_POST['action'])) {
// Home Class
$h = new Home();
// Method to count all "vacs"
$h->getVacs('id');
$vacs = $h->count();
// Method to count all "users"
$h->getUsers('id');
$users = $h->count();
// Create array to store all data
$arr = array();
$arr[] = $vacs;
$arr[] = $users;
// Use JSON to send the array back
json_encode($arr);
return $arr;
}
Once the AJAX Request receives a success, the following executes
success: function(output) {
obj = JSON.parse(output);
// Separate the parts of the JSON string
vacs = obj[0];
users = obj[1];
// Show the result at the correct position on the webpage
$('#vac_num').html(vacs);
if(vacs == 1) $('#vac_txt').html('is'); else $('#vac_txt').html('zijn');
$('#users_num').html(users);
if(users == 1) $('#users_txt').html('is'); else $('#users_txt').html('zijn');
}
});
});
Unfortunately this code results into an error: Unexpected end of JSON input.
Any help is much appreciated.
Rather than returning variable you need to echo it
require_once 'init.php';
if(isset($_POST['action']) && !empty($_POST['action'])) {
// Home Class
$h = new Home();
// Method to count all "vacs"
$h->getVacs('id');
$vacs = $h->count();
// Method to count all "users"
$h->getUsers('id');
$users = $h->count();
// Create array to store all data
$arr = array();
$arr[] = $vacs;
$arr[] = $users;
// Use JSON to send the array back
echo json_encode($arr);
}