I need to create two variables to run a js with this structure
var sets = [{"label":"PHP","size":"6"},{"label":"SQL","size":"1"}];
var overlaps = [ {"sets":[0,1],"size":"0"}];
I'm trying to create it dinamically with php, like this
$sets[] = array("label" =>"PHP", "size" => "6");
$overlaps[] = array("sets" => array(0,1), "size" => "0");
print json_encode(array($sets, $overlaps));
In ajax I do this
$.post(action
, {param:param}
, function(returned_data){
console.log(returned_data);
var json = $.parseJSON(returned_data);
sets = json[0];
overlaps = json[1];
});
Console.log dumps this
[[{"label":"PHP","size":"6"},{"label":"SQL","size":"1"},{"label":"JQuery","size":"1"}],[{"sets":[0,2],"size":"1"}]]
The error is "Cannot read property 'push' of undefined"
What's wrong? How can I parse json and assign each part to the variables?
I don't think you need to parse it as JSON, the console insinuates that it's already an object. Also, return is a reserved word (language construct) in almost every language, so you should get into the habit of not using it for variable names.
$.post(action
, {param:param}
, function(return_data){
return_data = typeof return_data=='object' ? return_data : $.parseJSON(return_data);
//The line above parses the string only if the browser didn't already recognize it as a JSON-object.
console.log(return_data);
sets = return_data[0];
overlaps = return_data[1];
});
Also, you should set the header in your PHP ($.parseJSON certainly won't be needed then):
$sets[] = array("label" =>"PHP", "size" => "6");
$overlaps[] = array("sets" => array(0,1), "size" => "0");
header('Content-type: application/json'); //I added this line
echo json_encode(array($sets, $overlaps));
Strange error. Could be because you are using a reserved word as a variable.
jQuery $.post already expects JSON so no need for JSON parse.
$.post(action
, {param:param}
, function(returned_data){
console.log(returned_data);
var json = returned_data;
sets = json[0];
overlaps = json[1];
});
Related
I have problem with get data from memcache in nodejs.
First of all i set data in memcache with php
Php code:
$memcache = new Memcache;<br>
$memcache->connect("localhost",11211);<br>
$array = array("id"=>"1","name"=>"aaa");<br>
$memcache->set("key",$array);
After this i check if this data is set in memcache and it show:
a:2:{s:2:"id";s:1:"1";s:4:"name";s:3:"aa a";}
Everything seems to be okay. Now i want to get this data in nodejs:
Nodejs code:
var memcache = require('mem');
var client = new memcache.Client(11211,'localhost');
client.connect();
client.get('key', function(err,result){
console.log(result);
});
And here i have problem...In console i get
a:2:{s:2:"id";s:1:"1";s:4:"name";s:3:"aa a";}
And my Question is
How to get in console name : aaa ?
I only add that:
console.log(result['name']); => show : undefined
Please help
Try using a more portable format to share data between the systems. E.g. JSON.
$memcache = new Memcache;
$memcache->connect("localhost",11211);
$data = json_encode(array("id"=>"1","name"=>"aaa"));
$memcache->set("key",$data);
I expect this to then show in memcache as
{ "id" : 1, "name": "aaa" }
Then you should be able to extract it as JSON:
var memcache = require('mem');
var client = new memcache.Client(11211,'localhost');
client.connect();
client.get('key', function(err,result){
console.log(result);
var entry = JSON.parse(result);
console.log(entry.name);
});
The PHP data looks likes it's being automatically serialized for you.
Instead of letting that happen, I would suggest you encode your array into JSON data prior to inserting into memcache, which you can easily decode with node.
So instead of
$memcache->set("key",$array);
do:
$memcache->set("key", json_encode($array));
And then in node, instead of:
client.get('key', function(err,result){
console.log(result);
});
do:
client.get('key', function(err,result){
var object = JSON.parse(result);
console.log(object);
console.log(object['name']);
});
Which will load that data into a JS object.
I've some JSON data in a javascript file
Data is build using javascript object literal notation;
var CMS = window.CMS = window.CMS || {};
CMS.Data = window.CMS.Data = window.CMS.Data || {};
CMS.Data['LANGUAGES'] = [
{id:"chi", value:"Chinese"},
{id:"spa", value:"Spanish"},
{id:'eng', value:"English"},
{id:"hin", value:"Hindi"},
];
CMS.Data['AGE_RANGE'] = [{id:'18', value:"18"}, {id:'25', value:"25"}, {id:'30', value:"30"}, {id:'35', value:"35"}, {id:'40', value:"40"}, {id:'50', value:"50"}, {id:'60', value:"60"}, {id:'70', value:"70"}, {id:'80', value:"80"}, {id:'90', value:"90"}, {id:'100', value:"100"}];
CMS.Data['HEIGHT_RANGE'] = [{id:'140-150', value:"140-150"}, {id:'150-160', value:"150-160"}, {id:'160-170', value:"160-170"}, {id:'180-190', value:"180-190"}];
Complete data is available at https://gist.github.com/mithunqb/675613fe985fe2afbbcf
I need to make it available in PHP array.
I cannot simply load the content and apply json_decode
$json_string = file_get_contents('data.json');
$json_array = json_decode($json_string, true);
As the content inside the json file is not actually a valid JSON string, the above operation will result NULL;
How can I do this?
If the JSON string is not valid then there is no way to convert it to PHP array. Not a chance at any circumstances. It's obvious.
You must provide a valid JSON string.
Hi all so here is a code I want to receive data in PHP.
so I have this in QT:
QUrl params;
params.addQueryItem("action","Dodaj_korisnika");
params.addQueryItem("ime","qt");
params.addQueryItem("prezime","QT");
params.addQueryItem("broj","998873");
params.addQueryItem("adresa","kkakka");
QByteArray data;
data.append(params.toString());
data.remove(0,1);
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
QNetworkReply *reply = manager->post(QNetworkRequest(url), data);
connect(reply, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));
How to write PHP to retireve array.
I have tried this:
$_FIELD=array(
"action" => $_POST{action},
"ime" => $_POST{ime},
"prezime" => $_POST{prezime},
"broj" => $_POST{broj},
"adresa" => $_POST{adresa}
its not working
and this:
$_POST array($_POST['action'],$_POST['ime'],$_POST['prezime'],$_POST['broj'],$_POST['adresa'];
still not working..any idea what is right way to get post data..
);
$_POST is like any other array in PHP and can be accessed like this:
echo $_POST['action']; // echos the value for the key "action"
To see whats in there you can use:
print_r($_POST);
Your code has syntax errors . It must be like this :
$field = array(
"action"=>$_POST["action"],
"ime"=>$_POST["ime"],
"prezime"=>$_POST["prezime"],
"broj"=>$_POST["broj"],
"adresa"=>$_POST["adresa"],
);
I am having a problem passing an array variable from Flash (AS2) to PHP. In action script I have several arrays defined like this
output["px1"]
output["px2"]
output["px3"]
and then I use the following code to pass the variables into a php file
output.sendAndLoad("orders/print2cart.php",output,"POST");
I want to know how to get the data from the array in PHP. I have tried using $_POST['px1'], $_POST['output']['px1'], $_POST['output'] but I cannot seem to get any data. Any ideas as to what I can change to get the desired result?
Thanks!
EDIT: Just noticed that I one of the other variables in output (output.username) is also not being sent to PHP, despite it showing up in flash. Using the following code to alert to flash and it does show all the variables correctly.
getURL("javascript:alert('Print Stamp: " + output.PrintStamp + " User: " + output.username "')");
EDIT: Seems like once I send a pretty long array (or a string for that matter) none of the other fields associated with the LoadVars variable are sent either. I googled it up for limits and it says text limits are ~ 63000. Still not sure if that is the problem
Try it as a String.
Use Array.join(); in flash and send the value returned by that, then use explode() in PHP convert it back to an array.
var dataOut:LoadVars = new LoadVars();
var dataIn:LoadVars = new LoadVars();
dataOut.info = your_array.join("#");
vars.sendAndLoad("url", dataIn, "post");
dataIn.onLoad = function(go:Boolean):Void
{
if(go)
{
trace('success');
}
else trace('connection failed');
}
The PHP:
<?php
$str = $_POST["info"];
$myarray = explode($str);
?>
Since there were no other alternatives and I went through a lot of stuff before finally concluding that Arrays of large sizes cannot be passed through from AS2 to PHP very easily. My array was actually an image converted to pixels, so what I did was that I split the array into 2 pieces and posted to the PHP file twice instead of only once. Another alternative would be to split and post the array to a text file first and then read that text file directly from PHP.
You can do the same as you would do with HTML, by naming your parameters "array[0]", "array[1]", etc... :
var urlVariable:URLVariables = new URLVariables();
urlVariable["phpArray[0]"] = "arrayEntry0";
urlVariable["phpArray[1]"] = "arrayEntry1";
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest("http://yourserver.com/phpScript.php");
request.method = URLRequestMethod.POST;
request.data = urlVariable;
loader.load(request);
then serverside you can verify the result received by php script :
print_r($_POST);
it should output :
Array
(
[phpArray] => Array
(
[0] => arrayEntry0
[1] => arrayEntry1
)
)
and for multiple dimension array you can use :
urlVariable["phpArray[0][0]"]
I have to send a two-dimensional JavaScript Array to a PHP page.
Indeed, I'm working on a form-builder, in which the user can add or remove fields.
These fields are added (or removed) using JavaScript (jQuery). When the user is done and hit a 'publish' button, I have to get all the fields concerned and send them to a PHP page which would build a real form with it.
I found a way to do it but I'm pretty sure it's not very clean :
addedFields = new Array();
$("#add-info .field").each(function() {
addedFields.push(new Array($(this).find('.name').val(), $(this).find('.type').val(), $(this).find('.size').val()));
});
Basically, the ".field" class objects are <tr> and the ".name", ".type" and ".size" objects are inputs.
So I get an array of [name, type, size], then I convert it into a string using
addedFields = addedFields.join(";");
Finally, I go to the PHP form that way ;
document.location.href = "create.php?addedfields=" + addedFields;
Concerning the PHP code, I create a PHP array using the explode() function:
$addedFields = explode(";", $_GET['addedfields']);
and then I use it again for each element in the array:
foreach ($addedFields as $field) {
$field = explode(",", $field);
echo "<li>Field with name : '$field[0]', of '$field[1]' type and with a size of $field[2]</li>";
}
So it works, but it seems very dirty...
Use the auto-array feature in PHP:
var data = {};
$("#add-info .field").each(function(i) {
data['field['+i+'][name]'] = $(this).find('.name').val();
data['field['+i+'][type]'] = $(this).find('.type').val();
data['field['+i+'][size]'] = $(this).find('.size').val()]);
});
$.post("target.php", data);
then on the server side
var_dump($_POST['field']);
// array(
// 0 => array(
// 'name' => ...
// 'type' => ...
// 'size' => ...
// ),
// 1 => ...
Edit: slightly more elegant version of the loop:
$("#add-info .field").each(function(i) {
for (attr in {name: 1, type: 1, size: 1}) {
data['field['+i+']['+attr+']'] = $(this).find('.'+attr).val();
}
});
Put those input fields in a form-element. Use JSON like
var formData = $('form').serializeArray();
formData = window.JSON.stringifiy(formData);
$.post('address', {addedfields: formData}, function(){});
something similar to that should do it in jQuery.
on the backend convert the JSON into an object and loop through.
Try consider using JSON to interact data between PHP and JavaScript.
JSON is built into Javascript and there is an awesome library for PHP. Check them out.