This is the array i have right now. I want to remove the random open bracket in the [0] => ["A100" and also the random close bracket in [4] => "B11"] ....I ve tried using :
foreach($list as $key=>$value)
{
**//its suppose to be the same array that is $list not a new array $array**
$list[$key]=str_replace("[","",$value);
}
$list being the array that contains the pictured elements. It doesnt seem to remove the brackets.. Am I doing something wrong?
**UPDATE: **
Im getting the array from a localstorage sending it through post to another php where i catch the value and explode to a array called $list.
$(function(){
$('#fbtn').click(function(){
$.ajax({
url: 'FactorAnalysis.php',
type: 'POST', // GET or POST
data: {data: localStorage.getItem('reportArray')}, // will be in $_POST on PHP side
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert("Response is"+ data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("failed");
}
});
});
});
the localStorage outputted to a div shows me :
so here im sending the data through a ajax call:
$list = array();
$list = explode(',',$_POST['data']);
^ then in another php (FactorAnalysis.php) i get the array and explode to array $list.
Try this
$list = json_decode($_POST['data'], true);
instead
$list = explode(',',$_POST['data']);
Related
This question already has answers here:
Array Foreach Loop Prints Last Item Only [closed]
(4 answers)
Closed 7 months ago.
So, I'm appending an array of objects to a FormData and sending the form with an ajax post request.
On my php page, I can access all form elements just fine (with the usual $_POST['field_name']), but when I try to access the array element I have appended, I'm having some problems.
Basically if I var_dump the element (called $_POST['dynamic_form']) I see an array of 2 (which is correct), but if I try to loop this array and echo the values only the last element of the array is echoed.
for (var i = 0; i < form_elements.length; i++) {
formData.append('dynamic_form[]', JSON.stringify(form_elements[i])); }
//THIS IS MY AJAX REQUEST
$.ajax({
type: 'POST',
url:'myurl',
data:formData,
processData: false,
contentType:false,
success: function(msg){
console.log(msg);
alert("form saved");
},
error: function(){
alert("request failed");
} });//fine ajax
//HERE MY PHP $dynamic_form = $_POST['dynamic_form']; var_dump($dynamic_form);
foreach( $dynamic_form as $form ); {echo $form;}
the var_dump result in the console is correct:
array(2) { [0]=> string(59) "{"type":"text","name":"","value":"2","label":"disponibile"}" [1]=> string(55) "{"type":"textarea","name":"","value":"1","label":"asd"}" }
but the echo inside the foreach loop only shows the last element of the array:
{"type":"textarea","name":"","value":"1","label":"asd"}
is_array($dynamic_form)
returns true (correct)
count($dynamic_form)
returns 2 (correct)
I have tried a for loop instead of the foreach but I still have problems.. what am I doing wrong?
Though it should be closed as a type, I will explain
foreach( $dynamic_form as $form ); {echo $form;}
is executed as
foreach( $dynamic_form as $form ) {
// do nothing
}
// echoes last value assigned to `$form` in loop.
{echo $form;}
And yes,
foreach( $dynamic_form as $form );
is absolutely valid code (though I don't know why you could need it unless it is a typo, as in question).
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']);.
I have this PHP array storing code(the data of array is came from database query) then the array will be pass to JQuery. My problem is I'm getting Undefined value when I retrieve the data from php Array. I use $.Each loop in JQuery. My question is, how to iterate loop of php associative array using JQuery?
Here's my code so far:
CONSOLE.LOG/NETWORK IMAGE
PHP Array storing
**** loop here*****
$ListOfWorkOrderDates[$rowInnerJoin['WorkOrder']][$rowInnerJoin['DateField']] =
array('DatePosted' => $rowInnerJoin['DatePosted']);
echo json_encode($ListOfWorkOrderDates);
Jquery Loop
/// Here where I get confuse. How can I retrieve those data from php using jquery loop
$.ajax({
url:'getWorkOrders.php',
type:'POST',
data:{id:_WOID},
dataType:'json',
success:function(output){
console.log(output);
$.each(output, function(index, object){
counter++;
ListOfPercentage.push(object.DateField);
ListOfDates.push(object.DatePosted);
});
}
});
$ListOfWorkOrderDates[$rowInnerJoin['WorkOrder']][$rowInnerJoin['DateField']] =
array('DatePosted' => $rowInnerJoin['DatePosted']);
Did you check your exact json response using firebug or chrome dev tools.
I believe object.WorkOrder might return undefined, because your json does'nt seem to have a WorkOrder key?
for the js to work, your json response should be something like
[
{
"WorkOrder": "w1",
"DateField": "D1",
"DatePosted": "DP1"
},
{
"WorkOrder": "w2",
"DateField": "D3",
"DatePosted": "DP2"
}
]
a quick code i used to generate the above response
$response=array();
$response[0]=array("WorkOrder"=>"w1","DateField"=>"D1","DatePosted"=>"DP1");
echo json_encode($response);
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'
)