i tried to submit multiple form using ajax, but how to send one by one, i mean send the first ajax after done/success then send second ajax, below is my script:
<form>
<input type="text" name="name" value="john doe" size="60">
<input type="text" name="age" value="23" size="2">
</form>
<form>
<input type="text" name="name" value="Alex" size="60">
<input type="text" name="age" value="24" size="2">
</form>
<button>Submit</button>
<script>
function post_form_data(data) {
$.ajax({
type: 'POST',
url: 'https://members.lelong.com.my/Auc/Member/Feed/feed.asp',
data: data,
success: function () {
console.log('Success');
},
error: function () {
console.log('error');
}
});
}
$('button').on('click', function () {
$('form').each(function () {
post_form_data($(this).serialize());
});
});
</script>
You can try this :
function post_form_data(data,cache,i) {
$.ajax({
type: 'POST',
url: 'https://members.lelong.com.my/Auc/Member/Feed/feed.asp',
data: data,
success: function () {
console.log('Success');
i++;
post_form_data(cache.eq(i).serialize(),_cached,i);
},
error: function () {
console.log('error');
}
});
}
$('button').on('click', function () {
var _cached=$('form');
post_form_data(_cached.eq(0).serialize(),_cached,0);
});
You can add
async : false
to make it sequential.
$.ajax({
type: 'POST',
url: 'https://members.lelong.com.my/Auc/Member/Feed/feed.asp',
data: data,
async :false ,
success: function () {
console.log('Success');
},
error: function () {
console.log('error');
}
});
Note:- async : false can logically turn down behavior of ajaxified request. We discourage the use of it until its needed desperately.
You could put requests data in array, returning promise interface from function and use done/then or always:
function post_form_data(data) {
return $.ajax({
type: 'POST',
url: '/echo/html',
data: data,
success: function () {
console.log('Success');
},
error: function () {
console.log('error');
}
});
}
$('button').on('click', function () {
var requests = $('form').map(function () {
return $(this).serialize();
}).get();
var i = 0;
if (requests.length) {
makeRequest(requests, i);
}
});
function makeRequest(requests, i) {
var iPromise = post_form_data(requests[i]);
if (i < requests.length - 1) {
iPromise.done(makeRequest(requests, ++i))
}
}
Related
Can you help me on how to get the checkbox values to be a data array? I code like this, and don't get any output. Thanks for helping me.
In my html :
<input class="form-check-input delete-checkbox" type="checkbox" name="checkbox[]" id="checkbox" value="{{ $item->id }}"data-id="{{ $item->id }}">
In my JS:
function multiple_delete(id) {
const selected = [];
$(".form-check input[type=checkbox]:checked").each(function () {
selected.push(this.value);
});
if (selected.length > 0) {
dataid = selected.join(",");
$.ajax({
url: "multiple-delete",
type: "POST",
data: +dataid,
success: function (data) {
if (data["success"]) {
alert(data["success"]);
} else {
alert(data["error"]);
console.log(data);
}
},
error: function (data) {
alert(data.responseText);
},
});
}
}
My output :
First, you are using the wrong selector. You should change .form-check in the javascript to .form-check-input or .delete-checkbox. Also you can easily get values of the selected checkboxes using jquery's .map() method.
Change your javascript code to something like this
function multiple_delete(id) {
const selected = $(".delete-checkbox:checked").map((i, el) => el.value).get();
if (selected.length > 0) {
$.ajax({
url: "multiple-delete",
type: "POST",
data: selected.join(","),
success: function (data) {
if (data["success"]) {
alert(data["success"]);
} else {
alert(data["error"]);
console.log(data);
}
},
error: function (data) {
alert(data.responseText);
},
});
}
}
I have the following input HTML tag
<input type="submit" id="submitForm" value="Submit" class="btn btn-primary start" autocomplete="off" onclick="submitForm();" />
When I click on the submit button, it goes to the related JavaScript file and executes the function submitForm();
I would like to change the text of the submit form to "Please wait..." until the function is completed.
Is there a way this can be done?
This is how the submitForm() function looks like:
function submitForm() {
$("#submitForm").val("Please wait...");
if (formValidation() === true) {
submitFormInfo().done(function () {
$("#submitForm").val("Submit");
});
}
}
function submitFormInfo() {
return $.ajax({
cache: false,
url: "URLHERE"
error: function (xhr) {
},
success: function (result) {
},
async: false,
processData: false
});
}
Are you having asynchronus operation in submitform() ?
if yes then you can use following line
$("#submitForm").val("Please Wait");
You can use jquery please see:-
https://jsfiddle.net/swawrm1g/3/
I have removed:-
onclick="submitForm();"
and added:-
$('#submitForm').click(function(){
$(this).val('Please Wait...');
submitForm()
});
function submitForm() {
alert('Form submitted');
};
Simple javascript is enough to do this..
<script>
function submitForm(){
document.getElementById('submitForm').value="Please wait..";
}
</script>
<input type="submit" id="submitForm" onclick="submitForm()" value="Submit">
Use the beforeSend option on your ajax call, so in your submitForm() function, you can do something like this:
function submitForm() {
var submitForm = $("#submitForm");
if (formValidation() === true) {
$.ajax({
cache: false,
url: "URLHERE",
async: false,
type: 'post',
data: { somedata: 'here' },
beforeSend: function (){
submitForm.val("Please wait...").attr("disabled", "disabled");
},
success: function (data){
// do something
},
error: function (){
// do something
},
complete: function () {
// regardless of the response status (success/error)
// the codes below will be executed.
submitForm.val("Submit").removeAttr("disabled");
}
});
}
}
I have a form and a input type file inside.
<form id='imageform' method='post' enctype='multipart/form-data' action='php/exec/add-message-image-exec.php' style='clear:both'>
<div id='imageloadstatus' style='display:none'><img src='assets/loader.gif' alt='Uploading....'/></div>
<div id='imageloadbutton'>
<div class='file-field input-field'>
<div class='btn'>
<span>Upload</span>
<input type='file' name='file' id='photoimg'/>
</div>
<div class='file-path-wrapper'>
<input class='file-path validate' type='text'>
</div>
</div>
</div>
</form>
It performs whenever i attach an image in the input file, and an ajax will handle it to submit it automatically and save it to the database.
$(document).ready(function () {
$('#photoimg').on('change', function () {
var A = $('#imageloadstatus');
var B = $('#imageloadbutton');
$('#imageform').ajaxSubmit({target: '#preview',
beforeSubmit: function () {
A.show();
B.hide();
},
success: function () {
A.hide();
B.show();
},
error: function () {
A.hide();
B.show();
}}).submit();
});
});
My problem is that it submits the image twice and save it to my database/table twice. But when i remove the .submit(); inside my script, it only perform once but there's a small modal-like window and another screen appeared whenever i attach an image/submit.
Remove 'action' and put it in an ajax POST request instead.
$(document).ready(function () {
$('#photoimg').on('change', function () {
var A = $('#imageloadstatus');
var B = $('#imageloadbutton');
$.ajax({
url: 'php/exec/add-message-image-exec.php',
type: 'POST',
data: $('#imageform').serialize(),
beforeSubmit: function () {
A.show();
B.hide();
},
success: function (data) {
//do something with data
//ex: console.log()
console.log(data);
A.hide();
B.show();
},
error: function () {
A.hide();
B.show();
}
});
});
});
Yes, I've read the related posts on Stack Overflow. Still can't figure out why this isn't working.
HTML:
<input type="checkbox" id="#finished-checker" value="value">
<label for="finished-check">Check if assessment is complete.</label>
JavaScript:
$('#finished-checker').change(function(){
console.log("this.checked = " + this.checked);//TEST
$.post({
method: 'POST',
url: '/Answers/UpdateFinishedValue',
data: { finished: this.checked },
success: function (retobj) {
console.log(retobj);//TEST
},
error: function () {
console.log("Error ...");
}
});
});
That change function isn't being invoked. I've also tried
$('#finished-checker').bind('change',function(){
// ...
});
and I've tried putting these in $(document).readys and yada yada.
fiddle of proof: https://jsfiddle.net/c83cd6ah/
Remove # from id of the checkbox finished-checkerUse and use ajax instead of post.
$.ajax({
method: 'POST',
url: '/Answers/UpdateFinishedValue',
data: { finished: this.checked },
success: function (retobj) {
console.log(retobj);//TEST
},
error: function () {
console.log("Error ...");
}
});
I have the following js code:
$("#add_station").on('click', function () {
$(this).closest('form').submit(function () {
alert("working!");
$.ajax({
url: advoke.base_url + "/new-vendor-user/station/ajax",
method: 'post',
processData: false,
contentType: false,
cache: false,
dataType: 'json',
data: new FormData(this),
beforeSend: function () {
$('.info').hide().find('ul').empty();
$('.success_message').hide().find('ul').empty();
$('.db_error').hide().find('ul').empty();
},
success: function (data) {
if (!data.success) {
$.each(data.error, function (index, val) {
$('.info').find('ul').append('<li>' + val + '</li>');
});
$('.info').slideDown();
setTimeout(function () {
$(".info").hide();
}, 5000);
} else {
$('.success_message').slideDown();
$('#add_station').remove();
$("#station").append(data.new_station);
setTimeout(function () {
$(".success_message").hide();
}, 5000);
} //success
},
error: function () {
//db error
$('.db_error').append('<li>Something went wrong, please try again!</li>');
$('.db_error').slideDown();
//Hide error message after 5 seconds
setTimeout(function () {
$(".db_error").hide();
}, 5000);
} //error
});
});
return false;
});
When I click the button with the id add_station it alerts on click function after $($this).closest('form').submit(function(){...) it doesn't work as you can see I've put an alert 'works' after submit function.I get no errors on the console and I can't figure what the problem is. Also, the button that is clicked is inside a form.
I need to use $($this).closest('form').submit(function(){...) inside because after ajax success a new form will be generated with add station button that will use this code.
You should block the default submit trigger by using
e.preventDefault();
$(this).closest('form').submit(function (e) {
e.preventDefault();
<!--rest of the code-->
})
add a separately submit handler
$("#add_station").on('click', function () {
$(this).closest('form').submit();
});
$("form").on("submit", function (e) {
e.preventDefault();
alert("working!");
$.ajax({
url: advoke.base_url + "/new-vendor-user/station/ajax",
method: 'post',
processData: false,
contentType: false,
cache: false,
dataType: 'json',
data: new FormData(this),
beforeSend: function () {
$('.info').hide().find('ul').empty();
$('.success_message').hide().find('ul').empty();
$('.db_error').hide().find('ul').empty();
},
success: function (data) {
if (!data.success) {
$.each(data.error, function (index, val) {
$('.info').find('ul').append('<li>' + val + '</li>');
});
$('.info').slideDown();
setTimeout(function () {
$(".info").hide();
}, 5000);
} else {
$('.success_message').slideDown();
$('#add_station').remove();
$("#station").append(data.new_station);
setTimeout(function () {
$(".success_message").hide();
}, 5000);
} //success
},
error: function () {
//db error
$('.db_error').append('<li>Something went wrong, please try again!</li>');
$('.db_error').slideDown();
//Hide error message after 5 seconds
setTimeout(function () {
$(".db_error").hide();
}, 5000);
} //error
});
});
after ajax success a new form will be generated with add station
button that will use this code
If you generate a new button you have to bind the click again after it is placed to the dom.