简体   繁体   中英

Emulate form submit with jQuery/Ajax

I would like to do a post request along with a header redirect with jQuery and Ajax. Normally when a form is submitted you are being transmitted to a different page, and the data you posted follows along (in a way that I haven't understood). This is what I want to perform with Ajax. If I do:

$.ajax({
 type: "POST",
 url: "https://hello/theurl",
 data: output,
 dataType: 'text',
 contentType: "application/x-www-form-urlencoded; charset=UTF-8",
 success: window.location = "https://hello/theurl",
 error: function(requestObject, error, errorThrown) {
        alert(error);
        alert(errorThrown);
    }
 });

..when I'm redirected to the page, it asks for missing data- so I guess that the post request isn't coordinated together with the header redirect in the same way as it is on a form post.

And the post request also fails: "No 'Access-Control-Allow-Origin'". I send the data as "text", which is a string with the inputs concatenated in the form of "a=b&". I haven't escaped this string - maybe I should use "encodeURI()" or something (it's not a url though)? But why is both the "error" and "success" being executed, shouldn't it be just either one?

I have read many examples using the .submit() method, which is activated when the user clicks the submit button. My case is different: On submit, the same page is loaded, the $_POST goes through PHP validation (on the same page), then the javascript function starts. So I don't think I can use the "submit()" function since it reacts on clicking a submit button. A different question is, can I simulate this submit click from javascript?

What you are doing in your AJAX code there (after fixing the success function) is: you are calling the "theurl" page twice, first in a POST with the data and then when that is done you are goint to it again in a GET without the data. If you want to be redirected to that url with the data, just do a form.submit().

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