how to pass data from json to a php function? - php

[registration] => Array
(
[first_name] => test
[location] => Array
(
[name] => Santa Ana
[id] => 1.08081209215E+14
)
[gender] => female
[password] => 123654789
)
and i need to insert that data into a database by using:
$carray = fns_create_talent($login, $pass, $gender, $name);
any idea on how to get them from a place to another?
i was thinking that i need to assign the array values to the post vars. maybe:
$login = registration.first_name...
any ideas?
thanks

$login = $json['registration']['first_name']

What you have shown is not JSON, but PHP's array. I am assuming this is the structure of the data you want to be sent to the server.
You can do it like that (remember, there are no associative arrays in JavaScript!):
on Javascript side do something similar to this:
var data = {
'registration': {
'first_name': 'test',
'location': {
'name': 'Santa Ana',
'id': '1.08081209215E+14'
},
'gender': 'female',
'password': 123654789
}
}
and then use data in eg. jQuery .post() as the second parameter.
on the PHP side just read from $_POST as you read multi-dimensional associative arrays. In this case it should look similar to:
// I have made assumption here (you do not have
// 'login' variable in your example)
$login = $_POST['registration']['first_name'];
$pass = $_POST['registration']['password'];
$gender = $_POST['registration']['gender'];
$name = $_POST['registration']['first_name'];
$carray = fns_create_talent($login, $pass, $gender, $name);
Here you go.

EDITED:
Where $arr is the array you submitted.
$carray = fns_create_talent(
/* your login var */,
$arr['registration']['password'],
$arr['registration']['gender'],
$arr['registration']['first_name']
);
I don't see your login inside the array, so I just put a comment for the login var, but you should get the idea.

Related

Pass php array to ajax

I have this array:
$users = array();
// Finally, loop over the results
foreach( $select as $email => $ip )
{
$users[$email] = $ip;
}
Now i want to pass this array to ajax and print in another script:
$html="<center>Check users for spam</center>";
mcheck.php
echo $_POST['users'];
This code does not work. How can i do this?
As Sergiu Costas pointer out, the best way is to JSON encode it and then decode, but you can also try:
$html="<center>Check users for spam</center>";
If your $users array is:
$users = array( array('email' => 'a#email.com'), array('email' => 'b#email.com')));
then http_build_query('users' => $users) will generate:
users%5B0%5D%5Bemail%5D=a%40email.com&users%5B1%5D%5Bemail%5D=b%40email.com
which is the url-encoded version of:
users[0][email]=a#email.com&users[1][email]=b#email.com
which will be decoded back to array in mcheck.php
The Best way is to encode array into JSON format.
In PHP:
$users_json = json_encode($users);
// To decode in javascript
var obj = JSON.parse(json_str);
if u want to pass php array to js you can json_encode the array to do that.
$html="<center>Check users for spam</center>";

How to fetch saved array from a file & access it like an array

I have a file, in which I saved data in array format and later I want to read this data into a variable and this variable must behave like an array.
Suppose I have a file on my pc : C:/test.txt and it contains an array :
Array
(
[first_name] => John
[last_name] => Doe
[email] => johndoe#gmail.com
)
Now I am fetching this data using below method :
$myfile = fopen("C:/test.txt", "r");
$test = fread($myfile,filesize("C:/test.txt"));
Now when I print $test it shows the data like array but when I check the datatype of this variable then it shows String.
I have also converted this variable into array using type casting :
$test1 = (Array) $test;
But when tried to fetch any index from $test1 then it show Illegal string error.
So can somebody help me out.
Try this
$file = "C:/test.txt";
$document = fopen($file,'r');
$contents = fread($document, filesize($file));
fclose($document);
this will give you a array $contents
print_r($contents);
C:/test.php
<?php
return array(
'first_name' => null,
'last_name' => null,
'email' => 'new',
);
another file:
<?php
$array = inclde('C:/test.php');
Or save json in file C:/test.json
{"first_name":null,"last_name":null,"email":"new"}
and in another file:
<?php
$json = file_get_contents('C:/test.json');
$array = json_decode($json, true);
Do this:
// $myarray is the array
file_put_contents('my_file', serialize($myarray));
// Later ...
$array = unserialize(file_get_contents('my_file'));
You can guess what serialize or unserialize does. But read more in docs to learn more specifically.
#VladimirKovpak 's answer will work too, but for simple arrays. Using serialization, you can save nearly any object, and get it back.
If you need more control over serialization process, look into magic methods __sleep and __wakeup from docs.

unserialize() function does not work with more than one index using php

I'm storing data in cookie using serialize/unserialize function. Unserialize function does not working when i add new item to array.
Code
$storedArr = array();
if(isset($_REQUEST['sendProductId'])){
$newItem = $_REQUEST['sendProductId'];
$storedArr[] = $_COOKIE['productID'];
array_push($storedArr, $newItem);
$cookie_name = 'productID';
setcookie($cookie_name, serialize($storedArr), time() + (86400 * 30));
}
$cookieData = $_COOKIE['productID'];
$data = unserialize($cookieData);
print_r($data);
Response on Single array index
Array ( [0] => [1] => 50 )
Response on when adding new item to array
Array ( [0] => a:2:{i:0;N;i:1;s:2:"50";} [1] => 50 )
Please guide me where i'm wrong. Thanks
i see logical issue in your code, when you get data from cookie as it is serialized you have to first unserialize it then use
$storedArr[] = $_COOKIE['productID'];
change to
$storedArr = !empty($_COOKIE['productID']) ? unserialize( $_COOKIE['productID'] ):array();
it should solve your issue.

How to change the array in order to make the desired JSON object in PHP?

I've an array titled $request as follows :
Array
(
[invite_emails] => suka#gmail.com, swat#gmail.com
[page_id] => 322
[ws_url] => http://app.knockknot.com/api/group/sendInvitation
)
After using json_encode($request) I got following output:
{
"invite_emails": "suka#gmail.com, swat#gmail.com",
"page_id": "322",
"ws_url": "http://app.knockknot.com/api/group/sendInvitation"
}
But actually I want the JSON object as follows :
{
"page_id": 322,
"invite_emails": [
"suka#gmail.com",
"swat#gmail.com"
],
"ws_url": "http://app.knockknot.com/api/group/sendInvitation"
}
How should I manipulate the array in PHP in order to get the above desired JSON object?
Please someone help me.
Split the list of emails using the comma:
$array["invite_emails"] = preg_split("#\s*,\s*#", $array["invite_emails"]);
I personally prefer using callback functions for readability and possibilities. To your purpose, array_walk should fit:
<?php
// reproducing array
$request = array(
"invite_emails" => "suka#gmail.com, swat#gmail.com",
"page_id" => 322,
"ws_url" => "http://app.knockknot.com/api/group/sendInvitation"
);
// callback finds a comma-separated string and explodes it...
array_walk($request, function (&$v,$k) {if ($k == 'invite_emails') $v = explode(", ", $v);});
// ... and then encode it to JSON
json_encode($request);
// testing
print_r($request);
OUTPUT:
{
"invite_emails":[
"suka#gmail.com",
"swat#gmail.com"
],
"page_id":322,
"ws_url":"http://app.knockknot.com/api/group/sendInvitation"
}
You are free to change the field if your needs changes, and even suppress it to be used with any field of the array.
Use PHP explode for example:
$array['invite_emails'] = explode(',',$array['invite_emails']);
To avoid spaces use preg_split (source):
$array['invite_emails'] = preg_split("/[\s,]+/", $array['invite_emails']);
This entry:
[invite_emails] => suka#gmail.com, swat#gmail.com
should be an array (currently, it is a string) in PHP, then in JSON it will look like you want it.

How to get the POST values from serializeArray in PHP?

I am trying this new method I've seen serializeArray().
//with ajax
var data = $("#form :input").serializeArray();
post_var = {'action': 'process', 'data': data };
$.ajax({.....etc
So I get these key value pairs, but how do I access them with PHP?
I thought I needed to do this, but it won't work:
// in PHP script
$data = json_decode($_POST['data'], true);
var_dump($data);// will return NULL?
Thanks, Richard
Like Gumbo suggested, you are likely not processing the return value of json_decode.
Try
$data = json_decode($_POST['data'], true);
var_dump($data);
If $data does not contain the expected data, then var_dump($_POST); to see what the Ajax call did post to your script. Might be you are trying to access the JSON from the wrong key.
EDIT
Actually, you should make sure that you are really sending JSON in the first place :)
The jQuery docs for serialize state The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. Ready to be encoded is not JSON. Apparently, there is no Object2JSON function in jQuery so either use https://github.com/douglascrockford/JSON-js/blob/master/json2.js as a 3rd party lib or use http://api.jquery.com/serialize/ instead.
The OP could have actually still used serializeArray() instead of just serialize() by making the following changes:
//JS
var data = $("#form :input").serializeArray();
data = JSON.stringify(data);
post_var = {'action': 'process', 'data': data };
$.ajax({.....etc
// PHP
$data = json_decode(stripslashes($_POST['data']),true);
print_r($data); // this will print out the post data as an associative array
its possible by using the serialize array and json_decode()
// js
var dats = JSON.stringify($(this).serializeArray());
data: { values : dats } // ajax call
//PHP
$value = (json_decode(stripslashes($_REQUEST['values']), true));
the values are received as an array
each value can be retrieved using $value[0]['value'] each html component name is given as $value[0]['name']
print_r($value) //gives the following result
Array ( [0] => Array ( [name] => name [value] => Test ) [1] => Array ( [name] => exhibitor_id [value] => 36 ) [2] => Array ( [name] => email [value] => test#gmail.com ) [3] => Array ( [name] => phone [value] => 048028 ) [4] => Array ( [name] => titles [value] => Enquiry ) [5] => Array ( [name] => text [value] => test ) )
The JSON structure returned is not a string. You must use a plugin or third-party library to "stringify" it. See this for more info:
http://www.tutorialspoint.com/jquery/ajax-serializearray.htm
I have a very similar situation to this and I believe that Ty W has the correct answer. I'll include an example of my code, just in case there are enough differences to change the result, but it seems as though you can just use the posted values as you normally would in php.
// Javascript
$('#form-name').submit(function(evt){
var data = $(this).serializeArray();
$.ajax({ ...etc...
// PHP
echo $_POST['fieldName'];
This is a really simplified example, but I think the key point is that you don't want to use the json_decode() method as it probably produces unwanted output.
the javascript doesn't change the way that the values get posted does it? Shouldn't you be able to access the values via PHP as usual through $_POST['name_of_input_goes_here']
edit: you could always dump the contents of $_POST to see what you're receiving from the javascript form submission using print_r($_POST). That would give you some idea about what you'd need to do in PHP to access the data you need.
Maybe it will help those who are looking :)
You send data like this:
$.ajax({
url: 'url_name',
data: {
form_data: $('#form').serialize(),
},
dataType: 'json',
method: 'POST'
})
console.log($('#form').serialize()) //'f_ctrType=5&f_status=2&f_createdAt=2022/02/24&f_participants=1700'
Then on the server side use parse_str( $_POST['form_data'], $res).
Then the variable $res will contain the following:
Array
(
[f_ctrType] => 5
[f_status] => 2
[f_createdAt] => '2022/02/24'
[f_participants] => 1700
)
You can use this function in php to reverse serializeArray().
<?php
function serializeToArray($data){
foreach ($data as $d) {
if( substr($d["name"], -1) == "]" ){
$d["name"] = explode("[", str_replace("]", "", $d["name"]));
switch (sizeof($d["name"])) {
case 2:
$a[$d["name"][0]][$d["name"][1]] = $d["value"];
break;
case 3:
$a[$d["name"][0]][$d["name"][1]][$d["name"][2]] = $d["value"];
break;
case 4:
$a[$d["name"][0]][$d["name"][1]][$d["name"][2]][$d["name"][3]] = $d["value"];
break;
}
}else{
$a[$d["name"]] = $d["value"];
} // if
} // foreach
return $a;
}
?>

Categories