Question: Get response after form submit?

Question

Get response after form submit?

Answers 3
Added at 2016-12-25 17:12
Tags
Question

I have a form that I defined with html code below:

<form id="addUser" method="post" action=@Url.RouteUrl("DefaultApi", new {controller = "User", action = "Add", httproute = "true"})>

I also have submit button:

<input type="submit" class="btn btn-primary" value="Add user" />

When I click on button the browser go to api url, but I just wand to get value from api and past it into href on page.

How I can make it?

Answers to

Get response after form submit?

nr: #1 dodano: 2016-12-25 17:12

first remove form tags and type=submit in input element. Then in javascript

$(button).click(function(){
$.ajax({
   type:'POST',
   url:/api/User/Add or /User/Add
   success: function(declare parameter that will contain value returned by api)
   {
     // update your href here using the above parameter 
   }
 });
});

Hope this helps ...

nr: #2 dodano: 2016-12-25 17:12

Addition to Daniyals answer, to pass the input values:

data={};
$("input").each(function(elem){
data[elem.name]=elem.value;
});

Then do the ajax call with the following line:

data:data,
nr: #3 dodano: 2016-12-25 18:12

As per the information you provided on the question, i assume that your web api end point accepts the form data and return the new url to which your page should redirect to.

You can use jQuery to hijack the form submit event, send the data using ajax, and once you get the response from your web api call (the new url), use that to set the new value of location.href property so that browser will issue a new GET request to that.

You have to make sure that you are preventing the normal form submit behavior. You can use the jQuery preventDefault method to do so.

$(function(){
  $("[type='submit']").click(function(e){
     e.preventDefault(); 
     var _formUrl=$(this).attr("action");
     //make the ajax call now.
   //Build an object which matches the structure of our view model class
    var model = {  Name: "Shyju", Id: 123 };
    //update the above line with data read from your form.
    $.ajax({
        type: "POST",
        data: JSON.stringify(model),
        url: _formUrl,
        contentType: "application/json"
    }).done(function(res) {       
        console.log('res', res);
        // Do something with the result :)
        window.location.href=res;
    });

  });

});

Also take a look at How to pass json POST data to Web API method as object

Source Show
◀ Wstecz