Chris
Chris

Reputation:

Javascript submitting a form within a method

I have a method which prints out the order of a set of images. I need to submit this to a new php page.

I have a form which currently prints out the order to the same page.

<form action="mainpage.php" method="post">
<div style="clear:both;padding-bottom:10px">

    <input type="Button" style="width:100px" value="Show order" onclick="saveImageOrder()">

</div>

Saveimageorder() shows the image and it saves the order in a variable called orderString

function saveImageOrder()
{
    var orderString = "";
    var objects = document.getElementsByTagName('DIV');

    for(var no=0;no<objects.length;no++)
    {
        if(objects[no].className=='imageBox' || objects[no].className=='imageBoxHighlighted')
        {
             if(orderString.length>0) orderString = orderString + ',';
             orderString = orderString + objects[no].id;
        }
    }
    document.getElementById('debug').innerHTML = 'This is the new order of the images(IDs) : <br>' + orderString;    
}

How to do this?

Upvotes: 1

Views: 390

Answers (2)

smoothdeveloper
smoothdeveloper

Reputation: 2022

with plain POST (no ajax) you need to store the result of your process (image order id retrieval) in an form field:

<input type="hidden" name="imagesorder" value=""/>

in your function, you can set the value to this field after the orderString is populated:

document.getElementsByName('imagesorder')[0].value = orderString;

then submit the form, you can do this by replacing your

<input type="button" .../>

with

<input type="submit" .../>

on the server side you will then get the value in the post collection (I'm not php dev)

$_POST['imagesorder']

Upvotes: 1

jumoel
jumoel

Reputation: 1790

You can submit the form with (note that this isn't tested):

document.formname.submit();

If you need to change the action (the page to submit to) first:

document.formname.action = 'some_other_url';

If you need to submit the form asynchronously you need to use a XMLHttpRequest or something similar.

Upvotes: 2

Related Questions