I have set up post xmlhttprequest and it work working great. I however would like to set up the responseText to receive multiple variable in an array, comma delimited or whatever.
This is how I am currently scooping up my return php echo command.
var return_data = hrequest.responseText;
Maybe something like this?
var update = new Array();
if(response.indexOf('|$|' != -1)) {
update = response.split('|$|');
alert(update[0]);
document.getElementById("button1").value=update[1];
document.getElementById("button2").value=update[2];
}
Would be easier to send data as JSON from php.
Send JSON from php:
echo json_encode( $array);
Parse to array from responseText:
var return_data_array = JSON.parse(hrequest.responseText);
Related
I'm using $.post to return an array from a separate php file, and trying to access the values of the array in javascript by the keys, but am having trouble doing so.
Here's the post code:
$(document).ready(function(){
var limRefresh = setInterval(refreshLIM, 10000);
var dbAction = "feedRefresh";
var newestRow = <?php echo $newestRow ?>;
$.post("jsDb.php",{ action: dbAction,lastRow: newestRow },function(status){
console.log(status);
console.log(newArr['status']);
console.log(newArr.status);
console.log(newArr[0]);
});
});
Here's the excerpt of how the response is being formatted in the external php file:
echo json_encode(array("status" => "success","actId" => $newActId));
And here's the respective console logs (just trying different options):
{"status":"success","actId":"585924418"}
undefined
undefined
{
Any ideas where I'm going wrong?
The response you get as status from $.post is a string. You need to parse it order to use it as you intend. Moreover, newArr is undefined because you have not defined it anywhere. This is probably because you have reused someone else's code and missed this part:
newArr = JSON.parse(status)
The response is coming as string, so you need to parse it before you can access it as JSON:
$.post("jsDb.php",{ action: dbAction,lastRow: newestRow },function(status){
var data = JSON.parse(status);
console.log(data['status'])
console.log(data['actId'])
}
I have problem with send array in $.post to php.
var_dump result is "NULL"
JSON.stringify doesn't work..
JQUERY
var photobox = [];
photobox.push(e.target.result);
$.post("../modules/upload.php",{"images[]" : photobox, count : sum},
function(data)
{
$('.list').prepend(data);
}).done(function() {
$('#files').prop('disabled', false);
$('.file-search').html("Szukaj...");
$(".img-thumbnail").removeClass("first");
$(".img-thumbnail").first().addClass("first");
e.target.result is base64 code
PHP
$images = $_POST['images'];
var_dump($images);
You can send arrays like this:
$.post('/thepage.php', {'NameOfKey': variableName});
The above code will allow VariableName to be an Array.
You would need to encode to JSON on your client, but when on your server (PHP) convert it back to an array by using json_decode:
http://php.net/manual/en/function.json-decode.php
I am going CRAZY posting a json request to a php webservice file when the object I am trying to send is multi-level. ie:
postdata = {
name:"francesco"
, age:58
, address : {
street:"my Street"
, number: 42
, city:"London"
}
}
I have tried every example on the web, but, when I read the $_POST data on the php webservice two things happen:
if I use JSON.stringify I dont get anything on $_POST or $_GET depending what method I use, and I have to read the file_get_contents('php://input') and then json_decode it (whereas calling the webservce from php I get the info tidily in my $_GET or $_POST globals),
If I use other methods I have found, I get the name and age fine, but the address comes through as "[object object]" .
My question is, is it possible, WITHOUT USING jquery, to :
- create an object in javascript (multilevel or however the right term)
- use the "XMLHttpRequest()" object to post it to the php ws?
- read it from php using the $_GET or $_POST globals (depending on method used)?
I have been going crazy for over 96 hours now!!!
Thanks!
Francesco
So many incorrect answers here.
To POST a nested object to your PHP script you can use plain js:
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://yourwebsite.com/yourscript.php");
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send({"data":postData});
To read the info server-side
$postData = $_POST['data'];
When I looked to see what PHP had actually given me with error_log(print_r($_POST['test'], true)) I got
Array
(
[name] => francesco
[age] => 58
[address] => Array
(
[street] => my Street
[number] => 42
[city] => London
)
)
It's all there.
Question #1
is it possible to create an object in javascript (multilevel or however the right term)
This is how you create an object in javascript:
var o = {
foo: "bar"
};
Question #2
is it possible to use the "XMLHttpRequest()" object to post it to the php ws?
It's not hard to find it on the web: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
The code would be something like:
var oReq = new XMLHttpRequest();
oReq.open("POST", "http://www.example.org/target");
oReq.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
oReq.send(JSON.stringify(postdata));
Question #3
is it possible to read it from php using the $_GET or $_POST globals (depending on method used)?
No, you can't. As the docs say, $_POST is:
An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.
So the $_POST is usable only if you're passing form encoded data. Since you're passing a JSON, you're supposed to parse the request body by yourself.
From what I understand, it is not possible to post data to php from jscipt unless it's a form. but I can do this:
if ($_POST != null)
$req = $_POST;
else {
$json = file_get_contents('php://input');
$req = json_decode($json, true);
}
.. and then just read the $req ..
Is this VERY dirty or commonplace??
I have my client app sending a json object to server which is in php.
Client side code:
var jacc = JSON.stringify(acc);console.log(acc);
$http.post($rootScope.url+'signup.php',jacc)
.then(function(response){console.log(response.data);});
which works perfectly fine.
But at server side
$acc = $_POST["jacc"];
$code = $_POST["code"];//received later
if($acc){
echo 1;//this thing never echoed.
}
elseif ($code && matchCode($code)){
if(addAcc($acc))
echo 1;
}
else echo 0 ." failed";
die();
The output at the console will be always "0 failed". Tried changing the post request to httpbin.org/post which works well. so the problem is with my php script. Also tried a var_dump($_POST) which also returns null value.
Your JavaScript code should be something like :
var params = { jacc : JSON.stringify(acc) };
// or var params = acc; if acc is already an object with the "jacc" property
$http.post($rootScope.url+'signup.php', params)
.then(function(response){
console.log(response.data);
});
Your error is that you try to post a "string" when you need to post an object with key:value.
tiltem saved my day.. thanks to dievardump for help.. Finally i got the issue and able to fix it. When using JSON content-type the $_POST array will not populate. All i had to do to fix it was
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);
I am beginner in this stuff, but I am learning quite quick so I would appreciate any kind of help.
On example i have something object like
function shape(name, size)
{
this.name = name;
this.size = size;
// some functions
}
and I am creating an array of this (this is just example)
var shape1 = new shape("Square", 10);
var shape2 = new shape("Circle", 5);
var array_of_shapes = [shape1, shape2];
I need to send all shapes (name and size values in this case) into php in json or any other format that will allow me to send it to MySQL database
I don't know how jQuery / Ajax works, so I am trying to avoid this way if possible
I am not sure if title is correct when I am calling this a "class" actually
When you got shapes values in array.. now you can send all values on server using AJAX..
$.ajax({
url: 'http://www.domain.com/xyz',
dataType: 'json',
data : JSON.stringify(array_of_shapes),
success: function(data){
//server response in data variable
}
})
and on the server side you can receive json data as
<?php
$json_data = file_get_contents("php://input");
$json_array = json_decode($json_data, true);
echo '{msg: "data posted"}';
die;
?>
kinldy follow and check the link hopefully you will get to understand what you are trying to achieve.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_native_JSON
after value get returned as json you can save it to PHP variable.