Jquery and ajax call being fired multiple times - javascript

Hi I'm making an ajax call to my php side to add or edit in the database. I return three options depending on what was completed. After debugging with firebug I see that after each submit of with add/edit/delete there is more than one call to the php side (doubles each time) I've done a lot reading of trying to unbind and bind which only allows the event handler to execute once but once I do that the submit buttons don't work until the page is reloaded which isn't what I want. Please help!
Javascript page:
//$('#addAgeGroupForm').trigger("reset");
//$(document).ready(function() {
$(function() {
$("#dialog").dialog({
autoOpen:false,
maxWidth:600,
maxHeight: 500,
width: 500,
height: 350,
async: false,
close: function(){
$('#addAgeGroupForm').trigger("reset");
$.ajax({
type: "GET",
url: "/Ajax/ajax_reset_id.php",
async: false,
success: function(html){
$("#responce_event").html(html);
}
});
}
});
$("#addAgeGroup").on("click", function()
{
$("#dialog").dialog("open");
});
$("#addAgeGroupForm").submit(function(e)
{
e.preventDefault();
var postData = jQuery(this).serialize();
var data = "";
$("#dialog").dialog("close")
$.ajax({
type: "POST",
url: "/Add/AddAgeGroups.php",
dataType: 'json',
async: false,
data: postData,
success: function(result){
data = result;
$('#ageGroups').load('Tables/agegroupTable.php').fadeIn("slow");
if (data==1)
{
alert("Error: Please fill in all fields");
}
else if(data==2)
{
alert("Error: Duplicate Age Group entry for this Meet");
}
else
{
alert(data);
//alert("success");
$('#ageGroups').load('Tables/agegroupTable.php').fadeIn("slow");
}
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
$('[id^="editAgeGroup"]').submit(function(e)
{
e.preventDefault();
var editData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "/Get/GetAgeGroup.php",
async: false,
dataType: 'json',
data: editData,
success: function(data){
var form = document.forms['addAgeGroupForm'];
form.id.value=data.id;
form.agegroup.value=data.agegroup;
form.abbrev.value=data.abbrev;
form.sort.value=data.sort;
}
});
$("#dialog").dialog("open");
});
$("#dialog2").dialog({
autoOpen:false,
maxWidth:600,
maxHeight: 500,
width: 500,
height: 300,
async: false,
close: function(){
$('#deleteAgeGroupForm').trigger("reset");
$.ajax({
type: "GET",
url: "/Ajax/Delete/ajax_delete_ageGroup.php",
async: false,
success: function(html){
$("#responce_delete").html(html);
}
});
}
});
$('[id^="deleteAgeGroup"]').submit(function(e)
{
e.preventDefault();
var deleteData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "/Get/GetAgeGroup.php",
dataType: 'json',
data: deleteData,
success: function(data){
var form = document.forms['deleteAgeGroupForm'];
var id = data.id;
var name = data.agegroup;
form.age_group_id.value = data.id;
$.ajax({
type: "GET",
url: "/Ajax/Delete/ajax_delete_ageGroup.php?id="+id+"&name="+name,
async: false,
success: function(html){
$("#responce_delete").html(html);
}
});
}
});
$("#dialog2").dialog("open");
});
$("#deleteAgeGroupForm").submit(function(e)
{
e.preventDefault();
var postData = jQuery(this).serialize();
var editData = jQuery(this).serialize();
$("#dialog2").dialog("close")
$.ajax({
type: "POST",
url: "/Get/GetAgeGroup.php",
dataType: 'json',
async: false,
data: editData,
success: function(data){
var id = data.id;
//alert(data.id);
//alert(data.schoolname);
$.ajax({
type: "Get",
url: "Delete/DeleteAgeGroup.php?id="+id,
dataType: 'json',
async: false,
data: postData,
success: function(data){
//alert(data);
//alert("success");
$('#ageGroups').load('Tables/agegroupTable.php').fadeIn("slow");
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
}});
});
/******************/
})
function updateTable()
{
$('#ageGroups').load('Tables/agegroupTable.php').fadeIn("slow");
}
PHP side:
session_start();
if($_SESSION["logged_in"] == 0)
header("Location: ****");
else if($_SESSION["type"] == "general")
header("Location: ****");
else
{
$agegroup = addslashes($_POST['agegroup']);
$abbrev = addslashes($_POST['abbrev']);
$sort = addslashes($_POST['sort']);
$id = $_POST['id'];
$managerID = $_SESSION["manager_id"];
$meetID = $_SESSION["meet_id"];
$db = mysqli_connect("****", "****", "****","****");
if(!$db){
exit("Error in database connection");
}
else
{
$exists = mysqli_query($db,"SELECT * FROM `AgeGroup` WHERE `AgeGroupLong` = '$agegroup' AND `AgeGroupShort` = '$abbrev' AND `ManagerID` = $managerID AND `MeetID` = $meetID ");
$row = mysqli_fetch_array($exists);
if($_POST['agegroup']=="" || $_POST['abbrev']=="" || $meetID=="")
{
//exit(json_encode(1));
echo json_encode(1);
}
else if($id == "" && $row > 0)
{
echo json_encode(2);
}
else
{
$result = mysqli_query($db, "SELECT * FROM `AgeGroup` WHERE `AgeGroupLong`='$agegroup' AND `AgeGroupShort` = '$abbrev'");
//$row = mysqli_fetch_array($result);
if($id == "")
{
mysqli_query($db, "INSERT INTO `AgeGroup` (`AgeGroupLong`,`AgeGroupShort`,`Sort`, `ManagerID`, `MeetID`) VALUES ('$agegroup', '$abbrev', $sort, $managerID, $meetID)");
}
else
{
$AgeGroup_id = $row['AgeGroupID'];
mysqli_query($db, "UPDATE `AgeGroup` SET `AgeGroupLong`='$agegroup',`AgeGroupShort` = '$abbrev', `Sort`=$sort WHERE `AgeGroupID`=$id");
}
$ageGroup = array
(
'agegroup' => stripslashes($agegroup),
'abbrev' => stripslashes($abbrev),
'sort' => stripslashes($sort)
);
echo json_encode($ageGroup);
}
}
}
mysql_close($db);

declare global variable and make ajax request one time:-
var is_request_sent = false;
function like_post(wall_post,obj)
{
if(is_request_sent == false)
{
$.ajax({
type: "POST",
dataType: "json",
url: base_url+"ajax_timeline/like_post",
data: "action=like_post&wall_post_id="+wall_post,
success: function(result){//alert(result);alert('here');
is_request_sent = false;
},
error: function(a,b,c)
{
is_request_sent = false;
//fbalert('Error', 'Error occured. Please try again.');
},
beforeSend: function(jqXHR, plain_jqXHR){
is_request_sent = jqXHR;
// Handle the beforeSend event
},
complete: function(){
is_request_sent = false;
// Handle the complete event
}
});
}
}
i hope this will help you

Related

The Function App/GetSPANList returns 401 error on server. C# asp.net

The below method returns 401 error on server. As I don't see any errors in this. Please suggest why its coming as 401 error
function loadSPANByMZ() {
try {
showLoading();
var OperationType = "";
if (R4GStateSelected != "Select") {
if ($(mzoneid).val() != "Select") {
if ($(activitytypeid).val() != "Select") {
//call CurrentGroupName UMS variable
var UserType = CurrentGroupName;
var SpanType = $(spantypeid + ' option:selected').val().toUpperCase();
var MZone = $(mzoneid + ' option:selected').val();
OperationType = $(activitytypeid + ' option:selected').val();
var Values = { "USERTYPE": UserType, "SPANTYPE": SpanType, "MZONE": MZone, "OPERATIONTYPE": OperationType.toUpperCase() };
//$(gridSpanlisttable).empty();
$.ajax({
type: "POST",
url: AppConfig.PrefixURL + "App/GetSPANList",
data: JSON.stringify(Values),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (response) {
displaySpanList(response, SpanType, MZone, OperationType);
//hideLoading();
},
error: function (response) {
hideLoading();
$(dataContent).hide();
},
complete : function(response)
{
hideLoading();
}
});
}
}
}
//},
}
catch (e) {
hideLoading();
$(dataContent).show();
}
}

alert is not working on error message

// Alert is not working on error message , I want to insert only few 4 issue after that it should not work.
success: function(msg, String, jqXHR) {
window.location = 'home.html';
$("#result").html(msg, String, jqXHR)
alert("Data Uploaded: ");
if (msg.success == 'Error') {
alert("Please close the previous issue");
window.location = 'home.html';
}
// here (msg.success=='Error') is not working i want to display this message - "Please close the previous issue" on this .
Hope this works for you.
$(document).ready(function(){
$('#your_form').submit(function(event) {
event.preventDefault();
dataString = $("#your_form").serialize();
$.ajax({
type: "post",
url: "post.php",
dataType:"json",
data: dataString,
success: function (response) {
if(response.status === "success") {
// do something with response.message or whatever other data on success
alert("Data Uploaded: ");
window.location='home.html';
} else if(response.status === "error") {
alert("Please close the previous issue");
window.location='home.html';
}
}
})
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Redirect somewhere else upon JSON success?

My Code:
<script>
$('#form').submit(function() {
$.ajax({
type: 'POST',
url: $(this).attr('action'),
dataType: 'json',
success: function(json) {
window.location.href = "http://www.example.com";
}
});
return false;
});
</script>
The FORM:
<form id="form" class="center" action="http://localhost/products/index.php?route=checkout/cart/add" method="post">
<input type="text" name="cname">
<input type="hidden" name="product_id" value="51">
<input type="submit">
</form>
When the form presses submit it goes to the action page which is just a JSON success message, what I want to do is redirect to a different page other than the action page, but my code does not seem to be working?
What exactly is wrong with my code, can someone help me fix it?
I would be so grateful if you could help me out, many thanks!
You aren't posting any data which makes a POST fairly useless .
Also you have no error handler either
Try:
$(function(){
$('#form').submit(function() {
var $form = $(this);
$.ajax({
type: 'POST',
url: $form.attr('action'),
// data to send
data: $form.serialize(),
dataType: 'json',
success: function(json) {
window.location.href = "http://www.example.com";
},
error: function(){
// do something when request fails - See $.ajax docs
}
})
return false;
});
});
You can used this code for error handling! You also check this question on stackOverflow for redirecting to another page using jQuery/JavaScript:
click here
$('#form').submit(function() {
var $form = $(this);
$.ajax({
type: 'POST',
url: $form.attr('action'),
// data to send
data: $form.serialize(),
dataType: 'json',
success: function(json) {
window.location.href = "http://www.example.com";
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
alert(msg);
},
});
});
You need to have separate error and success handlerS like below.
In success method you can redirect to other pages/sites (window.location.href = "http://www.EXAMPLE.com";)
var ajaxUpdateRequest = {
url: '/dotnethelpers/UpdateUsers',
dataType: 'json',
success: updateSuccessfully, //Separate method for handling success
error: showError //Separate method for handling error
};

values not being accessed inside ajax call

I have the following code. The thing is that when I alert the values of id and status inside click functions it works fine but when I try to do so outside that then the value of id is returned undefined initially but alert doesn't work after that. Please help
var status = 1;
var id;
$("body").on('click','#first' , function() {
id = 1;
$.ajax({
type: "POST",
url: "url",
data: {id: id, status: status},
dataType: "html",
success: function(data) {
//alert(data);
if($.trim(data) == "A") {
alert('A');
} else if($.trim(data) == "B") {
alert('B');
}
}, error: function() {
alert("ERROR!");
}
});
});
$("body").on('click','#second' , function() {
id = 2;
status = 0;
$.ajax({
type: "POST",
url: "url",
data: {id: id, status: status},
dataType: "html",
success: function(data) {
//alert(data);
if($.trim(data) == "A") {
alert('A');
} else if($.trim(data) == "B") {
alert('B');
}
}, error: function() {
alert("ERROR!");
}
});
});
Try this
var status = 1;
var id;
$("body").on('click','#first' , function() {
id = 1;
SomethingName();
});
$("body").on('click','#second' , function() {
id = 2;
status = 0;
SomethingName();
});
function SomethingName(){
$.ajax({
type: "POST",
url: "url",
data: {id: id, status: status},
dataType: "html",
success: function(data) {
//alert(data);
if($.trim(data) == "A") {
alert('A');
} else if($.trim(data) == "B") {
alert('B');
}
}, error: function() {
alert("ERROR!");
}
});
}
Or Try this
var status = 1;
var id;
$("body").on('click','#first' , function() {
id = 1;
SomethingName(id,status);
});
$("body").on('click','#second' , function() {
id = 2;
status = 0;
SomethingName(id,status);
});
function SomethingName(_id,_status){
$.ajax({
type: "POST",
url: "url",
data: {id: _id, status: _status},
dataType: "html",
success: function(data) {
//alert(data);
if($.trim(data) == "A") {
alert('A');
} else if($.trim(data) == "B") {
alert('B');
}
}, error: function() {
alert("ERROR!");
}
});
}

jQuery trying to handle ajax failure and sucess not working

I had a working jQuery ajax call but i wanted to check the result of the request so i added
success: function(data) {
if(data.status == 'success'){
alert("Thank you for subscribing!");
}else if(data.status == 'error'){
alert("Error on query!");
}
}
but this is not working and made my whole function stop working even.so here is the whole function,can some one tell me what am doing wrong`
function addGoal() {
var description = $('.description').val();
var measure = $('.measure').val();
if( description.trim() && measure.trim() ){
if(window.confirm("Are you sure? You can't edit or remove goal(s) you have added here.")==true) {
$.ajax({
url: '${g.createLink( controller:'review', action:'saveGoal', params:[id: params.id] )}',
data: {
"description": description,
"measure": measure
},
success: function(data) {
if(data.status == 'success'){
alert("Thank you for subscribing!");
}else if(data.status == 'error'){
alert("Error on query!");
}
}
type: 'POST'
});
}
}else {
showErrorMessage("Description and Measure fields cant be empty");
}
}`
when i remove the success it works as i expected it to.And if it matters am using grails
There is a syntax error which is a missing comma
function addGoal() {
var description = $('.description').val();
var measure = $('.measure').val();
if( description.trim() && measure.trim() ){
if(window.confirm("Are you sure? You can't edit or remove goal(s) you have added here.")==true) {
$.ajax({
url: '${g.createLink( controller:'review', dataType: "json", action:'saveGoal', params:[id: params.id] )}',
data: {
"description": description,
"measure": measure
},
success: function(data) {
if(data.status == 'success'){
alert("Thank you for subscribing!");
}else if(data.status == 'error'){
alert("Error on query!");
}
},
type: 'POST'
});
}
}else {
showErrorMessage("Description and Measure fields cant be empty");
}
}`
This will fix the issue

Categories

Resources