How to set jQuery AJAX outside .each on my script below?
$('#btnUpdate').click(function()
{
$('#result').html('');
$('.moduleIDInput').each(function()
{
var uid = $(this).attr('id');
var moduleID = $(this).val();
var chk = new Array();
$('#result').append('<h3>' +$(this).val() + '</h3>');
$('input[data-uid=' + uid + ']:checked').each(function()
{
chk.push($(this).val());
$('#result').append('<div>'+ $(this).val() + '</div>');
});
});
$.ajax(
{
url: "updateGroupAccess.php",
type: "POST",
data:
{
moduleID: moduleID,
chk: chk
},
dataType: "JSON",
success: function (jsonStr)
{
$("#btnUpdate").attr({disabled: true, value: "Update"}).addClass('btn_inact').removeClass('btn_act');;
}
});
});
If I put the AJAX function inside .each function it will submit more than 1.
But I need to put it outside, and found problem moduleID and chk not found.
Scope problem. Define uid and moduleID outside the click.
var uid="";
var moduleID="";
$('#btnUpdate').click(function()
{
$('#result').html('');
$('.moduleIDInput').each(function()
{
uid = $(this).attr('id'); // Assign value for uid
moduleID = $(this).val();
Define the variables in the global scope:
make a function called sendAjax and call it on button click.
In the mean time all your data will be stored in the data global variable (object).
var data={};
$('#btnUpdate').click(function()
{
$('#result').html('');
$('.moduleIDInput').each(function()
{
var uid = $(this).attr('id');
data.moduleID = $(this).val();
$('#result').append('<h3>' +$(this).val() + '</h3>');
$('input[data-uid=' + uid + ']:checked').each(function()
{
data.chk.push($(this).val());
$('#result').append('<div>'+ $(this).val() + '</div>');
});
});
sendAjax();
});
function sendAjax()
{
$.ajax(
{
url: "updateGroupAccess.php",
type: "POST",
data:
{
moduleID: data.moduleID,
chk: data.chk
},
dataType: "JSON",
success: function (jsonStr)
{
$("#btnUpdate").attr({disabled: true, value: "Update"}).addClass('btn_inact').removeClass('btn_act');;
}
});
}
Related
I got an issue here. I found out that the global variable got changed every time it got into ajax.
$(document).on("keyup input", ".product-id", function () {
var id_prod = this.id.replace('prod_id_', '');
console.log('id_prod (outside ajax): ', id_prod);
var inputVal = $(this).val();
var resultDropdown = $('#result2').css({
"display": "block"
});
if (inputVal.length) {
$.ajax({
type: 'POST',
data: { term: inputVal },
url: 'backend-search-inv.php',
success: function (data) {
resultDropdown.html(data);
$(document).on("click", "#result2 p", function () {
var inv_id = $(this).text();
//console.log('inv_id: ',inv_id);
$.ajax({
type: 'POST',
data: {
term: inv_id
},
url: 'autocomplete_inv.php',
success: function (response) {
var inv_info = jQuery.parseJSON(response);
console.log('id_prod (in ajax): ', id_prod);
},
error: function () {
console.log('Unable to access database.');
}
});
}); //end of result being clicked
}
});
}
else {
resultDropdown.empty();
}
});
I don't get it why the variable id_prod gets incremented everytime when it goes into ajax. Here is the screenshot of the console.log.
Referring to the screenshot, everytime I want to enter something to the id_prod = 2, the ajax always ended up updating the id_prod = 1, and then id_prod = 2 again automatically, and result in duplication of my data.
Can someone help me on this?
So basically I just declare the id_prod as a global variable and assigned 0 as it's default value. Then, for id_prod is basically assigned to new value once it's in the keyup input event.
Thanks to Mohamed Yousef for his answer in my own question's comment section!
//DECLARE id_prod as a global variable...
var id_prod = 0;
$(document).on("keyup input", ".product-id", function(){
id_prod = this.id.replace('prod_id_', '');
var inputVal = $(this).val();
var resultDropdown = $('#result2').css({"display":"block"});
if(inputVal.length){
$.ajax({
type: 'POST',
data: {term:inputVal},
url: 'backend-search-inv.php',
success: function(data){
resultDropdown.html(data);
}
});
}
else{
resultDropdown.empty();
}
});
// WHEN RESULT BEING CLICKED...
$(document).on("click", "#result2 p", function(){
var inv_id = $(this).text();
$.ajax({
type: 'POST',
data: {term:inv_id},
url: 'autocomplete_inv.php',
success: function (response) {
var inv_info = jQuery.parseJSON(response);
console.log('id_prod (in ajax): ',id_prod);
$('#prod_id_'+id_prod).val(inv_info[0]);
$('#prod_qty_'+id_prod).val(1);
$('#prod_disct_'+id_prod).val(0);
$('#prod_type_'+id_prod).val(inv_info[1]);
$('#prod_colour_'+id_prod).val(inv_info[2]);
$('#prod_price_'+id_prod).val(inv_info[3]);
$('#result2').empty();
sumPrice();
},
error: function(){
console.log('Unable to access database.');
}
});});
How To Set This ajax Run Every 5 Second
$(document).ready(function() {
var SrNo = document.getElementById('EntryType').value;
var EntryType = document.getElementById('EntryType').value;
$.ajax({
type: "POST",
url: "get_max_srno.php?CID=" + SrNo + "&EntryType=" + EntryType,
data: {
SrNo: $("#EntryType option:selected").val()
},
data: {
EntryType: $("#EntryType option:selected").val()
}
})
.done(function(msg1) {
var msg = msg1;
document.getElementById('SrNo').value = msg1;
});
});
function autoCall(){
var feedback = $.ajax({
type: "POST",
url: "autocall.php",
async: false
}).success(function(){
setTimeout(function(){autoCall();}, 5000);
}).responseText;
$('div').html(feedback);
}
if you want it to run only after successfully completing the call,
you can set it up in your .ajax().success() callback:
Or use .ajax().complete() if you want it to run regardless of result:
here is the demo explaining success() and complete().
here complete() will fire every 5 seconds as success is returning 404.
Hope this will be interesting everyone who looking this kind of problem.
Working Demo
You can use setInterval function.
For reference
https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval
var reloadContent = function () {
var SrNo = document.getElementById('EntryType').value;
var EntryType = document.getElementById('EntryType').value;
$.ajax({
type: "POST",
url: "get_max_srno.php?CID=" + SrNo + "&EntryType=" + EntryType,
data: {
SrNo: $("#EntryType option:selected").val()
},
data: {
EntryType: $("#EntryType option:selected").val()
}
})
.done(function(msg1) {
var msg = msg1;
document.getElementById('SrNo').value = msg1;
});
}
$(document).ready(function() {
var reloadContentInterval = setInterval(reloadContent, 5000);
// You can cancel it later if you want
// clearInterval( reloadContentInterval );
});
I'm having troubles using a global variable in my ajax response.
LastDate is a variable defined in the page I loaded into my second page. (function load_table)
I am able to acces the variable before the ajax call, but I can't seem to acces it in my ajax succes. because it gives undefined. <==== in code
my code:
var dia_date = {};
$(window).load(function()
{
DP("eerste keer")
load_table();
} );
function load_table()
{
DP('load_table');
$.ajax({
type: "POST",
url: "/diagnose_hoofdpagina/table_diagnose/" + DosierID,
success: function (data) {
$("#diagnoses_zelf").html('');
$("#diagnoses_zelf").append(data).trigger('create');
//initialize_table();
update_table();
},
error: function(){
alert('error');
}
});
return false;
}
function update_table()
{
if(LastDate > Datum)
{
alert("LasteDate" + LasteDate);
}
else
{
alert("Datum" + Datum);
}
alert('gast .... ' + LastDate); // <========== this is promted on the screen so there is no problem
$.ajax({
type: "POST",
url: "/refresh_diagnose/" + DosierID,
dataType: "json",
data : JSON.stringify(dia_date),
success: function (data) {
var DataDate = new Date(data.Year, data.Month, data.Day, data.Hour, data.Minute, data.Second);
alert('lastdate :'+ LastDate + 'date.date :' + DataDate);
//<============ BUT HERE HE GIVES LastDate AS UNDEFINED
},
error: function(data){
alert(data);
}
});
return false;
}
I can't see what I'm doing wrong. Can annyone help me plaese ? Thanks in advance.
You can try making a function.
var lastDate = #;
function getLastDate(){return lastDate;}
ajax.blablabla.success :{getLastDate();}
For some reason, my script isn't writing out the text after I remove the textbox element. Am I incorrectly using the .html or is something else wrong?
$('.time').click(function () {
var valueOnClick = $(this).html();
$(this).empty();
$(this).append("<input type='text' class='input timebox' />");
$('.timebox').val(valueOnClick);
$('.timebox').focus();
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
$(this).remove('.timebox');
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88");
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88");
}
});
});
OK, thanks to the comments, I figured out I was referencing the wrong thing. The solution for me was to change the blur function as follows:
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
}
$(this).parent().html("8");
$(this).remove('.timebox');
});
$(this) in your success handler is refering to msg, not $('.timebox') (or whatever element that you want to append the html to)
$(this) = '.timebox' element but you have removed it already,
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88"); // This = msg
}
and
else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88"); // this = '.timebox' element but you have removed it already,
}
The value of this changes if you enter a function. So when u use this in the blur function handler, it actually points to '.timebox'
$('.time').click(function () {
var valueOnClick = $(this).html();
var $time=$(this);//If you want to access .time inside the function for blur
//Use $time instead of$(this)
$(this).empty();
$(this).append("<input type='text' class='input timebox' />");
$('.timebox').val(valueOnClick);
$('.timebox').focus();
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
$(this).remove(); //Since $(this) now refers to .timebox
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88");
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88");
}
});
});
Im having an issue with jquery autocomplete plugin. the textbox im using wont populate the results of autocomplete until i enter a value that is in the first entry of my data. After it populates that, then the autocomplete works how its supposed to.
$(document).ready(function () {
});
function textChange() {
var callback = function (request, response) {
var searchText = request.item;
var searchField = $(".ddlist > option:selected").attr("value");
$.ajax({
type: "GET",
dataType: "text",
url: "SearchCallback.aspx?searchText=" + searchText + "&searchField=" + searchField,
success: function (data) {
var splitData = data.split(",");
response(splitData);
}
});
}
$(".searchTextBox").autocomplete({
source: callback,
autoFill: true
})
}
after playing around with it i got the following code to work, before i was using an onkeyup event in the text box but i guess i didnt need it. i dont know if this is efficient but it is working correctly now.
$(document).ready(function () {
$(".searchTextBox").autocomplete({
source: callback,
autoFill: true
});
});
var callback = function (request, response) {
var searchText = request.term;
var searchField = $(".ddlist > option:selected").attr("value");
$.ajax({
type: "GET",
dataType: "text",
url: "SearchCallback.aspx?searchText=" + searchText + "&searchField=" + searchField,
success: function (data) {
var splitData = data.split(",");
response(splitData);
}
});
}
You have to use a callback as the source option when you initialize the autocomplete (in your example you initialize the autocomplete every time a key is being pressed):
var callback = function(request, response) {
var searchText = request.item;
// Set searchField somehow here
$.ajax({
type: "GET",
dataType: "text",
url: "SearchCallback.aspx?searchText=" + searchText + "&searchField=" + searchField,
success: function (data)
{
var splitData = data.split(",");
response(splitData);
});
});
};
$( ".searchTextBox" ).autocomplete({
source: callback,
autoFill: true
});
There are some more examples and a more detailed description in the documentation.