简体   繁体   中英

Submit two forms in one event

Basically I have this onclick event that serializes some form data and saves it to a variable, when the user runs another function I want to be able to send that previously created variable through ajax in the function.

Here is the onclick event (first form):

$('#new_shout_next').on('click', function () {
    var new_shout_slide_1_form = $("#new_shout_form").serialize();
});

Here is the function that is performed after the onclick event, so hopefully you can get what I mean (second form):

function uploadFile(){

    var file = _("new_shout_upload_pic").files[0];


    var formdata = new FormData();
    formdata.append("new_shout_upload_pic", file);
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", progressHandler, false);
    ajax.addEventListener("load", completeHandler, false);
    ajax.addEventListener("error", errorHandler, false);
    ajax.addEventListener("abort", abortHandler, false);
    ajax.open("POST", "scripts/dashboard/dash_new_shout_upload.php");

    var new_shout_slide_1_form = $("#new_shout_form").serialize(); //This is the edit i have made and removed this line of code from the on click event above
    ajax.send(formdata, new_shout_slide_1_form);

}

And just in case you need it here is the dash_new_shout_upload.php :

     $fileName = $_FILES["new_shout_upload_pic"]["name"]; 
     $fileTmpLoc = $_FILES["new_shout_upload_pic"]["tmp_name"];
     $fileType = $_FILES["new_shout_upload_pic"]["type"];
     $fileSize = $_FILES["new_shout_upload_pic"]["size"]; 
     $fileErrorMsg = $_FILES["new_shout_upload_pic"]["error"];

     $new_shout_text = $_POST['hiddenNewShoutText']; //This is one of the fields in the serialized form first created in the onclick event.

Here is the error I get in the console:

Uncaught ReferenceError: new_shout_slide_1_form is not defined

Sorry if this is a bit confusing, basically the short story is that I want to be able to submit two forms in one event, so my idea was to save the first form and submit it with the second one.

Thanks and let me know if you need anything else.

EDIT

Ok basically musa has given me this code below

 function uploadFile(){
    var file = _("new_shout_upload_pic").files[0]; 
    var formdata = new FormData($("#new_shout_form")[0]);// add new_shout_form fields to the formdata object
    formdata.append("new_shout_upload_pic", file);
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", progressHandler, false);
    ajax.addEventListener("load", completeHandler, false);
    ajax.addEventListener("error", errorHandler, false);
    ajax.addEventListener("abort", abortHandler, false);
    ajax.open("POST", "scripts/dashboard/dash_new_shout_upload.php");

    ajax.send(formdata);

}

Which will obviously work better as it will send both the new_shout_form data along with the uploaded file. The problem is i can't seem to access the new_shout_form fields in the php script, i can access and get the file ok such as this $fileName = $_FILES["new_shout_upload_pic"]["name"]; However, i am not sure how to get the field in the new_shout_form into variables. I have tried $new_shout_text = $_FILES["dash_new_shout_location"]; and $new_shout_text = $_POST["dash_new_shout_location"]; However i get the error Undefined index: dash_new_shout_location Any ideas?

EDIT 2

This is an edit for Musa's recent comment here are the two forms, the first is the first one the users submit with the text inputs and the second one is the file.

First form, when this is submitted the textarea div content is set to the hidden input, then the second form is diplayed for the user to select the file/image

        <form id="new_shout_form">      

                        <div class="dash_new_shout_content">
                                <div id="dash_new_shout_textarea" name="dash_new_shout_textarea" class="dash_new_shout_textarea" contenteditable="true" placeholder="Write your shout..."></div>
                                <input id="hiddenNewShoutText" name="hiddenNewShoutText" type="hidden"></input>
                        </div><!--end dash_new_shout_content-->

                        <div class="dash_new_shout_options">
                            <input name="new_shout_next" type="button" id="new_shout_next" class="new_shout_finish" value="Next" alt="Next" />
                            <div class="dash_new_shout_cancel" id="new_shout_cancel">Cancel</div><!--end dash_new_shout_cancel-->   
                        </div><!--end dash_new_shout_options-->

            </form>

Form 2 with the file upload, when this one is submitted i want it to send the inputs from form 1 with it.

<form id="new_shout_2_form" enctype="multipart/form-data" method="post">


                <div class="dash_new_shout_content">

                    <div id="dash_new_shout_new_pic">
                        <img id="new_shout_img" src="#" class="new_shout_img" width="100%" />           
                    </div><!--end dash_new_shout_new_pic-->

                    <div class="dash_new_shout_content_option_pic"> 
                        <div class="dash_new_shout_pic_file_upload_wrapper">
                            <input name="dash_new_shout_pic_name" id="new_shout_upload_pic" type="file"  /><span id="dash_new_shout_pic_file_upload_span">Upload from Computer</span>
                        </div><!--end dash_new_shout_pic_file_upload_wrapper-->     
                    </div><!--end dash_new_shout_content_option-->

                </div><!--end dash_new_shout_content-->
                <br style="clear: both">

                <progress id="new_shout_image_progress_bar" value="0" max="100" style="width:80%;"></progress>
                <div id="progress_status">0%</div> 
                <div id="new_shout_image_status"></div> 
                <div class="dash_new_shout_options">

                    <input name="new_shout_finish" type="button" id="new_shout_finish" onclick="uploadFile()" class="new_shout_finish" value="Finish" alt="Finish" />
                    <div class="dash_new_shout_cancel" id="new_shout_back">Back</div><!--end dash_new_shout_cancel-->

                </div><!--end dash_new_shout_options-->
            </form><!--end new_shout_2_form-->

You should just get the data when you are going to post it, get all the data in the upload function

function uploadFile(){
    var file = _("new_shout_upload_pic").files[0]; 
    var formdata = new FormData($("#new_shout_form")[0]);// add new_shout_form fields to the formdata object
    formdata.append("new_shout_upload_pic", file);
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", progressHandler, false);
    ajax.addEventListener("load", completeHandler, false);
    ajax.addEventListener("error", errorHandler, false);
    ajax.addEventListener("abort", abortHandler, false);
    ajax.open("POST", "scripts/dashboard/dash_new_shout_upload.php");

    ajax.send(formdata);

}

I think you need to define var new_shout_slide_1_form = ''; outside your on event, then inside the on event just new_shout_slide_1_form = $("#new_shout_form").serialize(); . This will get rid of the error.

I already had this problem. The best thing you can do is this:

-- Submit data form as normal ajax and return the mysqlID -- Use that to submit second form in the callback of the first

BELIEVE ME: it's going to save you a lot of headache

It appears that your FormData object is not working correctly.

 var formdata = new FormData($("#new_shout_form")[0]);// add new_shout_form fields to the formdata object
formdata.append("new_shout_upload_pic", file);

The reason the "new_shoud_upload_pic" is working is because it is explicitly defined.

A method to test this theory is to use var_dump on the $_POST variable and see what data is being posted.

<?php
   //show $_POST index values
   var_dump($_POST);...
?>

If the post values don't exist, then you know the problem is in the HTML, but it could be that one of the name fields in the form is misspelled.

If indeed the $_POST global variable doesn't contain your form field name and values, there is a problem in the FormData object.

You can try replacing the jQuery method by using document.getElementById. Another possible solution would be to manually loop through the fields in the form and append them to the FormData object.

This Mozilla Developer Site gives some instruction and samples of how to use FormData and pass with an XMLHttpRequest as well as looping through the form fields.

Why make it so complicated?

function checkForm(button) {

      formOk = false;

      if (button = 'first') {
        //check form
        if (formOk) myform.submit();
      }

      if (button = 'second') {
        //check form using other logic
        if (formOk) myform.submit();
      }

    }


    <input type="button" onClick="checkForm('first');" value = "button 1">
    <input type="button" onClick="checkForm('second');" value = "button 2">

Simple just add a closure!

$(function(){
var new_shout_slide_1_form  = "";

$('#new_shout_next').on('click', function () {
    new_shout_slide_1_form = $("#new_shout_form").serialize();
});

function uploadFile(){

    var file = _("new_shout_upload_pic").files[0];


    var formdata = new FormData();
    formdata.append("new_shout_upload_pic", file);
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", progressHandler, false);
    ajax.addEventListener("load", completeHandler, false);
    ajax.addEventListener("error", errorHandler, false);
    ajax.addEventListener("abort", abortHandler, false);
    ajax.open("POST", "scripts/dashboard/dash_new_shout_upload.php");


    ajax.send(formdata, new_shout_slide_1_form);

}

});

将数据保存在cookie中:

document.cookie = "key1=value1;key2=value2;expires=date";

You can kick of two AJAX calls on two concurrent threads to simultaneously submit each of the forms. You will have to implement the Concurrent.Thread JavaScript library, which is free and open source towards this end.

You can download it from here: http://sourceforge.net/apps/mediawiki/jsthread/index.php?title=Main_Page

Tutorial explaining the use of the library can be found here: http://www.infoq.com/articles/js_multithread

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM