2

I have a javascript function that gathers two arrays, imagepaths and captions. I want to send with PHP's post to the same page $_SERVER['PHP_SELF'], 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; ?>">

FFish
  • 10,538
  • 30
  • 89
  • 133
  • AFAIK jQuery does not support that. For pure JS solutions, see this question: http://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit – Tgr May 14 '10 at 01:49

2 Answers2

1

I´d say the procedure would be something like:

  1. Add some hidden fields to your form, one for every variable you want to send (not strictly necessary, you can add the hidden fields later with javascript / jquery as well).
  2. Use javascript to change the values of these hidden values as your javascript gathers the information, serializing objects and arrays (change and / or add, depending whether you already added the hidden form fields in step 1.)
  3. Get your values from $_POST in php and unserialize the objects and arrays.
jeroen
  • 88,615
  • 21
  • 107
  • 128
0

Here is a jQuery POST request:

$('form').submit(function() {
    $.post('ImageProcessor.php', 
            { imgdata: getImgData() },
            function() {
                alert('Processed Images');
            });
    return false;
});

This will over-ride default submit behavior because of the return false

Here is the PHP to process the post:

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']);
}

This is just an ajax POST request.

Gutzofter
  • 1,965
  • 22
  • 26