1

Is it possible to submit two forms with one button? One form's values are generated from JavaScript and the other form from PHP.

I made an example to give an idea of what I'm attempting.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>

<?php
Class testing{

    function text_test(){
        ?>
        <form method="post" name="postform">
        <input type="textbox" name="text"/>
        <input type="submit" onclick ="submit_form()" name="submit"/>
        </form>
        <?php
    }

    function display(){
        echo $_POST['text'];
        echo $_POST['js_input'];
     }
 }
$test = new testing();
$test->text_test();

if(isset($_POST['js_form'])){
    $test->display();
}
?>

<script type="text/javascript">
    var jsvariable = "js_test";
</script>

<form method="post" name="js_form">
<input type="hidden" name="js_input"    value="document.getElementByName(jsvariable).value" />
</form>

<script type="text/javascript">
function submit_form(){
    $('postform').each(function () {
            $(this).ajaxForm();  //Initialize as ajaxForm
            var options = {
               context: this
            }                 
            $(this).ajaxSubmit(options); //Submit form with options above
    });
    $('js_form').each(function () {
        $(this).ajaxForm();  //Initialize as ajaxForm
        var options = {
           context: this
        }                 
        $(this).ajaxSubmit(options); //Submit form with options above
     });
 }
 </script>
user1104854
  • 2,137
  • 12
  • 51
  • 74

3 Answers3

2

I don't believe its possible to do two consecutive submit() calls, because invoking submit() means that you are making an HTTP request (GET, POST, etc..) and that the server will forward your page somewhere else. This means that the second submit() will never be reached.

It might be better to send a blocking asynchronous POST/GET call and after that call a submit() or even a second POST/GET.

Edit1

Please see this thread on how to make asynchrnonous GET requests in php. The next is quoted from this source

file_get_contents will do what you want

$output = file_get_contents('http://www.example.com/');
echo $output;

Edit: One way to fire off a GET request and return immediately.

Quoted from http://petewarden.typepad.com/searchbrowser/2008/06/how-to-post-an.html

function curl_post_async($url, $params)
{
    foreach ($params as $key => &$val) {
      if (is_array($val)) $val = implode(',', $val);
        $post_params[] = $key.'='.urlencode($val);
    }
    $post_string = implode('&', $post_params);

    $parts=parse_url($url);

    $fp = fsockopen($parts['host'],
        isset($parts['port'])?$parts['port']:80,
        $errno, $errstr, 30);

    $out = "POST ".$parts['path']." HTTP/1.1\r\n";
    $out.= "Host: ".$parts['host']."\r\n";
    $out.= "Content-Type: application/x-www-form-urlencoded\r\n";
    $out.= "Content-Length: ".strlen($post_string)."\r\n";
    $out.= "Connection: Close\r\n\r\n";
    if (isset($post_string)) $out.= $post_string;

    fwrite($fp, $out);
    fclose($fp);
}
Community
  • 1
  • 1
Moataz Elmasry
  • 2,509
  • 4
  • 27
  • 37
  • 1
    What do you mean by a blocking asynchronous POST/GET call? Can you please provide an example, I'd really appreciate it? – user1104854 Nov 14 '12 at 13:47
1

You can submit them separately via Ajax. Here's an example using jQuery and the Form Plugin. Should get you started.

     $('form').each(function () {
            $(this).ajaxForm();  //Initialize as ajaxForm
            var options = {
               success: succesCallback,
               error: errorCallback,
               context: this
            }                 
            $(this).ajaxSubmit(options); //Submit form with options above
    });
Ryan O'Neill
  • 1,710
  • 2
  • 13
  • 24
  • I tried to implement this, but nothing is posting. I updated my code above, can you please take a look? – user1104854 Nov 14 '12 at 14:43
  • My example used the jQuery Form Plugin(linked in my post). You'll need to grab that for it to work. You can do it without by serializing the form object manually and running a regular $.ajax but I find it easier to use the plugin. – Ryan O'Neill Nov 14 '12 at 16:10
1

looking at your code you are trying to submit a form and submit a secondary form afterwards...

if(isset($_POST['submit'])) {
    ?>
    <script type="text/javascript">
        document.js_form.submit();
    </script>
    <?php

if your 2nd form data is NOT dependant on the first form submitted you can simple APPEND form elements to the php form - see below

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">

    var jsvariable = "js_test";

    $(document).ready(function(){
      //append form elements here...
      $('#form').append('<input type="hidden" name="js_input" value="'+jsvariable+'" />');
    });

</script>


<?php
Class testing{

    function text_test(){
        ?>
        <form method="post" name="postform" id="form">
        <input type="textbox" name="text"/>
        <input type="submit" name="submit"/>
        </form>
        <?php
    }

    function display(){
        echo $_POST['text'] . '<br>';
        echo $_POST['js_input'];
    }
}

$test = new testing();
$test->text_test();

if(isset($_POST['submit'])) {
    $test->display();
}

?>
on_
  • 556
  • 5
  • 12
  • Thanks a lot for clearing that up! I do have one question though. Does document.ready execute when id "form" is posted? I'm assuming, because otherwise I can't figure out how it knows when to execute. – user1104854 Nov 14 '12 at 16:13
  • No the document.ready will get executed once your page has completed loading (the DOM is ready) in the browser as per jquery http://api.jquery.com/ready/ – on_ Nov 14 '12 at 18:24
  • Ok, so the PHP is executed first, the the jquery/javascript? – user1104854 Nov 14 '12 at 18:36
  • 1
    Yes, place an "alert('hi');" inside the document ready and you will see. – on_ Nov 14 '12 at 18:42