How to pass Javascript array to PHP file using AJAX? - javascript

I have to pass a Javascript arry to a PHP file while AJAX call.
Below is my js array:
var myArray = new Array("Saab","Volvo","BMW");
This JS code has to pass JS array to PHP file using AJAX request and will show count of array.
function ProcessAJAXRequest()
{
$.ajax
({
type: "POST",
url: "myphpfile.php",
data: {"id" : 1, "myJSArray" : myArray},
success: function (data)
{
alert(data);
}
});
}
This myphpfile.php file has to return the count of the array
<?php
$myPHPArray = $_POST["myJSArray"];
echo count($myPHPArray);
?>
There is error in PHP file. I am getting undefined index: myPHPArray. How should acheive my required functionality?

Convert js array in json format by JSON.stringify
function ProcessAJAXRequest()
{
$.ajax
({
type: "POST",
url: "myphpfile.php",
data: {"id" : 1, "myJSArray" : JSON.stringify(myArray)},
success: function (data)
{
alert(data);
}
});
}
And In the PHP use json_decode function to get value in array
json_decode($_POST["myJSArray"]);

Use JSON.stringify to converts a value to JSON and send it to server.
data: JSON.stringify({"id" : 1, "myJSArray" : myArray})

You could use JSON.stringify(array) to encode your array in JavaScript, and then use
$array=json_decode($_POST['jsondata']);
in your PHP script to retrieve it.please check this link
Pass Javascript Array -> PHP

What seems to me is that your array is not available in the function scope:
function ProcessAJAXRequest(){
var myArray = new Array("Saab","Volvo","BMW"); // this has to be in fn scope
$.ajax({
type: "POST",
url: "myphpfile.php",
data: {"id" : 1, "myJSArray" : JSON.stringify(myArray)}, // do the stringify before posting
success: function (data){
alert(data);
}
});
}

Related

cannot send json data from html to php

I cannot send JSON Data from HTML to PHP with jquery and always show fail status at console.log. Please check my code.
jsonObjects.domain = client_domain;
jsonObjects.pkg = client_package;
jsonObjects.company_name = client_company;
jsonObjects.company_email = client_email;
jsonObjects.personal_name = psn_name;
jsonObjects.personal_phone = psn_phone;
jsonObjects.personal_email = psn_email;
var JsonPush = new Array();
JsonPush.push(jsonObjects);
var JsonArray = JSON.stringify(JsonPush);
$.ajax({
type: "POST",
url: 'order.php',
data: JsonArray,
dataType: 'json',
})
.done(function (data) {
console.log('done');
console.log(data);
}).
fail(function (data) {
console.log('fail');
console.log(data);
});
Order.php file
<?php
$decoded = json_decode($_POST['data']);
var_dump($decoded);
?>
You don't need to stringify first, just post it in a keyed object and access via the key like this
let postData = { object: jsonObjects };
$.ajax({
type: "POST",
url: 'order.php',
data: postData,
dataType: 'json',
})
Then in php:
$jsonObjects = $_POST['object'];
note: you don't access the posted variable by the name of the object itself but rather the keys inside the posted object
You have no data parameter in your AJAX call. It should be:
data: { data: JsonArray },
But there really isn't any need to use JSON at all. You can just given an object as the data: option, and its properties will become POST parameters.
data: jsonObjects,
Then in PHP you can access $_POST['domain'], $_POST['pkg'], etc.

How to pass javascript variable to ajax 'data' attribute

I am tying to pass a javascript variable as an ajax paramater but it is being sent as null. Simply passing 'host' gives 'host' itself which isn't what is desired
var host = "some value"
$.ajax({
type: 'GET',
url: '/Main/GetData/',
data: '{'
hostname '=' + host '}',
dataType: 'json',
success: function(json) {
var data = json;
},
}); //ajax
Try the following:
data: {'hostname' : host},
Pass the data as an object, using key you can access the value of the variable on the server side.
USE:
var host = "some value"
$.ajax({
type: 'GET',
url: '/Main/GetData/',
data: {
"hostname": host
},
dataType: 'json',
success: function(json) {
var data = json;
},
}); //ajax
If you are trying to send data as a string make use of JSON.stringify()
dataToSend = JSON.stringify({ "hostname": host });
And in your AJAX
data : dataToSend
I feel the problem is you have made the wrong JSON data format.
the correct JSON format should be like this:{key:value}
Give an eg. here:
"employees": [
{ "firstName":"Bill" , "lastName":"Gates" },
{ "firstName":"George" , "lastName":"Bush" },
{ "firstName":"Thomas" , "lastName":"Carter" }
]
ex:the employee contains 3 elements
Wish can make some help :)

Return json from php to ajax

I'm trying to get back a json object from php to then use in my ajax.
My ajax is
$( document ).ready(function() {
var eventsListPath = "/php/eventsList.php";
$.ajax({
type: 'get',
url: eventsListPath,
data: {},
success: function(data) {
var json = JSON.parse(data);
$('#eventInformation').html(json[table]);
}
});
});
and then my php does stuff but I basically want to return a string (plus more, but getting the string to work first would probably help the rest):
$obj->table="hey";
echo json_encode($obj, JSON_UNESCAPED_SLASHES);
But the line
$('#eventInformation').html(json[table]);
seems to only give me back an error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
What am I doing wrong?
first, use the Network Monitor to see the result of the HTTP request
e.g. in Firefox : https://developer.mozilla.org/en-GB/docs/Tools/Network_Monitor
then, try this code who let jQuery do the JSON parsing in the AJAX call :
$(document).ready(function () {
var eventsListPath = "/php/eventsList.php";
$.ajax({
type: 'get',
url: eventsListPath,
data: {},
result: "json"
success: function (dataJson) {
$('#eventInformation').html(json.table);
}
});
});
Try to use . operator, also there is no need to parse the JSON string it is already in JSON form :)
$(document).ready(function () {
var eventsListPath = "/php/eventsList.php";
$.ajax({
type: 'get',
url: eventsListPath,
data: {},
success: function (data) {
$('#eventInformation').html(data.table);
}
});
});
ON PHP, ensure that you are instantiating the response data like below
$obj = new StdClass;
$obj->table="hey";
First of all you should check the response is properly parsed as json. if any data is present before the json array, javascript will throw exceptions. Use the chrome's developer tools response tab in the network option for seeing the response. If it's ok , try the below code.
$(document).ready(function () {
var eventsListPath = "/php/eventsList.php";
$.ajax({
method: "get",
url: eventsListPath,
dataType : "json",
data: {}, //data
success: function (data) {
$('#eventInformation').html(data.table);
}
});
});

converted JS array to JSON object but not able to read that json object at java servelet end

this is javascript code to create json variable and i am not able to get how to acess >this json variable at servlet end.
<script>
function()
{ alert("sending");
var Jsonobj=JSON.stringify(folderarray);
alert(Jsonobj);
$.ajax({ url: '/Chandrayan-2014/src/Handler/FolderHandler.java'+param,
type: 'POST',
dataType: 'json',
success: function(result) {
alert('SUCCESS'); } });
alert("sent");
}
May i suggest you to use console.log instead of alert?
also, like cloudwalker said, i see your ajax call is missing the data property
var Jsonobj=JSON.stringify(folderarray);
console.log(Jsonobj);
$.ajax({
'type' : 'POST',
'url' : '/route/to/my/handler',
'data' : Jsonobj,
'success' : function () { console.log('succeed with args %o', arguments); },
'error' : function () { console.log('failed with args %o', arguments); }
});
Note that the dataType property is used to specified the type of data that you're expecting back from the server. Not the type of data you're submiting
I don't see where you're actually passing the jsonobj as a parameter. You'd maybe want something like:
$.ajax({ url: '/myUrl',
type: 'POST',
dataType: 'json',
data: {myJsonObj: Jsonobj} --PASS THE OBJECT HERE
success: function(result) {
alert('SUCCESS'); } });
alert("sent");
I'm also a little confused about your url. Are you trying to link directly to a java source file, or did you just set up a servlet mapping that has .java at the end?

How to transfer json string to another page using jquery's ajax method?

I have a JSON string (stringified array of objects in javascript) which i intend to post to another page and then retrieve it from the $_POST variable. I used json =JSON.stringify(array).
The result gave me the following string
json = [{"keycodec":68,"eventc":"keydown","timec":1392849542994}
{"keycodec":65,"eventc":"keydown","timec":1392849543063},
{"keycodec":87,"eventc":"keydown","timec":1392849543084}]
Now I use
$( "#other").click(function() {
$.ajax({
url: 'some.php',
type: 'POST',
data: { kite : json}
});
On the page some.php I use
$kite=json_decode($_POST['kite'],true);
print_r($kite)
But nothing shows up. I have read many links on this topic and tried adding ContentType,dataType,processData parameters to the $.ajax() function but nothing helped.
What about this:
$( "#other").click(function() {
var json = [{"keycodec":68,"eventc":"keydown","timec":1392849542994}
,{"keycodec":65,"eventc":"keydown","timec":1392849543063},
{"keycodec":87,"eventc":"keydown","timec":1392849543084}];
$.ajax({
url: 'test.php',
type: 'POST',
data: "kite=" + JSON.stringify({ kite : json }),
success: function(msg){
alert(msg);
},
failure: function(errMsg) {
alert(errMsg);
}
});
});
And on your php code:
<?php
$obj=json_decode($_POST['kite']);
print_r($obj->{'kite'});
?>
Not in an elegant way on passing the json..
but this way you can still capture "kite" as post variable and decode your desired json string.

Categories