Ajax post in function in external js - javascript

I've made a function with an ajax post. This function is in an external js file on my server. (functions.js).
From another page I call the function like this:
$('table.table_sort td').click(function(e)
{
var url = "https://<?=$_conf['siteurl']?>/files/process.ajax.php";
sortTable(url, e);
});
The function in the functions.js looks like this:
function sortTable(url, e)
{
if( !$(e.target).is(".last, .last input")){
$('input[name="sort"]').parent('td').removeClass('sort_active');
$('input[name="sort"]').parents('td').children('div').removeClass().addClass('sort_none');
if($(this).children('input[type="radio"]:first').is(':checked'))
{
$(this).children('input[type="radio"]:last').prop('checked', true);
$(this).children('div').removeClass().addClass('sort_asc');
$('input[name="sort"]:checked').parent('td').addClass('sort_active');
}
else
{
$(this).children('input[type="radio"]:first').prop('checked', true);
$(this).children('div').removeClass().addClass('sort_desc');
$('input[name="sort"]:checked').parent('td').addClass('sort_active');
}
$.ajax({
type: "POST",
url: url,
async: false,
data: $('#myform').serialize(),
complete: function(data)
{
$('#results').html(data.responseText);
}
});
}
}
Unfortunately nothing happened. When I do this it work:
$('table.table_sort td').click(function(e)
{
var url = "https://<?=$_conf['siteurl']?>/files/process.ajax.php";
if( !$(e.target).is(".last, .last input")){
$('input[name="sort"]').parent('td').removeClass('sort_active');
$('input[name="sort"]').parents('td').children('div').removeClass().addClass('sort_none');
if($(this).children('input[type="radio"]:first').is(':checked'))
{
$(this).children('input[type="radio"]:last').prop('checked', true);
$(this).children('div').removeClass().addClass('sort_asc');
$('input[name="sort"]:checked').parent('td').addClass('sort_active');
}
else
{
$(this).children('input[type="radio"]:first').prop('checked', true);
$(this).children('div').removeClass().addClass('sort_desc');
$('input[name="sort"]:checked').parent('td').addClass('sort_active');
}
$.ajax({
type: "POST",
url: url,
async: false,
data: $('#myform').serialize(),
complete: function(data)
{
$('#results').html(data.responseText);
}
});
}
});
Any ideas?

Your problem is the use of this inside the function. You need to pass that into the function as this inside the function does not return the clicked element...
$('table.table_sort td').click(function(e) {
var url = "https://<?=$_conf['siteurl']?>/files/process.ajax.php";
sortTable(this, url, e);
});
function sortTable(el, url, e)
{
var $el = $(el);
if( !$(e.target).is(".last, .last input")){
$('input[name="sort"]').parent('td').removeClass('sort_active');
$('input[name="sort"]').parents('td').children('div').removeClass().addClass('sort_none');
if($el.children('input[type="radio"]:first').is(':checked'))
{
$el.children('input[type="radio"]:last').prop('checked', true);
$el.children('div').removeClass().addClass('sort_asc');
$('input[name="sort"]:checked').parent('td').addClass('sort_active');
}
else
{
$el.children('input[type="radio"]:first').prop('checked', true);
$el.children('div').removeClass().addClass('sort_desc');
$('input[name="sort"]:checked').parent('td').addClass('sort_active');
}
$.ajax({
type: "POST",
url: url,
async: false,
data: $('#myform').serialize(),
complete: function(data)
{
$('#results').html(data.responseText);
}
});
}
}
You should now be able to put the function back in an external file, as you originally wanted :)

Related

Add CSS element after kendogrid refresh

I have an ajax call that sends to MyAction in MyController.. it returns me with result of success and an Id for an element to which I want to attach some CSS.
the Id is returned, and the css is added but the refreshGridData happens afterwards removing the css I just added to the element.
Is there a way to wait for refreshGridData to finish and then add the css?
I did try the done for ajax.. it did not work.
$.ajax({
url: "#Url.Action("MyAction", "MyController")",
type: "POST",
data: postData,
success: function (result) {
if (result.Success) {
alert("success");
refreshGridData();
}
},
error: function (result) {
alert("Error!");
}
AddMyCSSToThis(result.Id);
// done: AddMyCSSToThis(result.Id);
});
function refreshGridData() {
var ajaxContainer = $(".grid-wrap");
kendo.ui.progress(ajaxContainer, true);
refreshGrid();
kendo.ui.progress(ajaxContainer, false);
}
Why don't you pass in the Id you want to add the change into your refreshGridData() function like:
$.ajax({
url: "#Url.Action("MyAction", "MyController")",
type: "POST",
data: postData,
success: function (result) {
if (result.Success) {
alert("success");
var savedId = result.Id;
refreshGridData(savedId);
}
},
error: function (result) {
alert("Error!");
}
AddMyCSSToThis(result.Id);
// done: AddMyCSSToThis(result.Id);
});
function refreshGridData(savedId) {
var ajaxContainer = $(".grid-wrap");
kendo.ui.progress(ajaxContainer, true);
refreshGrid(savedId); // I'm assuming this function is what adds the css
kendo.ui.progress(ajaxContainer, false);
}
You could create a global variable and use it in the grid dataBound event to add the CSS.
_addCssToResultId = null;
$.ajax({
url: "#Url.Action("MyAction", "MyController")",
type: "POST",
data: postData,
success: function (result) {
if (result.Success) {
alert("success");
_addCssToResultId = result.Id;
refreshGridData();
}
},
error: function (result) {
alert("Error!");
}
});
// add a dataBound handler to your grid
$("#grid").kendoGrid({
dataBound: function(e) {
if(_addCssToResultId) {
AddMyCSSToThis(_addCssToResultId);
_addCssToResultId = null;
}
}
});

Close active ajax request (setTimeout)

I'm trying to stop an active ajax request when I click on checkbox. i active an ajax which calls every second to a url, but when i uncheck the checkbox, I was trying to close the ajax request. I tried with listener.abort(); and it doesnt work and also i added xhr.abort() and nothing happend.
Any suggestion?
function listener() {
$.get('http://localhost:3000/get-value', function (dataf) {
if (dataf.result != "") {
$.ajax({
url: "http://localhost:8000/login",
data: { pId: dataf.result },
type: "POST",
success: function (result) {
if (result.name != "") {
$.get('http://localhost:3000/close-conn');
window.location.href = result.url;
}
}
});
}
setTimeout(listener, 1000);
});
}
function GetCheckStatus() {
var flag = chkAuto.GetValue();
if (flag) {
$.ajax({
url: "http://localhost:3000/open-conn",
type: "GET",
});
listener();
} else {
$.ajax({
url: "http://localhost:3000/close-conn",
type: "GET",
});
// Doesnt work
listener.abort();
}
}
You're calling the .abort() method on the function, not the actual request object. Try something like this instead.
Define variables for the $.get request and the setTimeout, then abort/clear them as needed.
var xhr, timeout;
function listener() {
xhr = $.get('http://localhost:3000/get-value', function (dataf) {
if (dataf.result != "") {
$.ajax({
url: "http://localhost:8000/login",
data: { pId: dataf.result },
type: "POST",
success: function (result) {
if (result.name != "") {
$.get('http://localhost:3000/close-conn');
window.location.href = result.url;
}
}
});
}
timeout = setTimeout(listener, 1000);
});
}
function GetCheckStatus() {
var flag = chkAuto.GetValue();
if (flag) {
$.ajax({
url: "http://localhost:3000/open-conn",
type: "GET",
});
listener();
} else {
$.ajax({
url: "http://localhost:3000/close-conn",
type: "GET",
});
//Cancel the current request and prevent the next one from being triggered
xhr.abort();
clearTimeout(timeout);
}
}

Call function after ajax load()

I initiate a function after an ajax load(), but the function I intimate calls upon an additional function, which isn't working. How do I initiate ajaxstuff() after load()?
function ajaxstuff(data) {
$.ajax({
type: "POST",
url: "do-it.php",
data: {data},
success: function() {
console.log('I got this far'); // this doesn't work / isn't called
}
});
}
function doit() {
$('form').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
console.log('I got this far'); // this works
ajaxstuff(formData);
}
}
$('.popup-loader').click(function() {
$(this).append('<div class="popup"></div>');
$('.popup').load('popup.php', function() {
doit(); // this works
}
});
Check for errors in your console, also, in your AJAX add an async option. set it to FALSE ("Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called"):
function ajaxstuff(data) {
$.ajax({
async: false,
type: "POST",
url: "do-it.php",
data: data,
success: function(result) {
console.log(result); //check in your console for errors
}
});
}
Syntax error in ajaxstuff function. data: {data}, , probably should be data: data,
Also when you're passing a FormData object to $.ajax, you have to specify processData: false and contentType: false
$.ajax({
type: "POST",
url: "do-it.php",
data: data,
processData: false,
contentType: false,
success: function() {
console.log('I got this far');
}
});

Ajax doesn't execute success function

My code looks like this. The problem is, PHP side does it job and returns right value. But ajax doesn't execute things inside success: function. What am I missing?
AnswerDiv.on("click", ".NotSelectedAnswer", function() {
var NotSelectedAnswerBtn = $(".NotSelectedAnswer"),
SelectedAnswerBtn = $(".SelectedAnswer"),
AnswerDiv = $("div.Answer"),
querystring="fromID="+SelectedAnswerBtn.data("id")+"&toID="+$(this).data("id")+"&op=SelectAsAnswer";
$.ajax({
url: 'processor.php',
type: "POST",
dataType: "json",
data: querystring,
success: function(data) {
if(data.status)
{
SelectedAnswerBtn.removeClass("SelectedAnswer").addClass("NotSelectedAnswer").button("enable");
$(this).removeClass(" NotSelectedAnswer").addClass("SelectedAnswer").button("disable");
$("div.Answer[data-id=" + SelectedAnswerBtn.data("id") + "]").toggleClass("SelectedDiv");
$("div.Answer[data-id=" + $(this).data("id") + "]").toggleClass("SelectedDiv");
}
}
});
return false;
});
Try to cache $(this) before ajax call
AnswerDiv.on("click", ".NotSelectedAnswer", function() {
var NotSelectedAnswerBtn = $(".NotSelectedAnswer"),
SelectedAnswerBtn = $(".SelectedAnswer"),
AnswerDiv = $("div.Answer"),
thisElem=$(this),
querystring="fromID="+SelectedAnswerBtn.data("id")+"&toID="+$(this).data("id")+"&op=SelectAsAnswer";
$.ajax({
url: 'processor.php',
type: "POST",
dataType: "json",
data: querystring,
success: function(data) {
if(data.status)
{
SelectedAnswerBtn.removeClass("SelectedAnswer").addClass("NotSelectedAnswer").button("enable");
thisElem.removeClass(" NotSelectedAnswer").addClass("SelectedAnswer").button("disable");
$("div.Answer[data-id=" + SelectedAnswerBtn.data("id") + "]").toggleClass("SelectedDiv");
$("div.Answer[data-id=" +thisElem.data("id")+ "]").toggleClass("SelectedDiv");
return false;
}
}
});
});

ajax request not working on IE

function VReload()
{
$.ajax({
type: "GET",
url: "/foo/",
success: function (data) {
$("#myid").html(data);
}
});
}
$(document).ready(function() {
setInterval('VReload()', 1000)
});
This piece of code is working fine on Mozilla and chrome but not on IE. Ajax call is not firing on IE. What could be the reason.
Switch off caching by doing this:
$.ajax({
type: "GET",
cache: false,
url: "/foo/",
success: function (data) {
$("#myid").html(data);
}
});
set cache false
$.ajaxSetup({ cache: false });
or
$.ajax({
cache: false,
//other options
});
Try this:
function VReload()
{
var timestamp = new Date();
$.ajax({
type: "GET",
url: "/foo/" + "&timestamp=" + timestamp.getTime(),
success: function (data) {
$("#myid").html(data);
}
});
}
$(document).ready(function() {
setInterval('VReload()', 1000)
});
use jQuery's $.get() function
$.get('/foo/', {}, function(data){
// whatever
});

Categories