ASP.NET MVC 2 Post AJAX from from JavaScript - javascript

I got control with strongly typed View, with Ajax.BeginForm(). Now I would like to change submit method from
<input type="submit" id="testClick" value="Submit" />
To some javascript method DoSubmit().
What I tried is :
Invoke click on that submit button
Invoke submit on form ('form1').submit(), document.forms['form1'].submit()
jQuery forms with ('form1').AjaxSubmit();
Create jQuery AJAX
$.ajax({
type: "POST",
url: $("#form1").attr("action"),
data: $("#form1").serialize(),
success: function() {
alert("epic win!!!1!1!")
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("epic fail!")
}
});
All those method created normal request (not AJAX), or they didn't work. So anyone know how I can do AJAX submit "Form", from JavaScript and strongly typed mechanism (public AcrionResult MyFormAction(FormModel model); ) will work?

I've had this work fine for me using the forms plugin for jquery. What I found tho, was that I had to handle the click event, do the ajax submit and then return false to ensure that the normal post didn't occur.
<script type="text/javascript">
$('#testClick').click(function(){
$('#form1').ajaxSubmit();
return false;
});
</script>

Related

ajax or post jquery method do refresh for page anyways

Have problem with snipped of jquery handler for email form submission:
Seems like submission 'hang on' when I use e.preventDefault otherwise it just load email.php page. So Any search, even add to html onSubmit="reutn false;" doesn't help. What's wrong?
if comment out preventDefault then everything works fine, but load email.php, if leave seems $ajax or $post dont do anything...
Search for prevent default, read documentation try to return false directly from script, I use jquery 3.4.1
$(function() {
var form = $('#email_form1');
form.submit( function(e) {
// problematic string
e.preventDefault();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function(data) {
window.alert(data);
form[0].reset();
$('#mail_popup').magnificPopup('close');
}
});
});
});
I expect that ajax request will execute email.php in background but it loads this page...
The problem was in using jquery slim instead standard. it hangs on $ajax unknown method :( shame on me....

Two submits one ajax one regular form

I have this form that i am trying to submit with ajax as well as the regular submit the regular submit is for creating a pdf and the ajax submit is for showing an html example for showing the preview which both work just fine if i use them both individually or use the create pdf before the preview submit but if sumbit for pdf after the preview submit it's not functional, nothing happens like regular submit button is disabled. My code is attached as folows, Do note both work fine just the regular post doesn't work if i use ajax submit first.
<script type="text/javascript">
$('#submitpdf').submit(function() {
return true;
});
$('#submitpreview').click(function() {
$('#form').submit(function(event) { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('GET'), // GET or POST
url: 'test.php', // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false;
});
});
</script>
and here is the HTMl of the form tag and the submit buttons:
<form action="dopdf.php" name="formular" id="form" method="GET" enctype="multipart/form-data">
<input type="submit" id="submitpdf" value="Create PDF" name="print" class="btn btn-primary submit-button" onclick="javascript:document.getElementById('act').value='0'" style="margin-left: 0;" />
<input id="submitpreview" type="submit" value="Preview!" name="preview" class="btn btn-primary submit-button" onclick="javascript:document.getElementById('act').value='0'" style="margin-left: 0;" />
</form>
One other thing to note is that with ajax i want to submit to "test.php" and with regular submit i want to submit to "dopdf.php".
The code for submitPreview button click does not look correct to me ( on the click handler, you are basically registering the submit event code!). Try changing to this clean version. Also, make sure to wrap your event handler code inside the document.ready event to avoid other issues.
Also you need to read the method attribute of the form, not GET attribute.
$(function(){
$('#submitpreview').click(function(e) {
e.preventDefault(); // prevent the default form submit behaviour
var _this=$(this).closest("form");
$.ajax({ // create an AJAX call...
data:_this.serialize(), // get the form data
type: _this.attr('method'), // GET or POST
url: 'test.php', // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
});
});
Since your form action value is set to dopdf.php, when user clicks that button, It will be submitted to dopdf.php. You do not need any additional jQuery click handler for that.
you could do the following
your script like this
$('#form').submit(function() {
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('GET'), // GET or POST
url: 'test.php', // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
});
and the form as it is. don't change it

Can't get values from form?

I can't get the value from the form. Due to Firebug the form is submitted tho and when I delete the js it works so it has something to do with it.
$ok= $_POST['ok']; //this doesnt work
if($ok== "ok" ){
echo "works";
}
<script type="text/javascript">
$(document).ready(function() {
var frm = $('#form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
});
ev.preventDefault();
});
});
function submitForm2() {
$('#form').submit();
}
</script>
<div onclick='submitForm2();'></div>
<form action='' method='post' id='form'>
<input type="hidden" name='ok' value="ok">
</form>
When the form is submitted, your first set of JavaScript kicks in. It:
Stops the normal submission process running
Takes the data from the form and submits it via Ajax
Since the normal form submission doesn't run, the page doesn't reload, so you don't load a new document, so you don't see the document with the ok in it loaded in the main browser window.
Since you don't have a success handler for the Ajax request, you completely ignore the response the server sends back to the JavaScript … so you don't see that document (with the ok in it) either.
If you want to see the results of an Ajax request, then you have to write JS to show you the results (or examine the Net tab of your developer tools).

submit JSON through form submit via jquery

I am trying to submit form through Jquery in MVC. If I remove form element, submit works. what is wrong with my code?
<form id="Send" method="POST">
<fieldset>
<button type="button" id="test" />
</fieldset>
</form>
<script type="text/javascript">
var data = {........}
$(function () {
$("#test").click(function() {
$.ajax({
type: "POST",
url: "http://localhost:0000/api/test",
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
});
});
});
</script>
Your page, for some reason not shown in your code, is probably behaving like it would when any form is submitting (by GETting or POSTing to its action attribute). You can, however, prevent this behavior. First, I would do your work when the form itself submits, not in a button click event. This will require two changes. (1): Change your button back to type="submit":
<button type="submit" id="test" />
And (2): Handle the "submit" event of the form instead of the "click" event of the button:
$("#Send").submit(function(e) {
// here's where you stop the default submit action of the form
e.preventDefault();
// Now execute your AJAX
$.ajax({
type: "POST",
url: "http://localhost:0000/api/test",
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
}).done(function(response) {
// handle a successful response
}).fail(function(xhr, status, message) {
// handle a failure response
});
});
Advantages of this approach:
You correctly handle the submission process no matter how it was initiated (enter button, button click, programmatically, etc.
You don't have to care what your button is called
The logic would be bound to an event that you would expect it to be
You need to cancel the default form submission, otherwise the browser will do a POST request to the current url with the form data.
$('#Send').submit(function(e) {
e.preventDefault(); // prevents the default submission
$.ajax(/* ... */);
]);
Use serialize() on the form like:
var data = $("#Send").serialize();
Edit:
Or, if you're absolutely sure you have a server side script that would handle RAW POST you could turn your form data into object and stringify that instead, like:
var data = {
'input_1': $("#Send_input_1").value(),
'input_2': $("#Send_input_2").value(),
...
'input_N': $("#Send_input_N").value()
};
data = JSON.stringify(data);
If you dont want to remove the form tags change the button tag for an anchor with the looks of a button (css) and bind the click event:
<a id = "test" href = "#">test</a>

Getting some problem with apply event to dynamic added form in Jquery

I am loading the form in dialog box via jQuery
The code is like
<form class ="form1" action="" method="post" enctype="multipart/form-data" >
...
</form>
I am using jQuery form plugin to submit form like this
$(".form1").live('submit', function(e) {
var options = {
target: '.ajaxMessage',
beforeSubmit: showRequest,
success: showResponse,
type: 'POST'
};
alert('test');
$(this).ajaxSubmit(options);
return false;
});
Now
If i load the form directly without AJAX and then i submit the form then form gets submiited successfuly without any problem. It works 10 out of 10 times
In second case I load the form dynamically. When i click on form link then i load the form dynamically in a jquery dialog box then if i click on submit form then i can see the alert but form is not submitted. But it works sometimes but sometimes not. I would say it work 2 times out of 10.
Firebug console is also not showing any error
Is there any way i can find whats problem
Firebug will usually (I actually think not at all) won't show any errors for a ajax call, instead the error will be in the ajax request(still in firebug). Click the request and then response.
My guess is that there is a problem with the params you are sending or there is something wrong with what you a returning(i.e. you return html when ajax is expecting json, this will cause success never to be fired)
Also, try to pass an error:function(jqXHR, textStatus, errorThrown){} to the ` ajaxSubmit params and see what happens.

Categories