I have a foreach loop that is called from my AJAX code. It appears that the foreach loop is being skipped right over. I would ultimately like to make it so that the foreach loop will execute a query using each value in the array, but I am first trying to test the the foreach loop works (which it does not). The alert (from my AJAX) that I am receiving is just the original array and not the one with the added items.
PHP:
$data = array();
if(isset($_POST['myArray']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']){
$data = $_POST['myArray'];
foreach ($data as $item) {
$data[] = $item;
}
echo json_encode($data);
die();
}
AJAX:
$(document).ready(function(){
$('#btn-addkegs').click(function() {
var arr = kegs;
var myArray = JSON.stringify(arr);
$.ajax({
url: "addkegs.php",
method: "POST",
dataType: "json",
data: {myArray: myArray},
success: function (result) {
alert("Your kegs have been added! These include: " + result);
textarea.value = "";
kegs = [];
}
});
});
});
As for the line var arr = kegs;, the value of the array 'kegs' is set through an input field and other AJAX, but all that works fine. I think that my problem is with my PHP code.
If you are send via post only values... like in comments : 1,2,3
your $_POST['myArray'] was receive literaly what you sent to.
So, data variable will receive the array that seems like this ['1','2','3']
Well... Since you are not creating a variable $data as an Array, and yes, only putting an array inside it.
The PHP doesnt consider the $data[] variable as same as $data.
So, the PHP was magicaly overwriting the values from each same values.
So, I think if you want to repeat the values in the same array, you must reference the array with the array_push
$data = $_POST['myArray'];
foreach ($data as $item) {
array_push($data, $item);
}
Now when you return this array, you will have a response like {1,2,3,1,2,3}
Answer from a comment by #David:
In your browser's debugging tools, take a look at the network requests. Examine the AJAX request and its response. If the result is entirely wrapped in quotes, then it's just a string and not an array. You may need to JSON-decode $_POST['myArray'] server-side to interpret it as an array.
I needed to change $data = $_POST['myArr']; to $data = json_decode($_POST['myArr']);.
Related
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
}
I am trying to echo some JSON with PHP. My array which I am echoing is part static and part of it has multiple records in the array.
Code
$return_output = array();
$return_output['error'] = false;
while (($serverLog_line=fgets($fopen_serverLog))!==false) {
$return_output[] = array(
"line" => $serverLog_line,
);
}
echo json_encode($return_output);
And the Jquery echoing it
$.getJSON("https://oasis-hosting.net/panel/handlers/server_functions/get.serverLog.php?service_id=22",
function(result){
var json = result;
$.each(json, function(i, data) {
$("#gameTerminal_content").append("" + data.line + "");
})
});
Now, it does echo the results, however it will echo one result which says "undefined". Screenshot: https://gyazo.com/47d2fbef749b94585c78a79b207fa65f
Thank you
It's because you have your actual data list mixed in with the error element.
Change the structure such that the data is in its own array:
$return_output['error'] = false;
$return_output['data'] = array();
In the while:
$return_output['data'] = array(
"line" => $serverLog_line,
);
In the JavaScript, iterate only over the data list not the error element:
var json = result.data;
it is written on the command console, it writes:
"Can not read the property 'line' of null"
this means, $return_output returns null. I am not so good at php, but i think you return $return_output but you modify $return_output[].
these are looking like two different variables. this should be the reason.
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 a JSON encoded array, to which i am returning to an AJAX request.
I need to place the JSON array into a JS Array so i can cycle through each array of data to perform an action.
Q. How do i place the JSON array contents into a JS array efficiently?
The PHP/JSON Returned to the AJAX
$sql = 'SELECT *
FROM btn_color_presets
';
$result = mysqli_query($sql);
$array = array(); //
while($row = mysql_fetch_assoc($result)) //
{
$array[] = $row;
$index++;
}
header("Content-type: application/json");
echo json_encode($array);
You can use JSON.parse function to do so:
var myObject = JSON.parse(response_from_php);
// loop over each item
for (var i in myObject) {
if (myObject.hasOwnProperty(i)) {
console.log(myObject[i]);
}
}
You can also use jQuery.parseJSON() if you are using jQuery, however jQuery also uses same function under the hood as priority if available.
Adding to Safraz answer:
If you're using jQuery, there's another way to do that. Simply add json as last parameter to your ajax calls. It tells jQuery that some json content will be returned, so success function get already parsed json.
Below example shows you simple way to achieve this. There's simple json property accessing (result.message), as well as each loop that iterates through whole array/object. If you will return more structurized json, containing list of object, you can access it inside each loop calling value.objectfield.
Example:
//Assuming, that your `json` looks like this:
{
message: 'Hello!',
result: 1
}
$.post(
'example.com',
{data1: 1, data2: 2},
function(response){
console.log(response.message) //prints 'hello'
console.log(response.result) //prints '1'
//iterate throught every field in json:
$(response).each(function(index, value){
console.log("key: " + index + " value: " + value);
});
},
'json'
)
I have a loop that grabs DB values and creates an object. I want to echo a JSON object every time the loop is iterated through. As of now, I just get blank in my console. Also, those commented out printf statements work fine. Any help would be much appreciated!
AJAX call
$.ajax({
url:'ajax/ipGet.php',
type: 'GET',
dataType:'json',
success:function(response){
console.log(response);
}
});
PHP Data Generation
$infoArray = new Array();
while($row = mysqli_fetch_array($getIpQuery, MYSQLI_NUM)){
for($x=0;$x<count($row);$x++)
{
$getIpInfo = mysqli_query($dbcon,"SELECT * FROM ipInfo WHERE address='$row[$x]'");
$retrievedInfo = mysqli_fetch_array($getIpInfo,MYSQLI_NUM);
$ipInfo->ipAddress = $retrievedInfo[0];
$ipInfo->port = $retrievedInfo[1];
$ipInfo->status = getStatus($ipInfo->ipAddress, $ipInfo->port);
array_push($infoArray,$ipInfo);
}
}
echo json_encode($infoArray);
Thanks for any help!
~Carpetfizz
json must be a single self-contained entity. You're outputting MULTIPLE separate bits of JSON text, which is incorrect.
JSON encoding should be the very LAST thing you do, e.g.
while(...) {
$array[] = ....
}
echo json_encode($array);
Consider what you're doing from the client perspective... building an array of ipinfo, so you run the loop once and produce
{"ipAddress":"127.0.0.1","port":80,....}
But you're doing it multple times, so you end up with
{"ipAddress":"127.0.0.1","port":80,....}{"ipAddress":"127.0.0.1","port":80,....{"ipAddress":"127.0.0.1","port":80,....}
as your output, and now you've got illegal javascript. Remember that JSON text is essentialy the right-hand-side of a Javascript assignment operation, e.g.
var somevar = ...json_goes_here...;
So you're doing
var stuff = {...}{...}{...};
which is an outright syntax error, instead of
var stuff = [{...},{...},{...}];
which would be correct.