Get ajax success and hide form while loading? - javascript

I am trying to do an ajax registration, the following works good, it gets the data from a php function I wrote somewhere else and the registration and messages for both error and success work. But I am basically looking at:
hiding the form once the submit button is pressed
display a rotating icon,
then if success get a success message and no form
otherwise display an error.
Code:
var ajaxurl = '<?php echo admin_url('admin-ajax.php') ?>';
jQuery('#register-me').on('click',function(){
var action = 'register_action';
var username = jQuery("#st-username").val();
var mail_id = jQuery("#st-email").val();
var firname = jQuery("#st-fname").val();
var lasname = jQuery("#st-lname").val();
var passwrd = jQuery("#st-psw").val();
var ajaxdata = {
action: 'register_action',
username: username,
mail_id: mail_id,
firname: firname,
lasname: lasname,
passwrd: passwrd,
}
jQuery.post( ajaxurl, ajaxdata, function(res){
jQuery("#error-message").html(res);
});

Add id="myform" to the form element, then:
$("#myform").hide();
About the icon. When you click the button you could make the icon visible and when succeed or error then hide again.

jQuery('#register-me').on('click',function(){
$("#myform").hide();
jQuery('#loadingmessage').show();
var action = 'register_action';
var username = jQuery("#st-username").val();
var mail_id = jQuery("#st-email").val();
var firname = jQuery("#st-fname").val();
var lasname = jQuery("#st-lname").val();
var passwrd = jQuery("#st-psw").val();
var ajaxdata = {
action: 'register_action',
username: username,
mail_id: mail_id,
firname: firname,
lasname: lasname,
passwrd: passwrd,
}
jQuery.post( ajaxurl, ajaxdata, function(res){
$('#loadingmessage').hide(); // hide the loading message
$("#myform").show();
jQuery("#error-message").html(res);
});
});
An id to the form, and add a div with an image, give it an id and hide it with css.

You could use the deferred options here:
jQuery('#register-me').on('click', function () {
var action = 'register_action';
var username = jQuery("#st-username").val();
var mail_id = jQuery("#st-email").val();
var firname = jQuery("#st-fname").val();
var lasname = jQuery("#st-lname").val();
var passwrd = jQuery("#st-psw").val();
var ajaxdata = {
action: 'register_action',
username: username,
mail_id: mail_id,
firname: firname,
lasname: lasname,
passwrd: passwrd
};
jQuery.post(ajaxurl, ajaxdata)
.beforeSend(function (data, textSttus, jqxhr) {
$('#myform').hide();
alert('Show the spinner');
$('#spinner').show();
})
.done(function (data, jqxhr, settings ) {
alert("success");
})
.fail(function (event, jqxhr, settings, exception) {
alert("oops, fail");
$('#myform').show();
})
.always(function (event, jqxhr, settings ) {
alert('hide the spinner please');
$('#spinner').hide();
});
});

Related

Ajax form doesn't submits data to php on first click but submits on second click

I have a form that submits through ajax. At first click it sends the request to php but doesnt send post variables and however when i submit form for second or third time it submits the form and gets the success response. The ajax request doesn't fail on first click it just doesnt send data to php.When i check the network tab request fields show up there on the first click and have correct values but doesnt reach php. Here is my code
jQuery("#bidding-form").on('submit', function(e) {
var request_english_level = jQuery('#request_english_level').val();
var job_title = jQuery('#job_title').val();
var request_type = jQuery('#request_type').val();
var estimated_hours = jQuery('#estimated_hours').val();
var designation = jQuery('#designation').val();
var service_type = jQuery('#service_type').val();
var budget = jQuery("#budget").val();
var user_id = jQuery('#user_id').val();
var locations = jQuery('#location').val();
var payment_terms = jQuery('#payment_terms').val();
var application_no = jQuery('#application_no').val();
var deadline_apply = jQuery('#deadline_apply').val();
var close_date = jQuery('#close_date').val();
var delivery_deadline = jQuery('#delivery_deadline').val();
var experience = jQuery('#consultant_experience').val();
var description = jQuery('#request_description').val();
var formdata = new FormData();
var length = jQuery(".attachment")[0].files.length;
for (i = 0; i < length; i++) {
formdata.append('file[]', jQuery(".attachment")[0].files[i]);
}
formdata.append('action', 'save_bid_info');
var checked_skills = []
jQuery("input[name='request_skills[]']:checked").each(function() {
//checked_skills.push(parseInt(jQuery(this).val()));
formdata.append('request_skills[]', parseInt(jQuery(this).val()));
});
var languages = []
jQuery("input[name='languages[]']:checked").each(function() {
//languages.push(parseInt(jQuery(this).val()));
formdata.append('languages[]', parseInt(jQuery(this).val()));
});
formdata.append('designation', designation);
// formdata.append('request_skills', checked_skills);
formdata.append('request_type', request_type);
formdata.append('estimated_hours', estimated_hours);
formdata.append('service_type', service_type);
formdata.append('delivery_deadline', delivery_deadline);
formdata.append('job_title', job_title);
formdata.append('locations', locations);
formdata.append('request_type', request_type);
formdata.append('payment_terms', payment_terms);
formdata.append('application_no', application_no);
formdata.append('deadline_apply', deadline_apply);
formdata.append('close_date', close_date);
formdata.append('experience', experience);
formdata.append('description', description);
formdata.append('budget', budget);
// formdata.append('languages', languages);
formdata.append('request_english_level', request_english_level);
e.preventDefault();
jQuery.ajax({
url: ajax_url,
type: 'post',
dataType: 'json',
contentType: false,
cache: false,
processData: false,
data: formdata,
beforeSend: function() {
jQuery(".loader").show();
},
complete: function(data) {
jQuery('.loader').hide();
}
})
.done(function(response, textStatus, jqXHR) {
if (response.success == true) {
jQuery(".ajax-processor").hide();
} else {
jQuery(".ajax-processor").find('p').html(response.msg);
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
})
});
// PHP CODE
if(isset($_POST['budget']) && !empty($_POST['budget']))
{
// on second click this is executed
}
else
{
// on first click this is executed
}

[object Object]parsererrorSyntaxError: Unexpected token < in JSON at position 0

I am insert the data in mysql database using ajax on submitting this error will appaer .I am making this
in codeigniter framework. I am new bie to ajax.I am not able to figure out where am going wrong .Here is my code
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled', true); //set button disable
var url;
// if (save_method == 'add') {
url = "http://[::1]/sms/sms/forms/1";
// } else {
// url = "";
//// }
var radio=$('#radio').val();
var st_id=$('#st_id').val();
var branch_type=$('#branch_type').val();
bname=$('#bname').val();
bcode=$('#bcode').val();
baddress=$('#baddress').val();
var bcity=$('#bcity').val();
var zcode=$('#zcode').val();
var bstates=$('#bstates').val();
var bcountry=$('#bcountry').val();
var bpno=$('#bpno').val();
var bemail=$('#bemail').val();
var bweb=$('#bweb').val();
var Latitude=$('#Latitude').val();
var Longtitude=$('#Longtitude').val();
var noted=$('#noted').val();
var addedby=$('#addedby').val();
// ajax adding data to database
$.ajax({
type: 'ajax',
data: {st_id: st_id, branch_type: branch_type, bname: bname, bcode: bcode, baddress: baddress,
bcity: bcity, zcode: zcode, bstates: bstates, bcountry: bcountry, bpno: bpno, bemail: bemail,
bweb: bweb, Latitude: Latitude, Longtitude: Longtitude, noted: noted, addedby: addedby},
url: url,
method: 'post',
asysc: false,
dataType: 'json',
success: function (data) {
if (data.status) //if success close modal and reload ajax table
{
}
else {
}
$('#btnSave').text('Add Record'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR + textStatus + errorThrown);
$('#btnSave').text('Add Record'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
//
}
});
my php code
$submit['sys_t_id']=$this->input->post('st_id');
$submit['t_id']=$this->input->post('branch_type');
$submit['name']=$this->input->post('bname');
$submit['code']=$this->input->post('bcode');
$submit['address']=$this->input->post('baddress');
$submit['city']=$this->input->post('bcity');
$submit['zip']=$this->input->post('zcode');
$submit['state']=$this->input->post('bstates');
$submit['country']=$this->input->post('bcountry');
$submit['contact_no']=$this->input->post('bpno');
$submit['email']=$this->input->post('bemail');
$submit['web']=$this->input->post('bweb');
$submit['latitude']=$this->input->post('Latitude');
$submit['longitude']=$this->input->post('Longtitude');
$submit['note']=$this->input->post('noted');
$submit['addedby']=$this->input->post('addedby');
$submit['addedon']=date('Y-m-d:H-m-s');
$insert = $this->Smsmodal->insert('branch_info',$submit);
echo json_encode(array("status" => TRUE));
I think you have server error! Use console.log(data) in you success function for see server output.

How do I exit the click function?

So with this example I have form with a hidden field and a button called ban user. When the ban user button is clicked, it submits the value in the hidden field and sends the ajax request to a java servlet. If it is successful, the user is banned and the button is changed to "unban user". The problem is when I click the button once and ban a user and I try to click it again to unban, I'm still inside the click event for the ban user and I get the alert "Are you sure you want to ban the user with the id of ...?". How do I exit the click event to make sure when the button is clicked a second time, it starts at the beginning of the function and not inside the click function? I have tried using 'return;' as you can see below but that doesn't work.
$(document).delegate('form', 'click', function() {
var $form = $(this);
var id = $form.attr('id');
var formIdTrim = id.substring(0,7);
if(formIdTrim === "banUser") {
$(id).submit(function(e){
e.preventDefault();
});
var trimmed = id.substring(7);
var dataString = $form.serialize();
var userID = null;
userID = $("input#ban"+ trimmed).val();
$("#banButton"+ trimmed).click(function(e){
e.preventDefault();
//get the form data and then serialize that
dataString = "userID=" + userID;
// do the extra stuff here
if (confirm('Are you sure you want to ban the user with the id of ' + trimmed +'?')) {
$.ajax({
type: "POST",
url: "UserBan",
data: dataString,
dataType: "json",
success: function(data) {
if (data.success) {
//$("#banUser"+trimmed).html("");
$('#banUser'+trimmed).attr('id','unbanUser'+trimmed);
$('#ban'+trimmed).attr('id','unban'+trimmed);
$('#banButton'+trimmed).attr('value',' UnBan User ');
$('#banButton'+trimmed).attr('name','unbanButton'+trimmed);
$('#banButton'+trimmed).attr('id','unbanButton'+trimmed);
$form = null;
id = null;
formIdTrim = null;
return;
}else {
alert("Error");
}
}
});
} else {
}
});
}
else if(formIdTrim === "unbanUs") {
//Stops the submit request
$(id).submit(function(e){
e.preventDefault();
});
var trimmed = id.substring(9);
var dataString = $form.serialize();
var userID = null;
userID = $("input#unban"+ trimmed).val();
$("#unbanButton"+ trimmed).click(function(e){
e.preventDefault();
//get the form data and then serialize that
dataString = "userID=" + userID;
// do the extra stuff here
if (confirm('Are you sure you want to UNBAN the user with the id of ' + trimmed +'?')) {
$.ajax({
type: "POST",
url: "UserUnban",
data: dataString,
dataType: "json",
success: function(data) {
if (data.success) {
//$("#banUser"+trimmed).html("");
$('#unbanUser'+trimmed).attr('id','banUser'+trimmed);
$('#unban'+trimmed).attr('id','ban'+trimmed);
$('#unbanButton'+trimmed).attr('value',' Ban User ');
$('#unbanButton'+trimmed).attr('name','banButton'+trimmed);
$('#unbanButton'+trimmed).attr('id','banButton'+trimmed);
$form = null;
id = null;
formIdTrim = null;
return;
}else {
alert("Error");
}
}
});
} else {
}
});
}
});
Try with:
$("#banButton"+ trimmed).off('click').on('click', (function(e){......
I had similar problem and this was solution

unable to post id of selected dropdown to controller through knockout function

This is my Post function something like this:
function Post(data) {
var self = this;
data = data || {};
self.PostId = data.PostId;
self.Message = ko.observable(data.Message || "");
self.PostedBy = data.PostedBy || "";
self.NeighbourhoodId = data.id || "";
This is my simple function in knockout. Here at the last line u can see, data: ko.toJson(post)
self.addPost = function () {
var post = new Post();
post.Message(self.newMessage());
return $.ajax({
url: postApiUrl,
dataType: "json",
contentType: "application/json",
cache: false,
type: 'POST',
data: ko.toJSON(post)
})
.done(function (result) {
self.posts.splice(0, 0, new Post(result));
self.newMessage('');
})
.fail(function () {
error('unable to add post');
});
}
Now, along with this, i want to pass dropdown selected id something like this:
data: { id: $("#Locations").val() }
Right now, i have tried using this:
data:{post: ko.toJSON(post), id: $("#Locations").val() }
but in controller, post: ko.toJSon(post) is sending nothing however i am getting id of selected dropdown but not the message property of post parameter.
If i use this line:
data: ko.toJSON(post)
then i can get every property of post parameter but then id is null so, how to deal with this.Plzz Plzz help me out.Debugger is showing nothing useful information.My Post Controller is:
public JsonResult PostPost(Post post, int? id)
{
post.PostedBy = User.Identity.GetUserId<int>();
post.NeighbourhoodId = id;
db.Posts.Add(post);
db.SaveChanges();
var usr = db.Users.FirstOrDefault(x => x.Id == post.PostedBy);
var ret = new
{
Message = post.Message,
PostedBy = post.PostedBy,
NeighbourhoodId = post.NeighbourhoodId
};
return Json( ret,JsonRequestBehavior.AllowGet);
}
on my view page,this is the button on which click event i fired addPost function
<input type="button" data-url="/Wall/SavePost" id="btnShare" value="Share" data-bind="click: addPost">
along with this, dropdown for sending id is something like this:
#Html.DropDownList("Locations", ViewBag.NeighbourhoodId as SelectList, "Select a location")
<script type="text/javascript">
$(document).ready(function () {
$("#btnShare").click(function () {
var locationSelected = $("#Locations").val();
var url = '#Url.Action("PostPost", "Post")';
$.post(url, { id: locationSelected },
function (data) {
});
});
});
</script>
Plzz someone help me out.I am not getting what to do from here.

.click() not working anymore jquery

I have been using this jQuery before I use $.ajax(); and it was working good:
$(document).ready(function(){
var urlSerilize = 'some link';
var appList = $("#applications > li > a");
var appCheck = $('input[type=checkbox][data-level="subchild"]');
var installbtn = $('#submitbtn');
var form = [];
var checked = [];
//var appList = $(".body-list > ul > li");
//var appCheck = $('input[type=checkbox][data-level="subchild"]');
appList.click(function(){
console.log('here!');
if($(this).children().find("input").is(":checked")){
$(this).children().find("input").prop('checked', false);
$(this).children('form').removeClass('checked');
$(this).removeClass("li-checked");
var rmValue = $(this).children('form').attr('id');
form = jQuery.grep(form, function(value) {
return value != rmValue;
});
}else{
$(this).children().find("input").prop('checked',true);
$(this).addClass("li-checked");
$(this).children('form').addClass('checked');
form.push($(this).children('form').attr('id'));
}
console.log(form);
});
installbtn.on('click', function () {
event.preventDefault();
jQuery.each( form, function( i, val ) {
console.log(val);
var request = $.ajax({
url: urlSerilize,
type: 'GET',
data: $('#'+val).serialize(),
success: function( response ) {
console.log( response );
$('#applications').html();
$('#apps_box').html();
}
});
request.done(function(msg){
console.log('Ajax done: ' + 'Yeah it works!!!');
});
request.fail(function(jqXHR, textStatus){
console.log('failed to install this application: ' + textStatus);
});
});
});
});
but after I used this ajax code the .click() jQuery event don't work anymore:
$(document).ready(function() {
/* loading apps */
//console.log('active');
var request = $.ajax({
url: 'some link',
type: 'GET',
dataType: 'html',
data: {id: 0},
})
request.done(function(data) {
console.log("success");
$('#applications').empty().append(data);
})
request.fail(function() {
console.log("error");
})
request.always(function() {
console.log("complete");
});
//end loading apps
var showmore = $('.showapps');
showmore.click(function(){
var parent = $(this).parent('.tv_apps');
var displayC = parent.children('.body-list').css('display');
console.log(displayC);
if (displayC=='none') {
parent.children('.body-list').show('400');
$(this).children().find('img').rotate({animateTo: 180});
}else{
parent.children('.body-list').hide('400');
$(this).children().find('img').rotate({animateTo: 0});
};
});
});
at first place I though it was because of the ajax loads and don't stop, then i was wrong.
I have tried the window.load=function(); DOM function to load the script after Ajax finish loading and also was wrong.
So please if there any idea to fix this problem,
Thanks.
This is the event I want it to be fixed:
appList.click(function(){
console.log('here!');
if($(this).children().find("input").is(":checked")){
$(this).children().find("input").prop('checked', false);
$(this).children('form').removeClass('checked');
$(this).removeClass("li-checked");
var rmValue = $(this).children('form').attr('id');
form = jQuery.grep(form, function(value) {
return value != rmValue;
});
}else{
$(this).children().find("input").prop('checked',true);
$(this).addClass("li-checked");
$(this).children('form').addClass('checked');
form.push($(this).children('form').attr('id'));
}
console.log(form);
});
showmore.click(function(){
should be
$('.showapps').on('click', function(){
OR
$(document).on('click','.showapps', function(){
For dynamically added contents, you need to bind events to it.
For more info: http://learn.jquery.com/events/event-delegation/
Thanks everyone, at last I have found the solution.
It was a question of the DOM, when I use the ready method of jquery it loads an empty ul (without content), so then what I figured out in the first time was correct, all I did is to remove the ready and use a simple function that includes all the .click() events, then call it in request.done();.
This is the solution:
function loadInstaller(){
var urlSerilize = 'some link';
var appList = $("#applications > li");
var appCheck = $('input[type=checkbox][data-level="subchild"]');
var installbtn = $('#submitbtn');
var form = [];
var checked = [];
//...etc
};
$(document).ready(function() {
/* loading apps */
//console.log('active');
var request = $.ajax({
url: 'some link',
type: 'GET',
dataType: 'html',
data: {id: 0},
})
request.done(function(data) {
console.log("success");
$('#applications').empty().append(data);
loadInstaller();
})
//...etc
});
I hope this answer will help someone else :)

Categories