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>
Related
I'm working on a message board and inputs forms have to be validated if javascript is disabled. If javascript is enabled it has to have AJAX to stop refresh and submit form.
I have an html form which is validated by php. And now I'm trying to add jquery and ajax to stop page refresh.
I added a loading gif and inactive inputs field on submit button. But when I add $.ajax gif won't stop spinning and fields won't become active. After I refresh the page I can see that the input data was added to database.
I'm quite new in using ajax and maybe you could help me find a solution to my problem.
here is my code:
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
// getting input values by id
var fullname = $("#fullname").val();
var message = $("#message").val();
// array for input values
var data = { fullname : fullname,
message : message };
//disabled all the text fields
$('.text').attr('disabled','true');
//show the loading sign
$('.loading').show();
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "validation.php",
//dataType : 'json',
data: data,
cache: false,
success: function(data){
alert('success');
}
}).done(function(result) {
if (result == "")
form.submit();
else
alert(result);
}).fail(function() {
alert('ERROR');
});
});
});
I get success and input value alert, when I use dataType : 'json', I get error alert.
I would appreciate any kind of help.
maybe once you display .gif image than you are not going to hide the same .gif image again although your ajax finished or stop or fail (in any case).
So, on success of ajax add below two lines to hide .gif and enable text fields.
//enabled all the text fields
$('.text').prop("disabled", false);
//hide the loading sign
$('.loading').hide();
Whole code seems like this,
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "validation.php",
data: data,
cache: false,
success: function(data){
//enabled all the text fields
$('.text').prop("disabled", false);
//hidethe loading sign
$('.loading').hide();
alert('success');
}
});
I have this Ajax code to submit a PHP form. The code works, however I would like the <div> that the content is supposed to change to refresh without the whole page refreshing.
The div's ID is #container.
Here is the AJAX code:
$('.accept_friend').submit(function(){
var data = $(this).serialize();
$.ajax({
url: "../accept_friend.php",
type: "POST",
data: data,
success: function( data )
{
//here is the code I want to refresh the div(#container)
},
error: function(){
alert('ERROR');
}
});
return false;
});
You will have to change the DIV's innerHTML property.. with jQuery it is done like so:
$('#container').html('... new content goes here...');
so in your case add in the success function:
$('#container').html(data);
or
$('#container').html(data.someAttribute);
depending on the type and structure of your returned data.
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
I have a bit of code that's "working," but is not doing what I want it to do.
On my page, I have a bit of code in the header:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="update.js"></script>
and inside my main page, I have:
<form id="updateChanges" method="POST" action="update.php">
...code...
</form>
When I click the button inside of this form, I want the code inside of update.js to execute, but the page redirects to update.php and executes my code successfully instead. I am trying to bypass this redirect, and execute the code without doing a page refresh. I do not understand why it's not working.
I got the .js from a tutorial on how to use AJAX.
$(function() {
// Get the form.
var form = $('#updateChanges');
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
});
});
my javascript file is not being called. Why?
You've already defined jQuery form object in the form variable, you do not need to wrap it for jQuery again.
All instances of $(form) become: form
$(function() {
// Get the form.
var form = $('#updateChanges');
// Set up an event listener for the contact form.
form.submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = form.serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData
});
});
});
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>