I am new to Ajax. I am currently submitting a form into my database using jQuery AJAX but it sends the same data multiple times in my database.
Here's my Ajax code :
$(document).ready(function () {
var id_js;
$(document).on('click', '.btn-success', function () {
id_js = $('#ID_TXT').val();
$('form').submit(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
$.ajax({
type: "POST",
url: 'server.php',
data: {
'Mark': 1,
'id': id_js,
},
success: function (response) {
$('#result').html(response);
}
});
return false;
});
});
});
Also I have tried .one() and .stopImmediatePropogation() but still no results
I see both form submit and Ajax call are doing the same work. If you are going to post the data only with AJAX call then form submit is not required.
I hope this works well for you.
$(document).ready(function () {
function postDataToServer() {
var id_js = $('#ID_TXT').val();
$.ajax({
type: "POST",
url: 'server.php',
data: {
'Mark': 1,
'id': id_js,
},
success: function (response) {
$('#result').html(response);
}
});
}
$(document).on('click', '.btn-success', postDataToServer);
});
The submit handler shouldn't be inside the click handler. Every time you click on the button, it adds another submit handler. So when you finally submit the form, it will submit it as many times as you clicked on the button.
If you want to ensure that the form isn't submitted until you've clicked on the button, add a test in the submit handler.
$(document).ready(function() {
var id_js;
$(document).on('click', '.btn-success', function() {
id_js = $('#ID_TXT').val();
});
$('form').submit(function(e) {
if (id_js !== undefined) {
$.ajax({
type: "POST",
url: 'server.php',
data: {
'Mark': 1,
'id': id_js,
},
success: function(response) {
$('#result').html(response);
}
});
} else {
alert("You need to click on the success button first");
}
return false;
});
});
Related
I am trying to run jquery function once modal is shown, but I close modal by clicking on the side or one close button and then open I find multiple instances of the inner function running.
<script type="text/javascript">
$(document).ready(function () {
$(".test").click(function () {
var cid = $(this).attr('cid');
$("#post-form").one('submit',function (event){
event.preventDefault();
$.ajax({
url: '{% url 'create_request' %}',
type: 'POST',
data: {
'cid': cid,
'req_num' : $('#request_number').val(),
},
success: function (data) {
console.log("success")
if (data['request']=='0')
{
alert("Request is already there");
}
else if(data['request']=='1')
{
alert("Not enough components:(");
}
$("#exampleModal").modal('hide');
}
})
})
})
})
</script>
test is the class given to button which opens bootstrap modal
post-form is the id given to my form
Attach the submit event listener outside the click function, otherwise you will create one listener per click.
$(document).ready(function () {
$("#post-form").one('submit',function (event){
event.preventDefault();
$.ajax({
url: '{% url 'create_request' %}',
type: 'POST',
data: {
'cid': cid,
'req_num' : $('#request_number').val(),
},
success: function (data) {
if (data['request']=='0')
{
alert("Request is already there");
}
else if(data['request']=='1')
{
alert("Not enough components:(");
}
$("#exampleModal").modal('hide');
}
})
})
})
This will of course break the context for this in $(this).attr('cid');, so you will have to update that to reflect the changes. I'd suggest placing it inside a hidden field in your form, or as an attribute to your modal, whatever is more convenient.
Currently i have a $(window).unload function which do some tasks on leaving that page. but i need these actions to be done only if a form is not submitted. This is what i have done so far`
$(window).unload(function () {
var flag=0;
$("#id-message-form").submit(function(){
flag=1;
});
if(flag!=1){
$.ajax({
url: "app/ajax_handler.php",
type: 'GET',
async: false,
data:{},
beforeSend: function() {
},
complete: function() {
},
success: function(data) {
}
});
}
});`
You could set a flag when a form is submitted - and then check that in your unload function.
// Set this globally
var formSubmit = false;
$('form').on('submit', function() {
formSubmit = true;
}
Then in your window unload function;
if(!formSubmit) {
// your code that submits the form
}
The issue is due to the scope of the flag variable and the submit handler. Place them outside the unload handler. I'd also suggest changing flag to a boolean value.
var formSubmitted = false;
$("#id-message-form").submit(function() {
formSubmitted = true;
});
$(window).unload(function() {
if (!formSubmitted) {
$.ajax({
url: "app/ajax_handler.php",
type: 'GET',
data: {},
async: false,
beforeSend: function() {},
complete: function() {},
success: function(data) {}
});
}
});
The submit() will no matter submit the form by default. You should try click() function to store flag value instead.
I would like to merge two JavaScripts. The first one is using ajax to send message and the second one to alert user about required field in the contact form.
I want to merge this two, maybe with an IF statement, so first to check all fields and then to send message.
1 with ajax JavaScript:
$('document').ready(function () {
$('form#contact-form').submit(function () {
var form = $(this);
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader').html('<img src="../spinner.gif" /> Please Wait...');
form.fadeOut(500, function () {
form.html("<h3>Thank you.").fadeIn();
$('#loader').html('');
});
// Normally would use this
$.ajax({
type: 'POST',
url: 'process.php', // Your form script
data: post_data,
success: function(msg) {
form.fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
return false;
});
});
2 alert JavaScript:
$('document').ready(function () {
$('form#contact-form').submit(function(e) {
var ref = $(this).find("[required]");
$(ref).each(function(){
if ( $(this).val() == '' )
{
alert("Required field should not be blank.");
$(this).focus();
e.preventDefault();
return false;
}
}); return true;
});
});
From the answer below i have create the following code.
I made this link if someone wants to help. The alert works fine but the code not stop. It continue to load the rest code.
https://jsfiddle.net/L8huq1t1/
You can do this by the following code.
function checkValidation() {
var ref = $(this).find("[required]");
$(ref).each(function(){
if ( $(this).val() == '' )
{
alert("Required field should not be blank.");
$(this).focus();
//e.preventDefault();
return false;
}
});
return true;
}
$('document').ready(function () {
$('form#contact-form').submit(function () {
if(!checkValidation()) {
return false;
}
var form = $(this);
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader').html('<img src="../spinner.gif" /> Please Wait...');
form.fadeOut(500, function () {
form.html("<h3>Thank you.").fadeIn();
$('#loader').html('');
});
// Normally would use this
$.ajax({
type: 'POST',
url: 'process.php', // Your form script
data: post_data,
success: function(msg) {
form.fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
});
return false;
});
});
But I give you a suggestion to use jquery.validate plugin which is better option. But if you still want to do like this, go ahead this is also works fine.
You can use jQuery Validation plugin that has a form submit handler where you can put your AJAX. Link to the plugin.
Your code should look something like this:
$('#contact-form').validate({
rules: {
your_input_name: {
required: true
}
},
messages: {
your_input_name: {
required: 'Field is required'
}
},
submitHandler: function() {
var form = $(this);
var post_data = form.serialize(); //Serialized the form data for process.php
$('#loader').html('<img src="../spinner.gif" /> Please Wait...');
form.fadeOut(500, function() {
form.html("<h3>Thank you.").fadeIn();
$('#loader').html('');
});
// Normally would use this
$.ajax({
type: 'POST',
url: 'process.php', // Your form script
data: post_data,
success: function(msg) {
form.fadeOut(500, function() {
form.html(msg).fadeIn();
});
}
});
return false;
}
});
i am newbie to jquery.I called a ajax when submit the form.But form submits before ajax complete the request.How to fix this issue? Below is my code
$("#formSearch").submit(
function() {
if (checkUserNumber($("#UserNumber").val())) {
$.ajax({
type : 'post',
url : 'CheckDetails.do',
data : {
userNumber:$("#UserNumber").val()
},
success : function(data) {
if (data == 'EI') {
$("#ErrMsg").text(
'User Number does not exist');
return false;
} else {
return true;
}
}
});
} else {
return false;
}
});
Any help will be greatly appreciated!!!
use event.preventDefault(); to prevent the form submission.
$("#formSearch").submit(
function(event) {
event.preventDefault();
...
...
....
});
You can apply trick to achieve your requirement, add a data attribute to target form as follows
<form id="formSearch" data-prevent-default="1">
set default value to data-prevent-attribute=1 than you can rewrite your jquery submit function as follows:
$("#formSearch").submit(function (e) {
if ($(this).data("prevent-default") === 1) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'CheckDetails.do',
data: {
userNumber: $("#UserNumber").val()
},
success: function (data) {
//on success change the value of data attribute to 0
$("#formSearch").data("prevent-default", "0");
$("#formSearch").submit(); //than call form submit again
}
}).fail(function () {
});
}
//otherwise it will submitted by default
});
I have a view with a few checkboxes that can be selected or unselected. I'd like to always register any change in a checkbox, without the use of a submit button (the user could forget to do it, and it would waste time).
So, is there a way to handle this inside the view? Up to now, I've only used the controller to do that job.
So, a piece of code :
#ModelType MvcApplication.OpportuniteDetails
#Code
ViewData("Title")="Details"
#End Code
<script type="text/javascript">
$(function () {
$(':checkbox').change(function() {
$.ajax({
url: '#Url.Action("update")',
type: 'POST',
data: { isChecked: $(this).is(':checked') },
success: function (result) { }
});
});
});
</script>
[... Some code here...]
#Html.Raw("Mail sent?") #Html.CheckBox(Model.Opportunite.Mail)
<input type="checkbox" name="mail" id="mail" onclick="test()" />
You could use AJAX:
$(function() {
$(':checkbox').change(function() {
var form = $(this).closest('form');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(result) {
}
});
});
});
In this example we subscribe to the change event of each checkbox. When this event is trigerred we look for the containing form and send its contents to the server using an AJAX request.
And if you only wanted to submit the current checkbox state to the server and not the entire form:
$(function() {
$(':checkbox').change(function() {
$.ajax({
url: '#Url.Action("SomeAction")',
type: 'POST',
data: { isChecked: $(this).is(':checked') },
success: function(result) {
}
});
});
});
where you could have a controller action which will do the necessary processing:
[HttpPost]
public ActionResult SomeAction(bool isChecked)
{
...
}
If you don't need or want AJAX and just want to submit the form, this
$(':checkbox').change(function() {
var form = $(this).closest('form');
form.get( 0 ).submit();
});
would do it.