seperate each array value from array passed by ajax -- php - javascript

I passed an array using Ajax and i echoed it in php , it works good. But i don't know how to separate its value and find its length.
Here is the code:
var myCheckboxes = new Array();
$(".book_type:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.post("s.php?c="+category+"&k="+myCheckboxes,{data : "some data"}, function(response){
$("#show_result").html(response);
And the php is:
$a=$_GET['k'];
echo $a;
it displays the values of all checkbox like this
all,0,1,2,3,4
How can i find $a length as array?. if i use sizeof($a) it shows as 1.
Also how to separate those values into each single value.
Any suggestion

try like this
$a=$_GET['k'];
$value= explode(",",$a);
echo sizeof($value); //output 6
echo $value[0]; //all
echo $value[1]; //0
echo $value[2]; //1
echo $value[3]; //2
echo $value[4]; //3
echo $value[5]; //4

Try using:
$a=$_GET['k'];
$a=explode(',', $a);
echo count($a);

Pass the value as an array
$.post("s.php", {
data: "some data",
c: category,
k: myCheckboxes
}, function (response) {
$("#show_result").html(response);
})
then
$a=$_GET['k'];
where $a will be an array, so count($a) should give you the length

You should call JSON.stringify in your javascript:
// ⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓
... category+"&k=" + JSON.stringify(myCheckboxes) ...
or, alternatively, use jQuery ajax syntax sugar in your post request:
$.post("s.php", { k: myCheckboxes, ... });
This will provide a json as string passed to controller. From within your controller you should json_decode the received parameters:
$a = $_GET['k'];
print_r(json_decode($a));
Hope this helps.

Related

How can I access jquery Stringified array elements using PHP?

I use the following to post to a PHP page, showing the result in the message div:
let x = JSON.stringify($('#my-form').serializeArray());
$.post("processjs.php", {data:x})
.done(function(result, status, xhr) {
$("#message").html(result)
})
That results in the following array:
[{"name":"AccountName","value":"TestAcct"},{"name":"AccountID","value":"FR-62"},{"name":"Domain","value":"TestDomain"},{"name":"Status","value":"Enabled"},{"name":"ConfigurationSetName","value":"WLOD-1"},{"name":"SecConfVersion","value":"4"},{"name":"LastUpdated","value":"2022-12-1"},{"name":"MostCurrentVersion","value":"Yes"},{"name":"NotCurrentVersionReason","value":"None"},{"name":"RouterCount","value":"3"},{"name":"CustomerASN","value":"999999"},{"name":"ConfiguredP","value":"127"},{"name":"IPInstalled","value":"No"},{"name":"SharedGroup","value":"True"},{"name":"overlap","value":"False"},{"name":"POverlap","value":"False"},{"name":"ACLSDConfigured","value":"No"},{"name":"ACESDCount","value":"432"}]
How can I use PHP to access the array elements? Why are all of the keys and values prefaced with "name:" or "value:"?
I have tried using the following to access a key:
$json = json_decode(stripslashes($_POST['data']),true);
$AccountName = $json['AccountName'];
echo $AccountName;
But I always get the same message:
Undefined array key "AccountName"
I have tried using the following to access a key:
$json = json_decode(stripslashes($_POST['data']),true);
$AccountName = $json['AccountName'];
echo $AccountName;
I have also tried things like
$AccountName = $json[0]['AccountName'];
or
$AccountName = $json[0];
and also
$AccountName = $json[1];
In your sample request, AccountName is not a index, it is value of name index in a object inside a array.
Please try like this.
$json = json_decode(stripslashes($_POST['data']),true);
foreach($json as $inner){
$name = $inner['name']; //"AccountName" .... Here you will get value in $name a name .
$accountId = $inner['value']; //"TestAcct" ... Here you will get value in $accountId as "TestAcct" name .
}
Outputs are stated only for first iteration of foreach .

convert js array to php array and check its content

I want to sent a JS array to remote php server and convert it to a php array.
To check if php array is equal to js array I'm trying to get its members inside result div, but without success.
var rlist = ["title1", "title2", "title3"];
var b = JSON.stringify(rlist);
$.ajax({
url: 'reorder.php',
type: 'post',
data: {'b': b},
success: function(data) {
$("#result").html(data);
}
});
reorder.php
$rlist = json_decode( $_POST['b'], true );
echo $rlist;
try to put this code in the reorder.php
$rlist = json_decode( $_POST['b'], true );
foreach ($rlist as $value) {
echo "<div>" . $value . "</div>";
}
You can use json_decode as jQuery ajax submits it's arrays as json.
// Use as object
$json = json_decode($_POST['postdata']);
// Use as
echo $json->seomthign
$json = $_POST['postdata'];
// Output array
echo "<pre>";
var_dump(json_decode($json));
echo "</pre>";

Ajax read PHP generated json

So I want to send a json to an ajax call but I don't know how to read the json when is sent. And also my json looks strange because of the backslashes...
This is my ajax:
function find(){
var type = $('#object_type').val();
$.ajax({
type : 'POST',
url : 'get_user.php',
data : {
'type' : type
},
dataType : 'json',
error : function(response){
alert('SOMETHING WENT WRONG');
},
success : function(response){
This is what I get as a response:
"[{\"name\":\"Test\",\"link\":\"test.php\"},{\"name\":\"Test2\",\"link\":\"test2
.php\"}]"
}
});
}
This is my PHP function:
$type = $_POST['type'];
$user_array;
$user = mysqli_query($conn, "SELECT name,link FROM user WHERE `type` LIKE '%".$type."%'") or die();
while ($row = mysqli_fetch_array($user, MYSQLI_ASSOC)) {
$row_array['name'] = $row['name'];
$row_array['link'] = $row['link'];
array_push($user_array, $row_array);
}
mysqli_close($conn);
$result = json_encode($user_array, 128);
echo json_encode($result);
First change that you should make :
You don't need to encode two times
$result = json_encode($user_array, 128);
echo json_encode($result);
should be
$result = json_encode($user_array, 128);
echo $result;
Now the response should look like
[{"name":"Test","link":"test.php"},{"name":"Test2","link":"test2
.php"}]
which is a valid Javascript Array and can be accessed using following code :
var len = response.length;
for(i=0;i<len;i++){
console.log(response[i].name);
console.log(response[i].link);
}
As provided in techierishi's answer. Do not encode your response twice. Just do
echo $result;
The JSON should be valid and parsed, why?
json_encode is used on a valid PHP array returned from a MySQLi query.
dataType is used, explicitly forcing jQuery to JSON.parse the response and no errors where raised during that process.
The JSON that is returned has the following structure
ROOT
ARRAY
ARRAY OBJECT
OBJECT PROPERTY
To address something like that:
root[array index].property
Will give you the array's value, which is an object. That object has multiple properties.
[] means array
{} means object
So [{name:"value 1"},{name:"value 2"}] is actually
ARRAY
[0].name = value 1
[1].name = value 2
So retrieving information like name from your JSON will be:
response[0].name; // = test

Get a php array into a js array

I want to get a php array made by pg_fetch_all in a javascript array. But when I try to do it, firebug tells me that I'm trying to convert an array to string. Indeed, I don't understand why because both are arrays.
Here is where I create the php array :
$conn_string = "host=localhost port=5432 dbname=test_postgre user=postgres password='1234'";
$dbconn = pg_connect($conn_string);
$sql = "SELECT ".$colonne." FROM public.".$tablevar."";
$res = pg_query($sql) or die("Pb avec la requete: $sql");
$data = pg_fetch_all($res);
And here is my js code :
var array_dropdown =[<?php echo $data;?>];
And it doesn't work. Please help me !
PHP Arrays 101: Arrays in a string context are the literal word Array:
$x = array(1 => 2);
echo $x; // ouputs "Array"
You need to use json_encode():
var array_dropdown = <?php echo json_encode($data); ?>;
json_encode guarantees that whatever you pass in to the encode function will be output as syntactically valid javascript. Note the lack of [] around the above code - json_encode handles all of that for you.
Assume this as your PHP array
$array = array('foo' => 'bar');
The JS part:
var array = <?php echo json_encode($array); ?>;

Copying array values from php to javascript

I have a php array
array(6) {
["merchant_id"]=> string(6) "ajeesh"
["passkey"]=> string(4) "1234"
["amt"]=> string(5) "10.00"
["email"]=> string(16) "ajeesh#gmail.com"
["mobileNo"]=> string(10) "9874563210"
["orderID"]=> string(6) "123456"
}
which I got as a result of var_dump($_POST).
How can I copy all this value to a javascript array variable?How can it be possible? Suppose if the javascript array I made is
var thisSession = new Array();
TRY
I have tried this in the javascript
<script>
window.onload = function getApp(){
var thisSession = JSON.parse('<?php echo json_encode($_POST); ?>');
alert (thisSession);
}
</script>
and this in the php
json_encode($_POST);
but the javascript is alerting "Object object".Im not gettign the array!why?
You can use JSON, encode the PHP variable, then parse it in JS:
var thisSession = JSON.parse('<?php echo json_encode($_POST); ?>');
using php's json_encode & javascript's JSON.parse
var thisSession=JSON.parse('<?php echo json_encode($phparray)?>');
EDIT
If you want to access merchant_id you simply do
alert(thisSession.merchand_id);
Here, you need to json_encode the php data to use in javascript
$array = json_encode($_POST);
In your html
<script>
var data = JSON.parse("<?php echo $array; ?>"); // your new javascript object
</script>
Reference http://www.php.net/json_encode
There is no comparable object (associative array) in JavaScript to that which you've shown us in your example. You'd either have to use two Arrays or lose the ordering (and ability to have multiple keys of the same name) by using an Object. This second option is what json_encode will result in.

Categories

Resources