'Get response after form submit?
I have a form that I defined with html code below:
<form id="addUser" method="post" [email protected]("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?
Solution 1:[1]
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 ...
Solution 2:[2]
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,
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daniyal Awan |
| Solution 2 | Jonas Wilms |
| Solution 3 | Community |
