I don't know why the selector jquery doesn't accept a variable.
function myfunction()
{
$.ajax({
url: "/file.php", dataType: "json", type: "GET",
success: function(data)
{
var data = data.split("-");
data.forEach(function(entry)
{
if (entry != "")
{
$("#check_status_" + entry).html('text');
}
});
}
});
}
variable entry is not empty, the problem is when I put it into the selector.
Thanks.
[update]
{
var test = "aaa-bbb-ccc";
var data = test.split("-");
data.forEach(function(entry) {
if (entry != ""){
$("#check_status_" + entry).html('!NEW!');
}
});
}
nothing the same
It seems to work fine if you are achieving something like this
data.forEach(function(entry) {
if (entry) {
$("#check_status_" + entry).html('text');
}
});
Related
I have the following code where I wanna remove and add an element back to the DOM in jQuery:
var pm_container = $(document).find('.pm-container');
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this), pm_container);
});
function displayPrice(elem, pm_container){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').remove();
} else {
$(document).find('.save-listing').prev(pm_container);
}
}
});
}
For some reason, when the value of amount_field is not equal to zero, my element .pm-container is not added back into my page.
Any idea why?
Thanks for any help.
When you remove the element, it is gone. there is no way to get it back. one solution is to clone the element into a variable and be able to re-use it later:
var pm_container = $(document).find('.pm-container').clone();
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this), pm_container); });
function displayPrice(elem, pm_container){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').remove();
} else {
$(document).find('.save-listing').prepend(pm_container);
}
}
}); }
However, for your case, Best way could be hiding and showing back the element:
$(document).on('change', '#payment-form .cat_field', function(){
displayPrice($(this)); });
function displayPrice(elem){
$.ajax({
type: 'GET',
url: 'getamount.php',
dataType: 'json',
cache: false,
success: function (data) {
var amount_field = $(document).find('#payment-form #amount');
amount_field.val(data.price);
if(amount_field.val() == 0) {
$(document).find('.pm-container').hide();
} else {
$(document).find('. pm-container').show();
}
}
}); }
First create a variable for your Clone .pm-container outside ajax function
Note*: When you use .remove() you cannot take it back.
var container = $(".pm-container").clone();
then inside your ajax function
if (amount_field.val() == 0) {
$(".pm-container").detach();
} else {
container.insertBefore($(".save-listing"));
}
jsfiddle: https://jsfiddle.net/marksalvania/3h7eLgp1/
building html that use jquery to get data from web API.
In the beginning of my script I did a function that checks the value of dropdown (what is selected) and according to the selected it's fill the global variable.
var $seldom;
$(document).ready(function () {
function chkdom() {
if ($("#dropdomain").val('Europa')) {
$seldom = '192.168.5.37';
}
else if ($("#dropdomain").val("Canada")) {
$seldom = '172.168.0.1';
}
}
after defining the function I calling it immediately to check it and fill the variable.
finally by Clicking on search it should check what selected from dropdown and according to that fill again the variable and start GET function with the modified URL
$('#search').click(function () {
chkdom();
$.ajax({
url: "http://" + $seldom + "/api/find/" + $("input#user").val(),
Problem: After I start the debug the $selcom always get the value of '192.168.5.37' doesn't matter what I do.
Tried to debug it many ways but couldn't find why it's assigning that value.
Please assist as it should be so simple but I must missed something.
Here is the part of the code from the begining:
var $seldom;
$(document).ready(function () {
function chkdom() {
if ($("#dropdomain").val('Europa')) {
$seldom = '192.168.5.37';
}
else if ($("#dropdomain").val("Canada")) {
$seldom = '172.16.0.1';
}
}
chkdom();
alert($seldom);
alert($("#dropdomain").val());
$('#search').click(function () {
chkdom();
$.ajax({
url: "http://" + $seldom + "/api/find/" + $("input#user").val(),
type: "GET",
dataType: 'Jsonp',
success: function (result) {....}
Problem: After I start the debug the $selcom always get the value of '192.168.5.37' doesn't matter what I do.
Don't:
if ($("#dropdomain").val('Europa')) {
$seldom = '192.168.5.37';
}
else if ($("#dropdomain").val("Canada")) {
$seldom = '172.168.0.1';
}
Do:
if ($("#dropdomain").val() === 'Europa') {
$seldom = '192.168.5.37';
}
else if ($("#dropdomain").val() === "Canada") {
$seldom = '172.168.0.1';
}
See documentation of jQuery.val():
.val(value)
Description: Set the value of each element in the set of matched
elements.
value argument
Type: String or Number or Array
A string of text, a number, or an array of strings corresponding to the value of each matched element to
set as selected/checked.
So, calling $("#dropdomain").val('some value') writes a value to the $("#dropdomain") element. To read its value, call $("#dropdomain").val().
Try the code below:
var $seldom;
$(document).ready(function () {
function chkdom() {
if ($("#dropdomain").val() === 'Europa') {
$seldom = '192.168.5.37';
}
else if ($("#dropdomain").val() === 'Canada') {
$seldom = '172.16.0.1';
}
}
chkdom();
alert($seldom);
alert($("#dropdomain").val());
$('#search').click(function () {
chkdom();
$.ajax({
url: "http://" + $seldom + "/api/find/" + $("input#user").val(),
type: "GET",
dataType: 'Jsonp',
success: function (result) {....}
This condition $("#dropdomain").val('Europa') is always writing and is being evaluated as true.
So, you need to compare the values:
var drop = $("#dropdomain").val();
if (drop === 'Europa') {
$seldom = '192.168.5.37';
} else if (drop === "Canada") {
$seldom = '172.16.0.1';
}
I have a connection with my DB and my DB sends me some integer value like "1","2" or something like that.For example if my DB send me "3" I display the third page,it's working but my problem is when it displays the third page it's not hide my current page.I think my code is wrong in somewhere.Please help me
<script>
function show(shown, hidden) {
console.log(shown,hidden)
$("#"+shown).show();
$("#"+hidden).hide();
}
$(".content-form").submit(function(){
var intRowCount = $(this).data('introwcount');
var exec = 'show("Page"+data.result,"Page' + intRowCount + '")';
ajaxSubmit("/post.php", $(this).serialize(), "", exec,"json");
return false;
})
function ajaxSubmit(urlx, datax, loadingAppendToDiv, resultEval, dataTypex, completeEval) {
if (typeof dataTypex == "undefined") {
dataTypex = "html";
}
request = $.ajax({
type: 'POST',
url: urlx,
dataType: dataTypex,
data: datax,
async: true,
beforeSend: function() {
$(".modalOverlay").show();
},
success: function(data, textStatus, jqXHR) {
//$("div#loader2").remove();
loadingAppendToDiv !== "" ? $(loadingAppendToDiv).html(data) : "";
if (typeof resultEval !== "undefined") {
eval(resultEval);
} else {
//do nothing.
}
},
error: function() {
alert('An error occurred. Data does not retrieve.');
},
complete: function() {
if (typeof completeEval !== "undefined") {
eval(completeEval);
} else {
//do nothing.
}
$(".modalOverlay").hide();
}
});
}
</script>
Thanks for your helping my code working fine now.The problem is occured because of the cache. When I clear cache and cookies on Google Chrome it fixed.
The second parameter passed into the show() method is a bit wrong:
"Page' + intRowCount + '"
Perhaps you meant:
'Page' + intRowCount
Edit: wait wait you pass in a string of code to ajaxSubmit? What happens inside it?
If ajaxSubmit can use a callback, try this:
var exec = function(data) {
show('Page' + data.result, 'Page' + intRowCount);
};
Assuming your html is:
<div id='Page1'>..</div>
<div id='Page2'>..</div>
<div id='Page3'>..</div>
add a class to each of these div (use a sensible name, mypage just an example)
<div id='Page1' class='mypage'>..</div>
<div id='Page2' class='mypage'>..</div>
<div id='Page3' class='mypage'>..</div>
pass the page number you want to show and hide all the others, ie:
function showmypage(pageselector) {
$(".mypage").hide();
$(pageselector).show();
}
then change your 'exec' to:
var exec = 'showmypage("#Page"+data.result)';
It would be remiss of my not to recommend you remove the eval, so instead of:
var exec = "..."
use a function:
var onsuccess = function() { showmypage("#Page"+data.result); };
function ajaxSubmit(..., onsuccess, ...)
{
...
success: function(data) {
onsuccess();
}
}
While i was searching at stackoverflow, i found the code below :
$(document).ready(function () {
$("#show").click(function () {
getYoutube($("#Search").val());
});
});
function getYoutube(title) {
$.ajax({
type: "GET",
url: yt_url = 'http://gdata.youtube.com/feeds/api/videos?q=' + title + '&format=5&max-results=1&v=2&alt=jsonc',
dataType: "jsonp",
success: function (response) {
if (response.data.items) {
$.each(response.data.items, function (i, data) {
var video_id = data.id;
var video_title = data.title;
var video_viewCount = data.viewCount;
$("#result").html(video_id);
});
} else {
$("#result").html('false');
}
}
});
}
How can i edit the code to keep only the function?
I want to be able to use it like that : getYoutube(my_keywords);
Also, how can i save the function output to variable? something like :
var_name = getYoutube(my_keywords);
would be ok?
Thnx! ;)
yes, you can use it as without $(document).ready. No, function does not return anything
To "return" value from Ajax:
$.ajax({
...
success: function(dataFromServer) {
processServerOutput(dataFromServer);
}
});
function processServerOutput(someString) {
alert(someString);
}
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");
}
});
});