0

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)`);
                            }
                    });
  • Possible duplicate of [Submitting HTML form using Jquery AJAX](https://stackoverflow.com/questions/16323360/submitting-html-form-using-jquery-ajax) – frobinsonj Jun 21 '19 at 18:10

1 Answers1

0

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()).

Nathan Gingrich
  • 171
  • 1
  • 6
  • Hey Thanks, However, I need the default action, as the default submit is getting me the url as mentioned in the question. So what I need is basically, default action and my custom action (as mentioned in the code) to happen one after the another simultaneously when I click submit. – newbietocoding Jun 21 '19 at 19:07