Passing JavaScript array to PHP through jQuery $.ajax
139325 просмотра
9 ответа
I want to manipulate a JavaScript array in PHP. Is it possible to do something like this?
$.ajax({
type: "POST",
url: "tourFinderFunctions.php",
data: "activitiesArray="+activities,
success: function() {
$("#lengthQuestion").fadeOut('slow');
}
});
Activities is a single dimensional array like:
var activities = ['Location Zero', 'Location One', 'Location Two'];
The script does not complete when I try this... How can I fix it?
Автор: krx Источник Размещён: 13.11.2019 11:29Ответы (9)
145 плюса
data: { activitiesArray: activities },
That's it! Now you can access it in PHP:
<?php $myArray = $_REQUEST['activitiesArray']; ?>
Автор: Valentin Golev
Размещён: 06.01.2010 03:02
12 плюса
You'll want to encode your array as JSON before sending it, or you'll just get some junk on the other end.
Since all you're sending is the array, you can just do:
data: { activities: activities }
which will automatically convert the array for you.
See here for details.
Автор: jvenema Размещён: 06.01.2010 03:0210 плюса
You need to turn this into a string. You can do this using the stringify method in the JSON2 library.
The code would look something like:
var myJSONText = JSON.stringify(myObject);
So
['Location Zero', 'Location One', 'Location Two'];
Will become:
"['Location Zero', 'Location One', 'Location Two']"
You'll have to refer to a PHP guru on how to handle this on the server. I think other answers here intimate a solution.
Data can be returned from the server in a similar way. I.e. you can turn it back into an object.
var myObject = JSON.parse(myJSONString);
Автор: James Wiseman
Размещён: 06.01.2010 03:00
9 плюса
I know it may be too late to answer this, but this worked for me in a great way:
Stringify your javascript object (json) with
var st = JSON.stringify(your_object);
Pass your POST data as "string" (maybe using jQuery:
$.post('foo.php',{data:st},function(data){... });
- Decode your data on the server-side processing:
$data = json_decode($_POST['data']);
That's it... you can freely use your data.
Multi-dimensional arrays and single arrays are handled as normal arrays. To access them just do the normal $foo[4]
.
Associative arrays (javsacript objects) are handled as php objects (classes). To access them just do it like classes: $foo->bar
.
2 плюса
I should be like this:
$.post(submitAddress, { 'yourArrayName' : javaScriptArrayToSubmitToServer },
function(response, status, xhr) {
alert("POST returned: \n" + response + "\n\n");
})
Автор: masterdany88
Размещён: 19.11.2014 08:22
1 плюс
Use the JQuery Serialize function
http://docs.jquery.com/Ajax/serialize
Автор: Gazzer Размещён: 06.01.2010 03:03Serialize is typically used to prepare user input data to be posted to a server. The serialized data is in a standard format that is compatible with almost all server side programming languages and frameworks.
1 плюс
This worked for me:
$.ajax({
url:"../messaging/delete.php",
type:"POST",
data:{messages:selected},
success:function(data){
if(data === "done"){
}
info($("#notification"), data);
},
beforeSend:function(){
info($("#notification"),"Deleting "+count+" messages");
},
error:function(jqXHR, textStatus, errorMessage){
error($("#notification"),errorMessage);
}
});
And this for your PHP:
$messages = $_POST['messages']
foreach($messages as $msg){
echo $msg;
}
Автор: I.Tyger
Размещён: 20.06.2013 05:18
1 плюс
Use the PHP built-in functionality of the appending the array operand to the desired variable name.
If we add values to a Javascript array as follows:
acitivies.push('Location Zero');
acitivies.push('Location One');
acitivies.push('Location Two');
It can be sent to the server as follows:
$.ajax({
type: 'POST',
url: 'tourFinderFunctions.php',
'activities[]': activities
success: function() {
$('#lengthQuestion').fadeOut('slow');
}
});
Notice the quotes around activities[]. The values will be available as follows:
$_POST['activities'][0] == 'Location Zero';
$_POST['activities'][1] == 'Location One';
$_POST['activities'][2] == 'Location Two';
Автор: chelista
Размещён: 26.03.2017 08:32
0 плюса
This is because PHP reads your value as a string. If I don't want to pass my data as an object (like in the previous answers, which are also fine), I just do this in my PHP:
$activitiesString = $_POST['activitiesArray'];
$activitiesArray = (explode(",",$activitiesString));
The last line splits string into bits after every comma. Now $activitiesArray is also an array. It works even if there is no comma (only one element in your javascript array).
Happy coding!
Автор: Hawthorn Размещён: 29.07.2019 07:58Вопросы из категории :
- php Как вы отлаживаете PHP-скрипты?
- php Заставьте XAMPP / Apache обслуживать файл вне htdocs
- php Как включить файлы PHP, которые требуют абсолютного пути?
- php Скрипт входа со скрытыми кнопками
- php How can I find unused functions in a PHP project
- javascript Как определить, какой из указанных шрифтов был использован на веб-странице?
- javascript Валидация клиентской стороны ASP.Net
- javascript Длина объекта JavaScript
- javascript Получение текста из выпадающего списка
- jquery Прокрутка переполненных DIV с помощью JavaScript
- jquery Экранирование строк HTML с помощью jQuery
- jquery Как сравнить HTML-сущность с JQuery
- jquery Есть ли функция "существует" для jQuery?
- jquery Как удалить все параметры в окне выбора, а затем добавить один вариант и выбрать его с помощью jQuery?
- ajax Есть ли какой-нибудь способ для передачи данных с веб-сервера в браузер?
- ajax Как получить результат из модального диалога в JQuery
- ajax Как я могу подавить диалог аутентификации браузера?
- ajax Обновление хода сервера на Rails-приложении