i am trying to retrieve the value of array via post in php script.
var data = [];
table.rows({ selected: true }).every(function(index){
// Get and store row ID
data.push(this.data()[0]); //create a 1 dimensional array
});
//send data via ajax
$.ajax({
url: '/...../...',
type: 'POST',
data: {userid:data},
dataType: 'json',
In my PHP script so far I am unable to decode the array. Have tried many ways
$myArray = $_REQUEST['userid'];
foreach ($arr as $value) {
$userid= $value; //for now just trying to read single item
}
I have tried print_r($myArray ); this sucessfully prints array contents to screen.
I am trying to retrieve the values for processing! Kindly point me in the right direction
I don't think that PHP would recognise the array that you've called "data" as being an array. Couldn't you turn the data from your table rows into values in a JavaScript object, encode it as a JSON string, then post that to your PHP script and use json_decode($_POST["userid"]) on the PHP end to convert it into a PHP array.
The object you are posting to PHP isn't in particular a jQuery object. Instead it is an JSON object or rather a JSON string. I guess you can't read that object the way you would read an regular array in PHP.
You might want to try to decode the string with json_decode(). With true as an function argument, it will return an php array as suggested in this stackoverflow answer https://stackoverflow.com/a/6964549/6710876
$phpArray = json_decode($myArray, true);
Documentation of json_decode(): http://php.net/manual/en/function.json-decode.php
simply use:
echo json_encode($myArray);
You're foreach is looping $arr, which doesn't exist. Your array is being set to $myArray, so use that in your for.
$myArray = $_REQUEST['userid'];
foreach ($myArray as $value) {
$userid= $value; //for now just trying to read single item
}
I believe you should also be able to find your values in $_POST
According to your var_dump :
array(1) { ["userid"]=> string(21) "assssssss,camo,castor" }
and if we assume "assssssss,camo,castor" are 3 different usernames.
You should use this:
$userids=explode(",",$myArray->userid);
foreach($userids as $userid){
// use $userid
}
Related
My php file receives a post from ajax call. The string received by the php file is as follows :
array(1) { ["userid"]=> string(21) "assssssss,camo,castor" }
I am trying unsuccessfully to decode this string then loop through the values in the array. I have tried the following :
$myarray =json_decode($_POST["userid"],true);
foreach ($myarray as $value) {
//do something with value
}
I am not sure whether the decode is the issue or my syntax to loop through the PHP array.
The POST data you'd want to manipulate is stored in $_POST['userid]
In case you're trying to access this comma separated user ids, you need to convert this to an array first using explode(). And then loop through these id's.
if (isset($_POST)) {
$user_ids = $_POST['userid']; // assssssss,camo,castor
$user_id_arr = explode(',', $user_ids); // Converts string to array Array (0 => assssssss, 1 => camo, 2 => castor)
foreach ($user_id_arr as $user_id) {
//Statements
}
}
$_POST is an associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request. So when you decode with json_decode that will decode JSON string to Object/Array.
But in your scenario you have not passed JSON String to $_POST so it not looks decoding.
The string you have passed into your $_POST is not JSON, so json_decode will not work on some random comma seperated values.
You can either pass in real JSON, or just use the explode method of splitting these values:
// explode example
$users = "assssssss,camo,castor";
$usersarray = explode(",", $users);
I've been experiencing a lot of trouble with my issue all afternoon. Endless searches on Google and SO haven't helped me unfortunately.
The issue
I need to send an array to a PHP script using jQuery AJAX every 30 seconds. After constructing the array and sending it to the PHP file I seemingly get stuck. I can't seem to properly decode the array, it gives me null when I look at my console.
The scripts
This is what I have so far. I am running jQuery 1.11.1 and PHP version 5.3.28 by the way.
The jQuery/Ajax part
$(document).ready(function(){
$.ajaxSetup({cache: false});
var interval = 30000;
// var ids = ['1','2','3'];
var ids = []; // This creates an array like this: ['1','2','3']
$(".player").each(function() {
ids.push(this.id);
});
setInterval(function() {
$.ajax({
type: "POST",
url: "includes/fetchstatus.php",
data: {"players" : ids},
dataType: "json",
success: function(data) {
console.log(data);
}
});
}, interval);
});
The PHP part (fetchstatus.php)
if (isset($_POST["players"])) {
$data = json_decode($_POST["players"], true);
header('Content-Type: application/json');
echo json_encode($data);
}
What I'd like
After decoding the JSON array I'd like to foreach loop it in order to get specific information from the rows in the database belonging to a certain id. In my case the rows 1, 2 and 3.
But I don't know if the decoded array is actually ready for looping. My experience with the console is minimal and I have no idea how to check if it's okay.
All the information belonging to the rows with those id's are then bundled into a new array, json encoded and then sent back in a success callback. Elements in the DOM are then altered using the information sent in this array.
Could someone tell me what exactly I am doing wrong/missing?
Perhaps the answer is easier than I think but I can't seem to find out myself.
Best regards,
Peter
The jQuery.ajax option dataType is just for the servers answer. What type of anser are you expexting from 'fetchstatus.php'. And it's right, it's json. But what you send to this file via post method is not json.
You don't have to json_decode the $_POST data. Try outputting the POST data with var_dump($_POST).
And what happens if 'players' is not given as parameter? Then no JSON is returning. Change your 'fetchstatus.php' like this:
$returningData = array(); // or 'false'
$data = #$_POST['players']; // # supresses PHP notices if key 'players' is not defined
if (!empty($data) && is_array($data))
{
var_dump($data); // dump the whole 'players' array
foreach($data as $key => $value)
{
var_dump($value); // dump only one player id per iteration
// do something with your database
}
$returningData = $data;
}
header('Content-Type: application/json');
echo json_encode($returningData);
Using JSON:
You can simply use your returning JSON data in jQuery, e.g. like this:
// replace ["1", "2", "3"] with the 'data' variable
jQuery.each(["1", "2", "3"], function( index, value ) {
console.log( index + ": " + value );
});
And if you fill your $data variable on PHP side, use your player id as array key and an array with additional data as value e.g. this following structure:
$data = array(
1 => array(
// data from DB for player with ID 1
),
2 => array(
// data from DB for player with ID 2
),
...
);
// [...]
echo json_decode($data);
What I suspect is that the data posted is not in the proper JSON format. You need to use JSON.stringify() to encode an array in javascript. Here is an example of building JSON.
In JS you can use console.log('something'); to see the output in browser console window. To see posted data in php you can do echo '<pre>'; print_r($someArrayOrObjectOrAnything); die();.
print_r prints human-readable information about a variable
So in your case use echo '<pre>'; print_r($_POST); to see if something is actually posted or not.
I have the following in php:
$query = mysql_query($sql);
$rows = mysql_num_rows($query);
$data['course_num']=$rows;
$data['course_data'] = array();
while ($fetch = mysql_fetch_assoc($query) )
{
$courseData = array(
'course_name'=>$fetch['course_name'],
'training_field'=>$fetch['training_field'],
'speciality_field'=>$fetch['speciality_field'],
'language'=>$fetch['language'],
'description'=>$fetch['description'],
'type'=>$fetch['type'],
);
array_push($data['course_data'],$courseData);
}
echo json_encode($data);
when I receive the result of this script in jquery (using post)
I log it using :
console.log(data['course_data']);
and the output is :
[Object { course_name="Introduction to C++", training_field="Engineering" , speciality_field="Software", more...}]
But I can't seem to figure out how to access the elements.
I tried
data['course_data'].course_name
data['course_data']['course_name']
Nothing worked. Any ideas
When you array_push($data['course_data'],$courseData); you are actually putting $courseData at $data['course_data'][0] and therefore you would access it in JavaScript as data['course_data'][0]['course_name'].
If you only intend to have one result, instead of array_push($data['course_data'],$courseData); you should just specify $data['course_data'] = $courseData. Otherwise, you should iterate over data['course_data'] like so:
for (i in data['course_data']) {
console.log(data['course_data'][i]['course_name']);
}
You should specify the index in the first array for instance
data['course_data'][0]['course_name'];
you could make it better if you had defined the first array just as variable not a variable within an array
$data['course_data'][0]['course_name']
should do the trick. If not please send the output of var_dump($data)
Assuming the PHP code is correct, you will receive a JSON data like:
{
"course_num":34,
"course_data":[
{
"course_name":"name_value",
....
},
....etc (other object based on SQL result)
]
}
So, if you want to access to the total number of result:
data.course_num
If you want to access to the first element of the list of result:
data.course_data[0]
If you want to access to the name of the first element of the list of result:
data.course_data[0].course_name
or
data.course_data[0]['course_name']
use jquery's parseJSON method to get all the goodies out of the json object...
http://api.jquery.com/jQuery.parseJSON/
My JSON looks like this. How do I get a specific field, e.g. "title" or "url"?
{
"status":1,
"list":
{
"204216523":
{"item_id":"204216523",
"title":"title1",
"url":"url1",
},
"203886655":
{"item_id":"203886655",
"title":"titl2",
"url":"url2",
}
},"since":1344188496,
"complete":1
}
I know $result = json_decode($input, true); should be used to get parsable data in $result, but how do I get individual fields out of $result? I need to run through all the members (2 in this case) and get a field out of it.
json_decode() converts JSON data into an associative array. So to get title & url out of your data,
foreach ($result['list'] as $key => $value) {
echo $value['title'].','.$value['url'];
}
echo $result['list']['204216523']['item_id']; // prints 204216523
json_decode() translates your JSON data into an array. Treat it as an associative array because that's what it is.
I have a jQuery post that returns some objects.
So, I have a DB query result that I do json_encode($result) and then I send it as a response in the success function inside the jQuery post.
If I console.log the response I see multiple objects. What I want is to send the response as an array of arrays.
In PHP
json_encode($results)
In javascript:
success: function(json) {
console.log(json);
}
In console log:
[>Object , >Object , >Object]
Any ideas?
Your $results in php is an array of objects or of associative arrays. Make it an array of numerically-indexed arrays before you send with casting:
// ASSUMING each $result object does not have its own nested arrays
foreach ($results as &$result) {
$result = array_values((array) $result);
}
Note you will lose the ability to get items by column name.
But please step back and think about where your $result comes from.
If you are using mysql driver, consider doing this when building your result:
$results = array();
// Note we use MYSQL_NUM option, so $row looks like array('col1value', 'col2value')
while (FALSE !== ($row = mysql_result_array($resource, MYSQL_NUM))) {
$results[] = $row;
}
json_encode($results);
In Javascript with JQuery:
jQuery.makeArray();
http://api.jquery.com/jQuery.makeArray/
In php, casting:
$aArray = (array) $oObject;
json encode will encode a string as a json OBJECT which in javascript is an object. in javascript an array is simply an object with special helper functions. there shouldn't be a need to create an array from the object as you can manipulate an object as easily as you can manipulate an array.