I am new to PHP and Ajax so please bear with me. I've searched around and found some answers but still am having trouble. I have an array of check box input values. If a user checks an item it is added to my array list. An example would be:
listOfPrograms = [chrome, firefox, sqlworkbench]
I want to send this array list to a PHP script on my server. My current Ajax script is as follows:
function ajaxPostToPhp(listOfPorgrams)
{
$.ajax
({
url: 'script.php',
type: 'post',
data: ("listOfPrograms" : listOfPrograms), // I believe this is where my issues lies as I do not know exactly that this is doing. I have read the PHP documentation. I tried converting to JSON and kept getting a 500 error.
success: function(data)
{
console.log(data);
}
});
}
My PHP script is as folllows:
$myArray = $_Request['listOfPrograms'];
echo $myArray;
This returns only 1 item from the array. I tried setting myArray = [] but I get an undefined index.
Thanks for your help! Sorry for such a noob question.
You need to fix a few things:
1- Javascript array:
var listOfPrograms = ['chrome', 'firefox', 'sqlworkbench'];
2- Ajax Data:
function ajaxPostToPhp(listOfPrograms)
{
myListData = {};
myListData['Programs'] = listOfPrograms;
$.ajax({
url: 'script.php',
type: 'post',
data: myListData,
success: function(data)
{
console.log(data);
}
});
}
3- Php Code:
$myArray = $_POST['Programs'];
var_dump($myArray);
You are passing an array as post parameter but they can only be strings. You should convert the array to a JSON string first. An easy function for that purpose is JSON.stringify()
var listOfPrograms = ["chrome", "firefox", "sqlworkbench"]
// I guess you need strings here
function ajaxPostToPhp(listOfPorgrams) {
$.ajax ({
url: 'script.php',
type: 'post',
// Convert listOfPrograms to a string first
data: ("listOfPrograms" : JSON.stringify(listOfPrograms)),
success: function(data) {
console.log(data);
}
});
}
jquery will kindly turn array values in ajax post data to an array for you. the issue is that in php you can't just echo an array. as a commenter stated, your php file needs to look like
$myArray = $_Request['listOfPrograms'];
echo json_encode($myArray);
also you should consider using $_POST over $_REQUEST
Related
PHP: lockState.php
require '../dbconn.php';
$query = mysql_query("select id, lockState,name from register_db where Id=1");
$items = array();
while ($row = mysql_fetch_object($query)) {
array_push($items, $row);
}
echo json_encode($items);
Result from query
[{"id":"1","lockState":"No","name":"Local Application"}]
Index.php
$.ajax({
type: "POST",
url: "feed/lockState.php",
data: ({id: 1}),
cache: false,
dataType:"json",
success: function (response) {
alert(JSON.stringify(response)); // [{"id":"1","lockState":"No","name":"Local Application"}]
alert(response.name); //***undefined***
if(response.name=='Local Application'){
callMyFunction(response.name);
}
},
error: function () {
alert("Oops..!! Something wrong!);
}
});
I'm totally lost where I'm doing wrong in using 'Success' response. Even I tried to JSON.parse(response) and tried to access the key:value, but still same undefined. Please help.
response[0].name will help you.
Look at your PHP. See $items = array(); where you create an array.
Look at the data you are getting. See the [ and ] around it.
You have an array containing an object. You need to read the first value out of that array.
var object = response[0];
var name = object.name;
The way you tried would work if the response was:
{"id":"1","lockState":"No","name":"Local Application"}
But your response is:
*[*{"id":"1","lockState":"No","name":"Local Application"}*]*
The brackets mean the response is an array, [], containing an object, {};
As others have mentioned; the way to retrieve values out of an array can be done by using array_variable[0] to for example select the first.
In your example try this:
alert(response[0].name); //***undefined***
I am trying to echo a string which is structured like json, but the jquery ajax post is not able to parse it properly. What I want to know is if this string will be treated like json in the jquery json parse just like when we echo a json_encode.
echo '{"mobno":'.$mobno.',"charge":'.$charge.',"capacity":'.$capacity.'}';
ajax code:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
var Vals = JSON.parse(response);
if(!Vals){
alert("Error1");
}else{
var capacity = parseInt(Vals.capacity);
if(capacity>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
I don't get a single alert out of the 3.
As per your edit and comment, your json string is correct. You just have to change your AJAX request.
Add this setting dataType: "json" in your AJAX request if you're expecting a json object as response from server.
So your AJAX request should be like this:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
dataType: "json",
success: function(response){
// you can access json properties like this:
// response.mobno
// response.charge
// response.capacity
var capacity = response.capacity;
if(capacity > 0){
alert("worked1");
}else{
alert("worked2");
}
}
});
Just so JavaScript can differ string and properties of json, please use double quote for starting and ending the string and for json properties use single quote or vice-versa. Try that out and let me know if you could not figure that out.
As other answers suggest you need to fix the quotes of the JSON the web service is sending back in the response.
Regarding you question, everything sent back in the response is actually a string. You need to decide what to do with it once it arrives.
One of the ways to allow both client side and server side programs understand what was sent is setting the right content type header.
For JSON the best way is to set the content type header to "application/json".
If you're using php you can do this:
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);
On the client side jquery ajax you can do this:
$.ajax({
dataType: "json",
url: url,
data: data,
success: function(data, textStatus, jqXHR){}
});
In this example the "data" parameter passed to the "success" callback function is already a js object (after JSON.parse). This is due to the use of the "dataType" parameter in the ajax declaration.
Optionally, you can do this manually and write a simple $.post which receives a string and do the JSON.parse yourself.
Maybe you should do the manual parsing yourself at first, and use the console.log(data) before and after the parsing so you'd know you're doing it correctly. Then, move on to the automatic way with "dataType" set to "json".
Please see #Rajdeep Paul's JSON string correction. Then, have your response JSON object remapped to an array.
JSON string
echo "{\"mobno\":\"".$mobno."\",\"charge\":\"".$charge."\",\"capacity\":\"".$capacity."\"}";
Ajax
$.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
// map JSON object to one-dimensional array
var Vals = $.map( JSON.parse(response), function(el) { return el });
if(!Vals){
alert("Error1");
}else{
var count = parseInt(Vals.length);
if(count>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
Reference: Converting JSON Object into Javascript array
I'm getting a array of the selected checkboxes and push them into an array.
After that I JSON.stringify() the array and send it to my PHP script.
But the weird thing is that when I send the array variable, it returns strange things.
Here is the code:
var _items = new Array();
$('input:checkbox:checked.item').each(function () {
_items.push($(this).val());
});
$.ajax({
type: 'POST',
url: btn.data('url'),
data: {_token: token, items: JSON.stringify(_items)},
dataType: 'json',
success: function () {
//
}
})
When I console log the `_items variable I get a array back with the selected boxes like this:
["3", "4"]
In my PHP I do:
dd(json_decode(Input::get('items')));
But the strange thing is the _items variable returns an array of this in my PHP script:
0: 2
1: 0
2: 3
3: 1
4: 1
5: 4
6: 1
When I manually created the _items variable like so: var _items = ["3", "4"];
It does return the correct array..
EDIT: When I try to send it as a array it will return the same result as the strange thing above..
EDIT2: The code where I print the PHP array with. I catch the route with laravel (this is working as it should) and then I die and dump (dd) the input. Same as $_POST['items']:
Route::post('user/destroy/multiple', function () {
dd(json_decode(Input::get('items')));
});
EDIT3: Strange things is when I output Input::get('items') it does return a JSON string, but for some reason I just can't json_decode it..
What can be wrong with the code...?
From http://laravel.com/docs/4.2/requests:
Note: Some JavaScript libraries such as Backbone may send input to the
application as JSON. You may access this data via Input::get like
normal.
So in your JavaScript you should do the following:
$.ajax({
type: 'POST',
url: btn.data('url'),
data: {_token: token, items: _items},
dataType: 'json',
success: function () {
//
}
})
And in PHP you should do:
Route::post('user/destroy/multiple', function () {
dd(Input::get('items'));
});
The problem is that you are encoding the array to Json in your javascript code, you don't have to do that, just send the array itself, the Ajax call will encode it for you. By doing that you are encoding twice the array to Json ! Replace data: {_token: token, items: JSON.stringify(_items)} by data: {_token: token, items: _items},
You want to serialize object, not array
Change your code:
var _items = {};
and something like this
$('input:checkbox:checked.item').each(function (i,v) {
_items[i] = v;
});
I have a array variable in jQuery which is created as follows:
var values = $('input:checked').map(function() {
return this.value;
}).get();
Assume the values in the array variable as 1,2,3. I am trying to pass this variable to php using the below ajax call:
doAjaxCallDelete("delete_checked", "values");
The ajax function is written as below:
function doAjaxCallDelete(mode, values) {
$.ajax({
url: ajaxURL,
type: "post",
data: {mode: mode, values: values},
async: false,
success: function(data){
responseData = data;
},
error:function(){
alert('Connection error. Please contact administrator. Thanks.');
}
});
return responseData;
}
I am retrieving this value in php using:
$myArray = $_REQUEST["values"];
But when I echo $myArray its showing 'values' instead of the real values inside the variable.
Can anybody suggest a solution to pass values of the array variable properly. Thanks in advance.
it is the double quotes you use in the function call
doAjaxCallDelete("delete_checked", "values");
you pass a string "values" instead of variable values.
use doAjaxCallDelete("delete_checked", values); instead.
note:
use $_POST['values'];
I want to pass a javascript array to a php page using ajax POST request .How to achieve this.please help..Thanks in advance
Have a look into JSON encoding.
In PHP you can decode it using json_decode, not quite sure how you'll encode it in Javascript but it is possible
http://en.wikipedia.org/wiki/JSON
using jQuery
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
Edit
if you are creating ajax object and using it then I'll suggest to convert your data in query string send it through ajax object.
like :
var userdetails = [1,2,3,4];
var queryString = "";
for(i=0; i<userdetails.length; i++){
queryString = queryString + 'userdetails[]='+userdetails[i]+'&';
}
connect.send(queryString)
example posting with json
var array = [1,2,3,4,5,6];
$.ajax({
url: "mydomain.com/url",
type: "POST",
dataType: "json",
data: {arrayName: array},
complete: function() {
//called when complete
},
success: function() {
//called when successful
},
error: function() {
//called when there is an error
},
});
Then the json could be parsed server side.
arrays can also be sent using application/x-www-form-urlencoded - this is the default format for submitting.