简体   繁体   中英

Posting HTML form using jQuery and/or AJAX

I am/have been utterly confused for several days now and cannot get my form to submit to a server. I've attempted every guide, tutorial, example and forum suggestion the internet offers and still no avail.

We can post this form to a variable number of different servers and this is done through a select/option drop down using 'id' as the variable. We use a button to submit the form and receive an XML in response which we need to see in an XML format. This XML response needs to be directed to display in an iframe within a different frameset. Below is a tid-bit of the code.

<script type="text/JavaScript" src="jQuery-1.12.4.js">
    $("#Form51").submit(function (e) {
        var url = "https://website.com:1234"; 

        $.ajax({
            type: "POST",
            url: url,
            data: $("#Form51"), 
            success: function (data) {
                alert(data); 
            }
        });

    });

</script>
</head>
<body> 

<form method="POST" name="form51" target="formresponse" id="form51">

<button>Submit</button>


....data
..data
data
</form>
</body>

Thanks if anyone can assist in resolving with me my headache on this :/

If you are submitting your data to a variable number of servers, each with different URLs, you may be running into problems with Cross-Origin Reference Sharing ( CORS ). You may need to make some changes to your web server to indicate to browsers that those other domains are valid and trusted before they will submit to and display responses from another domain.

You will need to tweak your web server to insert some additional HTTP headers. Eg:

Access-Control-Allow-Origin: http://foo.com
Access-Control-Allow-Methods: PUT, DELETE

On apache this is done by adding to one of the config files:

Header set Access-Control-Allow-Origin "http://foo.com"

I believe the form is trying to submit without running the code in your js. It's defaulting to the submit action, which isn't what you want. Try adding e.preventDefault() right after your event handler:

<script type="text/JavaScript" src="jQuery-1.12.4.js">
$("#Form51").submit(function (e) {
    e.preventDefault(); //<-----------------------------------try this here
    var url = "https://website.com:1234"; 

    $.ajax({
        type: "POST",
        url: url,
        data: $("#Form51"), 
        success: function (data) {
            alert(data); 
        }
    });

});

</script>
</head>
<body> 

<form method="POST" name="form51" target="formresponse" id="form51">

<button>Submit</button>


....data
...data
data
</form>
</body>

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