Send jQuery array to PHP post?
I have a javascript function that collects two arrays, image and signature paths. I want to send a PHP message to the same $ _SERVER ['PHP_SELF'] page, but I really don't know where to start.
PHP:
if (isset($_POST['Submit'])) {
$edit_photos->update_xml($edit_photos->album_id, $_POST['src_arr'], $_POST['caption_arr']);
// prevent resending data
header("Location: " . $_SERVER['PHP_SELF'] . "?ref=" . $ref);
}
JS:
function getImgData() {
var imgData = { 'src_arr': [], 'caption_arr': []};
$('.album img').each(function(index){
imgData.src_arr.push($(this).attr('src'));
imgData.caption_arr.push($(this).attr('alt'));
});
return imgData;
};
HTML:
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF'] . "?ref=" . $ref; ?>">
+2
a source to share
2 answers
I would say that the procedure would look something like this:
- Add some hidden fields to the form, one for each variable you want to submit (optional, you can add hidden fields later with javascript / jquery).
- Use javascript to change the values ββof these hidden values ββas your javascript collects information, serializes objects and arrays (changes and / or adds, depending on whether you added hidden form fields in step 1.)
- Get values ββfrom
$_POST
in php and unserialize objects and arrays.
+1
a source to share
Here is a JQuery POST request:
$('form').submit(function() {
$.post('ImageProcessor.php',
{ imgdata: getImgData() },
function() {
alert('Processed Images');
});
return false;
});
This will lead to the default send position due to return false
Here's the PHP to handle the message:
if (array_key_exists('imgData', $_POST)) {
$imgData = json_decode($_POST['imgData']);
$edit_photos->update_xml($edit_photos->album_id, $imgData['src_arr'], $imgData['caption_arr']);
}
It's just a POST ajax request.
0
a source to share