I have a page called profile.php and on this page I have 4 form for user to update. I used .validation class for all 4 form. I used this for jQuery beforeSend(). So that when a form is press it will be show Validation... text.
Now I use user_profile_data() on 2 forms. When I update the form it's showing Validation... text on 2 form. BUT it's should be show on selected form.
Here is jQuery/Js I am using :
function user_profile_data (element,event){
e= $(element);
event.preventDefault();
var formData = new FormData(e.parents('form')[0]);
$.ajax({
url: 'user_profile_data',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend: function () {
$('.validation').val('Validating...');
$("#avator_upload").attr("disabled", true);
$('.account_validation_msg').html('<div class="alert alert-warning"><strong>Validating...</strong></div>');
},
success: function (data) {
$('.account_validation_msg').html(data);
$('#notification_bottom').val('SAVE DETAILS');
$('.account_validation_msg').show();
$("#avator_upload").attr("disabled", false);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
Related
I am using this code for data sent by Ajax. I am using summernote editor. My problem is when I submit by missing any field, my from shows 'required alert' and then when I fill all fields and press submit button then the form sends an Ajax request two times. Until it happens every time I miss required field.
<script type="text/javascript">
jQuery(document).ready(function (e) {
jQuery('#btnSubmit').click(function(){ //btnSubmit is submit button id
jQuery("#my_form").submit(function(event){
event.preventDefault(); //prevent default action
var post_url = jQuery(this).attr("action"); //get form action url
var request_method = jQuery(this).attr("method"); //get form GET/POST method
var form_data = new FormData(this); //Creates new FormData object
jQuery.ajax({
url: "/demo/wp-admin/admin-ajax.php?action=theme_submit",
type: request_method,
data : form_data,
contentType: false,
cache: false,
processData:false,
success:function(data){
alert ('Data Successfully Inserted');
//location.reload();
//top.location.href="admin.php?page=data_list";
},
})
});
})
});
</script>
You can extract the submit out of the click. Write a function that would submit the form, and call it when the #btnSubmit is clicked. Below is the code to help you:
jQuery('#btnSubmit').on('click', function(event) {
event.preventDefault(); //prevent default action
submitForm();
})
function submitForm() {
var post_url = jQuery("#my_form").attr("action"); //get form action url
var request_method = jQuery("#my_form").attr("method"); //get form GET/POST method
var form = $('form').get(0);
var form_data = new FormData(form) //Creates new FormData object
jQuery.ajax({
url: "/demo/wp-admin/admin-ajax.php?action=theme_submit",
type: request_method,
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function(data) {
alert('Data Successfully Inserted');
//location.reload();
//top.location.href="admin.php?page=data_list";
},
})
}
My requirement is to upload a file from a form upon clicking the custom button by using Jquery stuff.
My form details are below:
<form id="CreateAttachmentForm" method="post" enctype="multipart/form-data" action="../../FileUploadServlet" >
My file is defined as below:
<input type="file" id="fileupload1" name="fileupload1" accept="image/*,application/pdf" "/>
My custom button related code is below:
<contact:contactbutton
id="printButton"
style="position:relative; width:90px; top:27px; height:30px; left:160px;"
textTop="7px"
defaultButton="false"
tabindex=""
accesskey="C"
onClickEx="createAttachmentRequest();"
onfocus="if(event.altKey){click();}">
<u>C</u>reate
</contact:contactbutton>
Whenever the user clicks on the custom button, the form should be submitted.I have registered an onClick event event where the control should reach the function named createAttachmentRequest()
The following is my createAttachmentRequest() function:
function createAttachmentRequest() {
alert("test ");
$("#CreateAttachmentForm").submit(function() {
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://HDDT0214:8080/pqawdTestWebApp/FileUploadServlet',
type: 'POST',
data: formData,
async: false,
success: function(data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
}
But the form is not submitted when I click the custom button. I have searched various questions on SO, but no suitable solution found so far.However I could see the alert message printed which confirms that the control is reaching the function createAttachmentRequest().What's wrong with my code?
The issue is because you're attaching a submit event handler in the function - not actually submitting the form.
It would be best to remove the createAttachmentRequest() function entirely and use unobtrusive JS code to attach the event. To do that, remove the onClickEx attribute from your <contact:contactbutton> element, then use this JS code:
$(function() {
$("#CreateAttachmentForm").submit(function(e) {
e.preventDefault();
$.ajax({
url: 'http://HDDT0214:8080/pqawdTestWebApp/FileUploadServlet',
type: 'POST',
data: new FormData(this),
success: function(data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});
});
Also note that I removed async: false as it's incredibly bad practice to use it. If you check the console you'll even see warnings about its use.
You can do one of the following:
Take the submit event outside the function and remove the function like so:
$("#CreateAttachmentForm").submit(function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://HDDT0214:8080/pqawdTestWebApp/FileUploadServlet',
type: 'POST',
data: formData,
async: false,
success: function(data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
OR
inside the function remove the submit listener like so:
function createAttachmentRequest() {
alert("test ");
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://HDDT0214:8080/pqawdTestWebApp/FileUploadServlet',
type: 'POST',
data: formData,
async: false,
success: function(data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
}
After click on submit beforeSend: works but it does not call success: also there is no console error . The data also submit to database correctly ! Then why it not call the success: . Please Help
$(function() {
//hang on event of form with id=ticketForm
$("#ticketForm").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
var form = $('#ticketForm');
var submit = $('#submite');
$.ajax({
url: actionurl,
type: "POST",
data: $("#ticketForm").serialize(),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
beforeSend: function(e) {
submit.html("Booking....");
},
success: function(e) {
submit.html("Booking Completed !");
//get the message from booking.php and show it.
$(".alert").removeClass("hide");
var msg = $.ajax({
type: "GET",
url: actionurl,
async: false
}).responseText;
document.getElementById("success-message").innerHTML = msg;
setTimeout(function() { // wait for 3 secs(2)
location.reload(); // then reload the page.(3)
}, 3000);
},
error: function(e) {
console.log(e)
}
});
});
});
Console Message
Object {readyState: 4, responseText: "<strong>Seat Booked Successfully</strong>", status: 200, statusText: "OK"}
In a Ajax call 'dataType' attributes means what data format can be expect from client(browser). As per error message server is returning 'string' instead 'json'.
But on the other hand, given ajax call is expecting json data to be returned by backend server. Either provide a
valid JSON in response or change datatype to html.
In your AJAX call settings you set dataType to json, but in return you provide a string.
dataType (default: Intelligent Guess (xml, json, script, or html)) The
type of data that you're expecting back from the server. If none is
specified, jQuery will try to infer it based on the MIME type of the
response
So, you have two solutions:
Provide a valid JSON in response
Do not ask for JSON by changing your dataType value (to html), or by removing it.
I had similar problem. As you are redirecting page in success you need to use
e.preventDefault(); // to prevent page refresh
after the ajax call or
return false; // to prevent page refresh
Something like this :
$(function() {
//hang on event of form with id=ticketForm
$("#ticketForm").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
var form = $('#ticketForm');
var submit = $('#submite');
$.ajax({
url: actionurl,
type: "POST",
data: $("#ticketForm").serialize(),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
beforeSend: function(e) {
submit.html("Booking....");
},
success: function(e) {
submit.html("Booking Completed !");
//get the message from booking.php and show it.
$( ".alert" ).removeClass( "hide" );
var msg = $.ajax({type: "GET", url: actionurl, async: false}).responseText;
document.getElementById("success-message").innerHTML = msg;
setTimeout(function(){// wait for 3 secs(2)
location.reload(); // then reload the page.(3)
}, 3000);
},
error: function(e) {
console.log(e)
}
});
return false; e.preventDefault(); //any one of this options to prevent page refresh after ajax call
});
});
I have several forms on my page with different IDs. Each form has a submit button and should be handled separately.
So the if i specify the form id the code below works fine, since I have x amount of forms which are not known in advance I need to make this script more general.
$(function() {
$('#form1').on('submit', function() {
$.ajax({
type: 'post',
url: 'post.php',
dataType: 'json',
data: $('#form1').serialize(),
success: function() {
console.log($('#form1').serialize());
}
});
});
});
I am able to get the form id with the scrpt below, but I cannot figure out how to combine with the script above.
$("form").submit(function() {
var myId = this.id;
alert(myId);
});
You need to store a reference to this, so that you can access the form element that triggered the submit event within the callback:
$('form').on('submit', function() {
var self = this;
$.ajax({
type: 'post',
url: 'post.php',
dataType: 'json',
data: $(self).serialize(),
success: function() {
console.log($(self).serialize());
}
});
});
This question already has answers here:
Show image with Ajax and beforeSend
(2 answers)
Closed 8 years ago.
I'm updating my form with lots of data so that I need to set loading GiF image so that user can understand that data is inserting to db.
I'm using following jquery. Can you guys tell me how can I show this loading image before success() is execute ?
loadubg.gif (it's my loading image)
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
var cid=$('#cdid').val();
$.ajax({
url: 'editContactDetails.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data){
// getDetails(cid);
$("#success").html(data);
document.getElementById("all_contact_details").reset();
},
data: formData,
cache: false,
contentType: false,
processData: false
});
});
Use AjaxStart and AjaxComplete callbacks:
$( document ).ajaxStart(function() {
$( ".loading" ).show();
});
$( document ).ajaxComplete(function() {
$( ".loading" ).hide();
});
If you don't wan global callbacks, you can put these into the $.ajax call:
$.ajax({
...
beforeSend: function(){$( ".loading" ).show();},
complete: function(){$( ".loading" ).hide();}
...
});
Also, everyone else are suggesting you to hide the gif in success handler. This is incorrect. If an ajax call results in an error, your gif will keep on spinning. complete handler is the correct place to do that.
Just show the loading image before the call to $.ajax.
Create a div or img tag for your loading image, and set it to display:none.
<img src="loading.gif" id="loading" style="display:none"/>
and modify your script like this
$('body').on('click', '#upload', function(e){
e.preventDefault();
$("#loading").show(); //show loading
var formData = new FormData($(this).parents('form')[0]);
var cid=$('#cdid').val();
$.ajax({
url: 'editContactDetails.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data){
// getDetails(cid);
$("#success").html(data);
document.getElementById("all_contact_details").reset();
},
complete: function(){
$("#loading").hide(); //hide loading here
},
data: formData,
cache: false,
contentType: false,
processData: false
});
});
Perhaps the best way is to set your #success div to show the gif image, as soon as the #upload is clicked.
Then the success method will overwrite the gif once it is finished:
$('body').on('click', '#upload', function(e){
// SHOW IMAGE AS SOON AS AJAX STARTS
$("#success").html("<img src="loadubg.gif></img>");
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
var cid=$('#cdid').val();
$.ajax({
url: 'editContactDetails.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data){
// getDetails(cid);
// ONCE AJAX REQUEST FINISHED, OVERWRITE THE GIF IMAGE
$("#success").html(data);
document.getElementById("all_contact_details").reset();
},
data: formData,
cache: false,
contentType: false,
processData: false
});
});
Show loading image before calling jQuery.ajax(). Let's say you have a imageDiv to show that image. Use following :
$("#imageDiv").html('<img src = "loadubg.gif">');
$("#imageDiv").show();
$.ajax({
url: 'editContactDetails.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data){
// getDetails(cid);
$("#success").html(data);
document.getElementById("all_contact_details").reset();
$("#imageDiv").hide();
},
data: formData,
cache: false,
contentType: false,
processData: false
});
});
Show images just before ajax call starts and hide it after it completes. (assuming GIF image has id="gifImage"
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
var cid=$('#cdid').val();
$('#gifImage').show();// show image here
$.ajax({
url: 'editContactDetails.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
error: function(xhr, status, error) {
$('#gifImage').hide();// hide image here
},
success: function(data){
// getDetails(cid);
$('#gifImage').hide();// hide image here
$("#success").html(data);
document.getElementById("all_contact_details").reset();
},
data: formData,
cache: false,
contentType: false,
processData: false
});
});
call your script/function to show your loader during the process, and hide your loader after the process is complete.
beforeSend: function(){
//show img loader
},
complete: function(){
//hide img loader
}
Add Div in your HTML file
<div class="ajax-loader"></div>
and then add 2 new parameter in ur ajax call. Beforesend and Complete
$.ajax({
url: 'editContactDetails.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend: function() {
$(".ajax-loader").html("<img src="images/loader_image.gif">");
},
complete: function(){
$(".ajax-loader").html("");
},
success: function(data){
// getDetails(cid);
$("#loading").hide(); //hide loading
$("#success").html(data);
document.getElementById("all_contact_details").reset();
},
data: formData,
cache: false,
contentType: false,
processData: false
});