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"],
);
Related
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];
});
My rails application need to send some data to a php application, which expects a POST call.
I use the folowing code:
uri = URI.parse(apiUrl)
req = Net::HTTP::Post.new(uri.to_s, initheader = {'Content-Type' =>'application/json'})
req.basic_auth(api_key, token)
req.set_form_data({"action" => action, "data" => data})
http = Net::HTTP.new(uri.host, uri.port)
response = http.request(req)
Where data is a hash converted to json:
data = {
:key1 => val1,
:key2 => val2
}.to_json
(it is a nested hash, i.e. some values are hash as well)
My problem is that the php application receives 4 backslashes before each quotation mark:
$data_json = $_POST['data'];
error_log($data_json);
and in error log I see:
'{\\\\"key1\\\\":val1,\\\\"key2\\\\":\\\\"val2\\\\"}'
Looks like rails add one of them, but even if I remove it and replace it with the following code:
a.gsub!(/\"/, '\'')
I still get many backslashes inside the php application, hence cannot convert the string to array.
Any idea??
By using set_form_data net/http is POSTing the form as urlencoded. Its NOT posting your request body as pure JSON.
If you want to POST raw JSON you will need to follow a pattern like:
uri = URI('https://myapp.com/api/v1/resource')
req = Net::HTTP::Post.new(uri, initheader = {'Content-Type' =>'application/json'})
req.body = {param1: 'some value', param2: 'some other value'}.to_json
res = Net::HTTP.start(uri.hostname, uri.port) do |http|
http.request(req)
end
I am stuck a long time with trying to send a JSON from javascript to a PHP script : the sending is fine (I can see the JSON in fiddler) yet I receive nothing in the PHP script :
javascript:
var person = {
name: 'yoel',
age: 28
};
xmlhttp.open("POST","http://localhost:8888/statisticsdb.php",true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify(person));
php :
echo 'trying to print ' . var_dump($_POST["name"]);
I would expect obviously to see SOMETHING but var_dump returns nothing. Help would be much appreciated!
try:
$data = json_decode(file_get_contents('php://input'));
var_dump($data->name);
the reason for this is, that the body of your POST-request is:
{"name":"yoel","age":28}
though, php expects something like (ref):
name=yoel&age=28
The json string can not be parsed properly, and thus $_POST will be empty.
$_POST holds value decoded from request having Content-Type application/x-www-form-urlencoded, i.e. it parses:
param1=value1¶m2=value2
into:
array( 'param1' => 'value1', 'param2' => 'value2')
If you send data in json format, you have to json_decode it from the raw php input:
$input = file_get_contents('php://input');
$jsonData = json_decode($input);
And you'll have a PHP object filled with your json stuff.
Add this:
xmlhttp.setRequestHeader("Content-length", JSON.stringify(person).length);
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.