values not being accessed inside ajax call - javascript

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!");
}
});
}

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();
}
}

How do I show a confirmation box before deleting a record

I need to show a confirm box before performing this ajax request.
$(document).on("click", ".deletecustomer", function() {
var id = $(this).attr("id");
$.ajax({
method: "post",
url: "deletecustomer.php",
data: {
id: id
},
success: function(data) {
console.log(data);
if (data == "success") {
window.location.href = "customer.php";
}
}
});
});
$(document).on("click", ".deletecustomer", function() {
if (confirm('Are you sure?')) {
var id = $(this).attr("id");
$.ajax({
method: "post",
url: "deletecustomer.php",
data: {
id: id
},
success: function(data) {
console.log(data);
if (data == "success") {
window.location.href = "customer.php";
}
}
});
}
});

Fill Variable with Web Service Results

I have a javascript function that is executed onClick via jquery. Within this function I am calling a Web Service "getTestConnection" which returns a True or False and I have confirmed it is working but keeps returning variable undefined.
$("#btnNext2").click(function() {
var postData = {}; {
postData['user'] = user;
postData['password'] = password;
postData['serviceurl'] = serviceurl;
postData['datasource'] = datasource;
};
//Converts object to string and formats to JSON
var json = JSON.stringify(postData);
//connTest keeps getting returned as 'Undefined'
var connTest = getTestConnection(json);
});
< script type = "text/javascript" >
function getDocType(json, rowcount) {
$.ajax({
type: "POST",
url: "http://localhost:64580/Web_Services/WebServiceLibrary.asmx/GetDocTypes",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
//*****************************************************************************
//This is being called immediately after getTestConnection is executed
//******************************************************************************
for (i = 0; i < data.d.length; i++) {
$('#SelectDocType' + rowcount + '')
.append($("<option></option>")
.attr("value", data.d[i].docTypeID)
.text(data.d[i].docTypeName));
}
var firstDocTypeID = data.d[0].docTypeID;
var jsonUnstringify = JSON.parse(json);
var postDataNew = {}; {
postDataNew['user'] = jsonUnstringify.user;
postDataNew['password'] = jsonUnstringify.password;
postDataNew['serviceurl'] = jsonUnstringify.serviceurl;
postDataNew['datasource'] = jsonUnstringify.datasource;
postDataNew['docTypeID'] = firstDocTypeID;
};
var jsonnew = JSON.stringify(postDataNew);
getKeywords(jsonnew, rowcount);
},
error: function(data) {
alert("***********Error***********" + data.responseText);
},
failure: function(data) {
alert("***********Failure***********" + data.responseText);
}
});
//Test Connection Web Service
function getTestConnection(json) {
$.ajax({
type: "POST",
url: "http://localhost:64580/Web_Services/WebServiceLibrary.asmx/TestConnection",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
if (data.d == 'True') {
return true;
} else {
return false;
}
},
error: function(data) {
alert("***********Error***********" + data.responseText);
},
failure: function(data) {
alert("***********Failure***********" + data.responseText);
}
});
}
< /script>
You have multiples errors:
You have a <script type = "text/javascript"> tag inside another <script> tag
You define a new function inside another function:
function getDocType(json, rowcount) {
$.ajax({
.....
});
function getTestConnection(json) {
....
}
}
which should be
function getDocType(json, rowcount) {
$.ajax({
.....
});
}
function getTestConnection(json) {
....
}
You forgot to get returned data from the AJAX call in your getTestConnection function :
$.ajax({
type: "POST",
url: "http://localhost...",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
if (data.d == 'True') {
return true;
} else {
return false;
}
},
error: function(data) {
....
}
});

Jquery and ajax call being fired multiple times

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

Passing parameters from function to its callback

Here's my code:
First the execution of the program comes here:
refreshTree(function() {
$.ajax({
type: "POST",
url: "/ControllerName/MethodName1",
success: function (data) {
refresh();
}
});
});
Here's the definition of refreshTree():
function refreshTree(callback) {
var isOk = true;
$.ajax({
type: "GET",
url: "/ControllerName/MethodName2",
success: function(data) {
if (data == 'True') {
isOk = false;
}
callback();
}
});
}
And here's the refresh() method:
function refresh() {
if (isOk) {
//do something
}
}
The problem is, I don't know how to get the isOk variable in refresh(). Is there some way to send the variable to refresh(), without it being a global variable?
You capture it in a closure here:
refreshTree(function(isOk) {
$.ajax({
type: "POST",
url: "/ControllerName/MethodName1",
success: function (data) {
refresh(isOk);
}
});
});
And pass it in here:
function refreshTree(callback) {
var isOk = true;
$.ajax({
type: "GET",
url: "/ControllerName/MethodName2",
success: function(data) {
if (data == 'True') {
isOk = false;
}
callback(isOk);
}
});
}
and here:
function refresh(isOk) {
if (isOk) {
//do something
}
}
Simply Pass it as parameter:
refreshTree(function(status) {
$.ajax({
type: "POST",
url: "/ControllerName/MethodName1",
success: function (data) {
refresh(status);
}
});
});
refreshTree() function:
function refreshTree(callback) {
var isOk = true;
$.ajax({
type: "GET",
url: "/ControllerName/MethodName2",
success: function(data) {
var isOk=true;
if (data == 'True') {
isOk = false;
}
callback(isOk);
}
});
}
Refresh() method:
function refresh(status) {
if (status) {
//do something
}
}

Categories

Resources