This question already has answers here:
Javascript array for AJAX POST send
(2 answers)
Closed 9 years ago.
I need help, I can't find the solution. I have a javascript array which I need to pass to a php script that will store all the array values (max 3) on Session variables. My javascript array comes from a string.split call:
var indentificators = id.split("_");
What I need is some help on how to do the Ajax call and then how to get every element of the array one by one.
My main problem is the format that this data has to be sent and how to retrieve it.
PD: I would post my current ajax call code but I think it would not help, it´s all messed up.
JSON is your answer here.. Are you using a javascript library like jQuery or MooTools?
jQuery:
How do I encode a javascript object as JSON?
url = 'target.php';
data = {identificators: JSON.stringify(identificators) };
jQuery.post( url, data, , function( response ) {
//response handling
});
MooTools:
url = 'target.php';
data = { identificators: JSON.encode(identificators) };
howto post (Async) in mootools:
http://mootools.net/docs/core/Request/Request
In php:
$phpArray = json_decode($_POST['identificators']/$_POST['identificators']);
You can format your answer to send as JSON String
For example:
Javascript array:
var indentificators = id.split("_"); // [0] => 'Stack', [1] => 'Overflow'
so you can do this:
var response_to_send = "{\"var1\":" + indentificators[0] + ", \"var2\": " + indentificators[1] + "}";
here you receive this string in your php script (supposing the ajax request is successful and the value of the string in POST is 'values'):
$values = json_decode($_POST['values'])
echo $values[0]; // This print 'Stack' echo $values[1]; // This print 'Overflow'
I hope this is what your searching
var array = id.split("_");
data = JSON.stringify(array);
var url = 'you/url'
$.ajax({
type: "POST",
url: url,
data: {array: data},
});
Finaly I solved it:
var identificadors = id.split("_");
$.ajax({
url: './phpScripts/comunicador.php?method=sessioList',
type: "POST",
data: ({data: identificadors}),
success: function(){
alert('cool');
}
});
Then at my php page:
function sessioList() {
$data = $_POST['data'];
$_SESSION['list_id_product'] = $data[0];
$_SESSION['list_id_tarifa'] = $data[1];
$_SESSION['list_index'] = $data[2];
}
As I said, my main problem was the format for the data to be sent and how to get it.
Thanks all, I really appreciate it.
Related
This question already has answers here:
Javascript POST not working - Sending Javascript array to PHP
(4 answers)
Closed 4 years ago.
Trying to have data passed to a php script so the said data can be added to the session.
The debug console log returns are the following:
the quant array is correct and typeof is object, the JSON.stringified data's type is string , lastly success from the ajax success.
In the PHP script var_dump return is NULL
$('#bigsubmit').click(function() {
var quant = [];
$('.input-number').each(function() {
var tmp = {};
tmp.id = this.id;
tmp.qu = $(this).val();
quant.push(tmp);
});
console.log(quant);
var data = JSON.stringify(quant);
console.log(typeof(data));
$.ajax({
type: "POST",
url: url,
data: {
data: data
},
success: function() {
console.log("success");
}
});
the php script (url var)
<?php
session_start();
$_SESSION['test'] = $_POST['data'];
var_dump($_SESSION['test']);
?>
Your success callback function isn't taking in a parameter, try changing to this,
success:function(data) {
console.log(data);
}
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
my javascript won't go into my Database.php file.
Anyone knows what's wrong?
I know there is another thread with this question but it just doesn't work for me.
I have this in javascript
var Score = 5;
//Score insert
var postData =
{
"Score":Score
}
$.ajax({
type: "POST",
dataType: "json",
url: "Database.php",
data: {myData:postData},
success: function(data){
alert('Items added');
},
error: function(e){
console.log(e.message);
}
});
and this in php
function InsertScore(){
$table = "topscores";
if(isset($_POST['myData'])){
$obj = json_encode($_POST['myData']);
$stmt = $conn->prepare("INSERT INTO " + $table + " VALUES (?)");
$stmt->bind_param('s', $obj);
$stmt->execute();
}
else{
console.log("neen");
}
$result->close();
change this line
success: function InsertScore(data){
to this
success: function(data){
the success parameter of jquerys ajax method has to be a anonymous function (without a name) or one defined in javascript but definitely not a php function.
You should read up on variable scope, your $table variable is not defined in the scope of your function.
You also have an sql injection problem and should switch to prepared statements with bound variables.
You are trying to send an object to your PHP file instead of a JSON data type.
Try 2 use JSON2 to stringify your object like this :
var scoreINT = 9000;
var usernameSTRING = "testJSON"
var scoreOBJ = {score:scoreINT,username:usernameSTRING};
var jsonData = JSON.stringify(scoreOBJ);
this would give you the following result "{"score":9000,"username":"testJSON"}"
You would be able to send this with your AJAX if you change ( if you follow my variable names ofcourse )
data: {myData:postData}
to
data: {myData:jsonData}
This would already succesfully transfer your data to your PHP file.
regarding your error messages and undefined. the message "e.message" does not exist. so thats the "undefined" you are getting. no worries here.
I noticed the succes and error are called incorrectly. I've just deleted them because there is no need to.
Next. moving up to your PHP.
you would rather like to "DECODE" then to encode your encoded JSON.
you could use the following there :
$score = json_decode($_POST['json'],true);
the extra param true is so you are getting your data into an array ( link )
or you could leave the true so you are working with an object like you already are.
Greetings
ySomic
How to access the serialized data in a PHP file in following situation?
The code and the serialized data is as follows:
$(document).ready(function() { $(document).on('click', '#delete_url', function (e) {
e.preventDefault();
var items = new Array();
$("input:checked:not(#ckbCheckAll)").each(function() {
items.push($(this).val());
});
var str = $("#user_filter").serialize();
$.ajax({
type: "POST",
url: "manage_users.php?op=delete_bulk_users&items="+items,
data: str,
dataType: 'json',
success: function(data) {
//var message = data.success_message;
var redirect_link = data.href;
alert(redirect_link);
window.location.href = redirect_link;
}
});
});
});
The data I'm getting in after serialize in str is as follows:
op=group_filter&page=1&from_date=11%2F10%2F2000&social_login=&to_date=11%2F10%2F2013&login_criteria=all&user_name=&user_state=&user_email_id=&user_city=
Now the PHP file(manage_users.php) is as follows:
/*The code is actually one of the switch casees*/
prepare_request();
$request = empty( $_GET ) ? $_POST : $_GET ;
$op = $request['op'];
switch( $op ) {
case "delete_bulk_users":
print_r($request);/*For printing the received array of values after form submission
Here I'm not getting serialized data */
}
Thanks in advance.
The serialize function is intended to be used to create a query string for a URL from a collection of inputs (or an entire form), and will out of necessity encode characters such as / (which denotes a directory in a URL). There's no way to tell .serialize() to convert to the "proper" format because it already is.
If you're using the result of .serialize() as part of an AJAX request it's fine to do that like so:
$.ajax({
url: 'yourpage.php',
data: str, // the string returned by calling .serialize()
... // other options go here
}).done(function(response) {
// do something with the response
});
Your server should handle decoding those characters when it receives the request and provide the correct values to you.
If you're using it for something else you could try using the native JavaScript decodeURIComponent function to convert those encoded characters back, like so:
str = decodeURIComponent(str);
Note that calling decodeURIComponent and then trying to use it for an AJAX request won't work.
For more information on URI encoding take a read through the MDN entry for encodeURIComponent.
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.