简体   繁体   中英

Submitting form data as JSON using ajax POST

So I have a form with a 3 hidden pre-filled input fields and 2 text input fields. I am trying to submit this form data using AJAX post as a JSON. Upon hitting the submit button, I get the url as :

http:myurl.com:7001/pagename/?obj1=val1&obj2=val2&obj3=val3&obj4=val4

after this I wrote some code which I have mentioned to convert these as JSON and then post it.

The problem which I am getting is:

How can I integrate the code I mentioned into the submit button, so that, as soon as the user click the submit button, the url as mentioned above is obtained and everything else (as mentioned in the code) happens in the background and the ajax post request is made.

Thanks. I am sorry if anything is unclear.

//This is the code, and If I run it in console after clicking the submit button then I am able to do the ajax post successfully. I want to integrate this code to the submit button.

var urlvalue = location.search.substring(1).replace(/\+/g, '%20');
var postdata = JSON.parse('{"' + decodeURIComponent(urlvalue).replace(/&/g, '","').replace(/=/g,'":"') + '"}');
console.log(urlvalue);

const URL = myurl;

$.ajax({
                       url:URL,
                           type:'POST',
                          data: postdata,                    
                            success: function(result){
                                console.log(result);
                            },
                            error: function(error){
                                console.log(`Error $(error)`);
                            }
                    });

I'm not sure I understand your question exactly, but if you just want the form submission to POST the data somewhere, you will have to provide a function to the form 's onsubmit attribute.

That function should contain pretty much the working code you have at the bottom of your question (as well as cancelling the default form action with event.preventDefault() ).

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