I have a function that returns an undefined variable. I tried all responses in some similar posts but no results.
identifier_id is defined but phcat is not defined. Any ideas?
$(function() {
$('body').on('click', '.save_random_profile', function() {
var identifier_id = $(this).attr("id");
$('.created_profile' + identifier_id).html('<img src="img/loader.gif" class="loading" />');
var phcat = document.getElementById('#phcat'+identifier_id).value;
alert(phcat);
$.ajax({
type: "POST",
async: false,
url: "actions/save_random_profile.php",
data: dataString,
cache: false,
success: function(data) {
if (data == 0) {
$('.created_profile' + identifier_id).html('Not Sent!');
} else {
$('.created_profile' + identifier_id).html(data);
}
}
});
return false;
});
});
Try jquery.attr().
Object.id is a native javascript method and will not be applicable on a jquery collection objects.
To get the id in a jquery object, use var phcat = $('.phcat#' + identifier_id).attr("id");
Or if you want to persist with javascript, use document.querySelector('.phcat#' + identifier_id).id;
$(function() {
$('body').on('click', '.save_random_profile', function() {
var identifier_id = $(this).attr("id");
$('.created_profile' + identifier_id).html('<img src="img/loader.gif" class="loading" />');
var phcat = $('.phcat#' + identifier_id).attr("id");
alert(phcat);
$.ajax({
type: "POST",
async: false,
url: "actions/save_random_profile.php",
data: dataString,
cache: false,
success: function(data) {
if (data == 0) {
$('.created_profile' + identifier_id).html('Not Sent!');
} else {
$('.created_profile' + identifier_id).html(data);
}
}
});
return false;
});
});
EDIT
If you are using document.getElementById, do not use the # along with the id.
var phcat = document.getElementById('phcat'+identifier_id).value;
Use var phcat = $('.phcat#'+identifier_id).attr('id');
use
var phcat = $('.phcat#' + identifier_id)[0].id;
it will give you native JS obj
OR
var phcat = $('.phcat#' + identifier_id).attr('id');
it will return id of element
Related
I created an ajax function that returns my items Price by fetching from my DB. I'm sure there isn't any problem with my php but sometimes I get the same result twice!
jQuery
$('.removemore___').click(function(e) {
var item_id = $(this).attr('data-item');
var col_id = $(this).attr('data-col');
var value = $(this).attr('data-value');
if ($(this).attr('data-trash') == 'trash') {
newPopuper('alert_sure__', 'flex', 'blackScreen');
$('.__aggtoyes').attr('data-item', item_id);
$('.__aggtoyes').attr('data-col', col_id);
$('.__aggtoyes').attr('data-value', value);
} else {
$.ajax({
type: "POST",
url: "includes/chekavailableitem.php?remove",
data: {
item_id: item_id,
col_id: col_id,
value: value
},
dataType: "text",
success: function(response) {
var iNum = parseInt(value);
iNum--;
if (response == 'done') {
$('.value__cart[data-item=' + item_id + '][data-col=' + col_id + ']').html(iNum);
$('.removemore___[data-item=' + item_id + '][data-col=' + col_id + ']').attr('data-value', iNum);
$('.addmore___[data-item=' + item_id + '][data-col=' + col_id + ']').attr('data-value', iNum);
if (iNum == 1) {
location.reload();
}
} else if (response == 'deleted') {
location.reload();
}
},
error: function() {
$('#wrong-signup').html(': 102');
},
timeout: 5000
});
}
$.ajax({
type: "POST",
url: "includes/get_finalize_cart.php",
data: {},
cache: false,
async: true,
dataType: "json",
success: function(response) {
// var final_price = $.parseJSON(response)
console.log(response);
if (response[0] == 'done') {
$('.final_price__').html(response[1] + ' <span style="font-size: .786rem;font-weight: 400">تومان</span>');
} else {
}
},
error: function() {
$('#wrong-signup').html(': 101');
},
timeout: 5000
});
e.stopImmediatePropagation();
return false;
});
Here is full function in jQuery
<?php
include 'db.php';
include 'function.php';
$user_id = extractUserId();
$chekcart = "SELECT * FROM `box` WHERE `user_id`='$user_id'";
$result_cox_cart_cheker = connectANDdie($chekcart);
$sum_price = 0;
while($row_items = mysqli_fetch_assoc($result_cox_cart_cheker)){
$price = $row_items['item_price'];
$value = $row_items['value'];
$sum_price = $sum_price + ( $price*$value );
$final_value = number_format($sum_price);
$result = ['done',$final_value];
$result1 = json_encode($result);
echo $result1;
}
and I'll also show a screenshot from console page so you can see what my result is:
You're not waiting for chekavailableitem.php?remove to complete before you call get_finalize_cart.php. Since AJAX is asynchronous, the latter might be processed first, so you'll get a duplicate of the old value.
You should put the second $.ajax() call in the sucess: function of the first $.ajax() call, or use a promise.
I am working on Infinite scrolling.
Here is the code in js
$('.workspace-activity .modal-body').scroll(function() {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight)
{
loadResults(base + 'co8/workspace/activityLogPagination');
}
});
function loadResults(url) {
start = parseInt($('.modal-body .acti-count').length);
var id = $(".single-workspace").attr("data-id");
$.ajax({
url: url,
type: "POST",
data: "start=" + start + "&limit=10&type=workspace&id=" + id,
success: function(data) {
if (!data) {
noData = '<h5 class="no-data">No more data</h5>';
$('.workspace-activity .modal-body').append(noData);
} else {
$('.workspace-activity .modal-body').append(data);
}
}
});
};
The problem is with !data.
The data returned is empty but the if statement executes the else statement,
Is the condition checking correct?
The problem might exists with the blank spaces
!$.trim(data) will remove the blank spaces
The updated javascript function is
function loadResults(url) {
start = parseInt($('.modal-body .acti-count').length);
var id = $(".single-workspace").attr("data-id");
$.ajax({
url: url,
type: "POST",
data: "start=" + start + "&limit=10&type=workspace&id=" + id,
success: function(data) {
if (!$.trim(data)) {
noData = '<h5 class="no-data">No more data</h5>';
$('.workspace-activity .modal-body').append(noData);
} else {
$('.workspace-activity .modal-body').append(data);
}
}
});
};
i want to check whether is a valid item or not before saving the values. then i create java-script function to check validation and return result. but the problem is this function returns before validate items, the always true the condition above if condition. my code is below. could anyone help me please?
this is series of ajax call and i'm not aware of how to use callback for this..
if(IsValidItems() != ''){
//Do something
}
function IsValidItems() {
var IsvalidStatus = '';
var lineqty = 0;
var LineNumber = -1;
var allRowData = jQuery("#tblJQGrid").jqGrid("getRowData");
for (var i = 0; i < allRowData.length - 1; i++) {
if (allRowData[i].BulkItem != "False") {
if (allRowData[i].quantity != '') {
lineqty = parseInt(allRowData[i].quantity);
LineNumber = i + 1;
var postURL = "/BookingDetail/GetItemAvailablity?ItemCode=" + allRowData[i].itemCode + "&StartDate=" + allRowData[i].StartDate + "&EndDate=" + allRowData[i].EndDate + "&srno=" + allRowData[i].srno + "&locationID=" + allRowData[i].Location;
$.ajax({
url: postURL,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "",
type: "POST",
async: true,
dataFilter: function (data) {
return data;
},
success: function (result) {
if (lineqty > parseInt(result)) {
IsvalidStatus = IsvalidStatus + "," + LineNumber;
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) { }
});
}
}
}
return IsvalidStatus;
}
the weird thing is that I get in my alert the proper values, but not in my
$('kl_naam').val();
var _naam="",
_voornaam="",
_straat="",
_post="",
_gem="",
_firma="",
data="";
function getFsmaGeg(str){
$.ajax({
url: 'classes/FsmaGeg.php?inscript='+str,
dataType: 'json',
error: function() {
//updateAfspraak(final);
},
type: 'post',
complete: function(data) {
data = $.parseJSON(data.responseText);
alert(data.straat);
if(data) {
_naam=data.naam ;
_voornaam=data.voornaam ;
_straat=data.straat ;
_post=data.post ;
_gem=data.gem ;
_firma=data.firma ;
//checkStep1();
}
}
});
$('#kl_voornaam').val()=_voornaam;
$('#kl_naam').val()=_naam;
$('#kl_straat').val()=_straat;
$('#kl_postcode').val()=_post;
$('#kl_gemeente').val()=_gem;
$('#kl_firma').val()=_firma;
alert(_naam+" "+_voornaam+" "+_straat);
}
You should parse the data like
data = JSON.parse(data);
To assign a value to an input do
$(input-selector).val(value);
In your case
function getFsmaGeg(str){
$.ajax({
url: 'classes/FsmaGeg.php?inscript=' + str,
dataType: 'json',
error: function () {
//updateAfspraak(final);
},
type: 'post',
success: function (data) {
data = $.parseJSON(data);
alert(data.straat);
if (data) {
_naam = data.naam;
_voornaam = data.voornaam;
_straat = data.straat;
_post = data.post;
_gem = data.gem;
_firma = data.firma;
$('#kl_voornaam').val(_voornaam);
$('#kl_naam').val(_naam);
$('#kl_straat').val(_straat);
$('#kl_postcode').val(_post);
$('#kl_gemeente').val(_gem);
$('#kl_firma').val(_firma);
}
}
});
alert(_naam + " " + _voornaam + " " + _straat);
}
You need to pass the value into the .val() method: $('#k1_voornaam').val(_voornaam).
You would set it with = if you were using just the DOM API: document.getElementById('k1_voornaam').value = _voornaam.
I have a select menu, that gives the user some criteria options that can use to act as a filter on a search, the user can add as many filters as they wish, however at the moment the user can add the same filter more than once.
What I am wanting to do is, when a user selects a filter from the select box, the value gets added into a array, and then that option in the select box is disabled, is this possible with javascript & jquery?
Currently I have the following
Code that creates a new filter select menu
$('select.option').live({
change: function() {
if($(this).val() == 'distance')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/distance',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'height')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/height',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'appearance')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/appearance',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'education')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/education',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'children')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/children',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'smoking')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/smoking',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'drinking')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/drinking',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'politics')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/politics',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'religion')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/religion',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'ethnicity')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/ethnicity',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'work')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/work',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
}
});
as the name of url and selected option is the same you can try this:
$('select.option').on({
change: function() {
var element = $(this).val();
$(this).prop('disabled', true);
$.ajax({
url: site_url + 'ajax/row/' + element,
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
})
Don't know what your HTML looks like, but I would make it look roughly like this:
<select class="option">
<option value="distance" data-path="ajax/row/distance">Distance</option>
<option value="height" data-path="ajax/row/height">Height</option>
...
</select>
Then have the jQuery be (assuming there are multiple selects in one page and a filter can only be applied once per row):
$('select.option').live({
change: function() {
// get selected history or empty array
var selected = $(this).data('selected') || [];
// get selected option
var $element = $(this).find('option:selected');
// if selected option in history, return
if($.inArray($element.val(), selected) return;
// otherwise, add to history and save back into element
selected.push($element.val());
$(this).data('selected', selected);
// query AJAX by using the data- attribute of the option
$.ajax({
url: site_url + $element.data('path'),
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
});