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.');
}
});});
Related
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');;
}
});
}
I'm trying to get a value of several URL input and if value of URL isn't not valid, I just want to animate input element and stop everything.
Is there any way to do it?
$('button').click(function(e){
var linkarr = [];
var $input = $('.default');
var isValidUrl = /[0-9a-z_-]+\.[0-9a-z_-][0-9a-z]/; // URLvalid check
$input.each(function() {
var inputVal = $(this).val();
if(!isValidUrl.test(inputVal)) {
$(this).parent().animateCss('shake');
// if input is not valid, I want to stop the code here.
}
if(inputVal) linkarr.push(inputVal);
});
e.preventDefault();
$.ajax({
url: '/api/compress',
type: 'POST',
dataType: 'JSON',
data: {url: linkarr},
success: function(data){ something
});
});
You need to let outside of your each loop know the condition of the contents.
$('button').click(function(e){
var linkarr = [];
var $input = $('.default');
var isValidUrl = /[0-9a-z_-]+\.[0-9a-z_-][0-9a-z]/; // URLvalid check
var blnIsValid = true;
$input.each(function() {
var inputVal = $(this).val();
if(!isValidUrl.test(inputVal)) {
$(this).parent().animateCss('shake');
// if input is not valid, I want to stop the code here.
// Input isn't valid so stop the code
blnIsValid = false;
return false; // Alternatively don't stop so that any other invalid inputs are marked
}
if(inputVal) linkarr.push(inputVal);
});
e.preventDefault();
// Check to make sure input is valid before making ajax call
if (blnIsValid) {
$.ajax({
url: '/api/compress',
type: 'POST',
dataType: 'JSON',
data: {url: linkarr},
success: function(data){ something
});
}
});
One method is you can use flag to check and execute the Ajax method
$('button').click(function(e){
var linkarr = [];
var $input = $('.default');
var isValidUrl = /[0-9a-z_-]+\.[0-9a-z_-][0-9a-z]/; // URLvalid check
var callAjax = true;
$input.each(function() {
var inputVal = $(this).val();
if(!isValidUrl.test(inputVal)) {
$(this).parent().animateCss('shake');
callAjax = false;
return false;
// if input is not valid, I want to stop the code here.
}
if(inputVal) linkarr.push(inputVal);
});
e.preventDefault();
if(callAjax)
{
$.ajax({
url: '/api/compress',
type: 'POST',
dataType: 'JSON',
data: {url: linkarr},
success: function(data){ something
});
}
});
I am appending html by taking code from data-prototype attribute from one div.
The problem is this that I am appending with two select boxes on which I want to run later jquery, as I want to update second one after choosing option from first one, it is just not executing jQuery code. Everything is alright on select boxes which are inserted when page is loading, but for those from append it doesn't work.
My jQuery Code:
var $optionDefinitions = $('.option-definitions');
var collectionHolder = $('div#epos_productsbundle_variant_options');
var $addOptionsLink = $('Add an option');
var $newLinkLi = $('<li></li>').append($addOptionsLink);
$(function() {
collectionHolder.append($newLinkLi);
collectionHolder.data('index', collectionHolder.find(':input').length);
$addOptionsLink.on('click', function(e) {
e.preventDefault();
addOptionsForm(collectionHolder, $newLinkLi);
});
function addOptionsForm(collectionHolder, $newLinkLi) {
var prototype = collectionHolder.data('prototype');
var index = collectionHolder.data('index');
var newForm = prototype.replace(/__name__/g, index);
var $newFormLi = $('<li id="subform_'+index+'"></li>').append(newForm);
$newLinkLi.before($newFormLi);
collectionHolder.data('index', index + 1);
}
$optionDefinitions.change(function(event){
var $optionid = $(this).val();
var url = '{{ path('variant_options', {'id': 'optionid' }) }}'
url = url.replace("optionid", $optionid)
$.ajax({
url: url,
dataType: "html",
success: function(data){
$(event.target).next('select').html(data);
},
error: function(){
alert('failure');
}
});
})
});
I found the problem. After append I should use on.
So instead of
$optionDefinitions.change(function(event){
var $optionid = $(this).val();
var url = '{{ path('variant_options', {'id': 'optionid' }) }}'
url = url.replace("optionid", $optionid)
$.ajax({
url: url,
dataType: "html",
success: function(data){
$(event.target).next('select').html(data);
},
error: function(){
alert('failure');
}
});
})
I got know
$(body).on('change', $optionDefinitions, function(event){
var $optionid = $(event.target).val();
var url = '{{ path('variant_options', {'id': 'optionid' }) }}'
url = url.replace("optionid", $optionid)
$.ajax({
url: url,
dataType: "html",
success: function(data){
$(event.target).next('select').html(data);
},
error: function(){
alert('failure');
}
});
})
You can try this hack. setTimeout(after, 1);
93 var self = this;
94 var after = function() {
95 self. _container = $("#container");
96 self._slidebox = $("#slidebox");
97 self._slidebox_icon = $("#slidebox_icon");
98 }
99
100 setTimeout(after,1);
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");
}
});
});
I'm trying to use the code below, but it's not working:
UPDATED WORKING:
$(document).ready(function() {
$('.infor').click(function () {
var datasend = $(this).html();
$.ajax({
type: 'POST',
url: 'http://domain.com/page.php',
data: 'im_id='+datasend',
success: function(data){
$('#test_holder').html(data);
}
});
});
});
As you can see I used $datasend as the var to send but it doesn't return the value of it, only its name.
I would change
$datasend = $(this).html;
to
var datasend = $(this).html();
Next I would change
data: 'im_id=$datasend',
to
data: 'im_id='+datasend,