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")
})
})
Related
Ran into an issue with simply querying and returning the suggestID value.
I keep getting Array to string conversion, so i'm a bit lost. I'm
Javascript
$('#autocomplete').on('typeahead:selected', function (e, data) {
console.log(data);
var dataID = data;
$.ajax({
type: "POST",
url: "get.php",
data: $.param({itemID: dataID }),
success: function(data) {
console.log(data)
}
});
})
Get PHP FILE
<?php
require 'db.php';
if(isset($_POST['itemID'])) {
$db = new DbConnect;
$conn = $db->connect();
$str = $_POST['itemID'];
$stmt = $conn->prepare("SELECT * FROM mytable WHERE id = '$str'");
$stmt->execute();
$result= $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
}
?>
The itemID parameter is being treated as an array by PHP:
$str = $_POST['itemID'];
If you were to var_dump that you might see that $str is an array.
When the data passed to ajax is an object and one of the property values is an array, param will serialize it using the array bracket syntax, which PHP automatically treats as an array. For example:
$.param({key: [1, 2, 3]}); // "key[]=1&key[]=2&key[]=3"
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');
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;
}
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);
}
});
});
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
}