The Problem
I am tring to do an ajax request to a PHP script, however I am having a problem getting the data into the format that the PHP is expecting it, the PHP is expecting the data to come in as array within an array something like,
Array
(
[cv_file] => Array
(
[849649717] => Y
[849649810] => Y
)
[save] => Save CVs
)
What have I tried?
I have tried in my javascript to create an empty array and use that as the array key, something like this,
var cv_file = new Array();
$(".drag_check").draggable({helper:"clone", opacity:"0.5"});
$(".searchPage").droppable({
accept:".drag_check",
hoverClass: "dropHover",
drop: function(ev, ui) {
var droppedItem = ui.draggable.children();
cv_file = ui.draggable.children().attr('name');
var link = ui.draggable.children().attr('name').substr(ui.draggable.children().attr('name').indexOf("[")+1, ui.draggable.children().attr('name').lastIndexOf("]")-8)
$.ajax({
type:"POST",
url:"/search",
data:cv_file+"&save=Save CVs",
success:function(){
alert(cv_file)
$('.shortList').append('<li><input type="checkbox" value="Y" class="checkbox" name="remove_cv['+link+']"/><a href="/cv/'+link+'">'+link+'</a></li>');
},
error:function() {
alert("Somthing has gone wrong");
}
});
}
});
My Question
How can I get the data into the format that the PHP is expecting, I would appreciate any help that anyone can give?
Edit
On alerting what the poster in the comments suggested I get he following,
cv_file[849649717]&save=Save CVs
Thank you
You could stringify your Array/Object, then do a json_decode on the PHP side to convert the string back to an array.
EDIT : now with the correct PHP function.
To get the results in a PHP array in the back-end PHP file, you need to create a string like the following to POST back to the server:
cv_file[]=849649717&cv_file[]=849649810&save=Save CVs
I don't think you can create an associative array using this method, but the above should give you an array like the following in the $_POST
:
Array
(
[cv_file] => Array
(
0 => 849649717
1 => 849649810
)
[save] => Save CVs
)
Then you can just do a foreach:
foreach ($_POST['cv_file'] as $cv)
{
// Do something with $cv;
}
Use $(form).serializeArray() to build an array of the POST data. serializeArray API doc