I am currently trying to post certain blocks of code every time an Ajax call is loaded. I am using Append to do it and it looks like this:
$("#wrap").append("
<div class='newData'>
<div class='infoBox'>
" + firstName + lastName + "
</div>
</div>"
);
My Ajax looks like this:
$.ajax({
type: "GET",
url: "feed.php",
dataType: 'json',
success: function(data) {
for(i = 0; i < data.length; i++){
firstName = data[i].First_Name;
lastName = data[i].Last_Name;
// wrap.innerHTML += '<div class="newData">' + firstName + lastName +'</div>';
$("#wrap").append("
<div class='newData'>
<div class='infoBox'>
" + firstName + lastName + "
</div>
</div>");
}
}
});
When I try to do this nothing comes up. If I take out the infoBox div I get it to work. Is this the proper way to do this. I will be adding multiple different divs inside of this with variables from my Ajax call. Are there better ways to do this or is this the right approach but done wrong?
You aren't concatenating it properly.
It should look like this:
$("#wrap").append("<div class='newData'>" +
"<div class='infoBox'>" +
firstName + lastName +
"</div>" +
"</div>");
Related
I have DataTables table with row details which are opening by clicking on row. The row details are displayed in 3 different languages which are selected by checkbox. When the row is clicked, the language is send to details.php script (langy:chLanguage) which returns json values for this selected language.
Initialy the language is set to chDe and everything is working fine until I click on another language. When the language is changed to EN or RU, or even back to DE, the returned json is empty.
index.php :
<h5>Language</h5>
<input type="checkbox" id="chDe" name="languages" checked>DE
<input type="checkbox" id="chEn" name="languages">EN
<input type="checkbox" id="chRu" name="languages">RU
<script>
var chLanguage = "chDe";
$('input[name=languages]').click(function() {
$('input[name="' + this.name + '"]').not(this).prop('checked', false);
chLanguage = [];
$('input[name=languages]:checked').each(function() {
chLanguage.push($(this).attr('id'));
});
if (chLanguage == '') {
chLanguage = 5;
}
$('#example').DataTable().ajax.reload();
});
function format ( rowData, row, $chLanguage ) {
// FOLLOWING CONSOLE.LOG RETURNS THE ACTUALLY SELECTED LANGUAGE CORRECTLY
console.log("chLanguage in format function: " + chLanguage);
var div = $('<div/>')
.addClass( 'loading slider' )
$.ajax( {
url: 'scripts/details.php',
data: {
name: rowData[0],
langy: chLanguage,
},
dataType: 'json',
type: 'post',
success: function ( json ) {
// FOLLOWING CONSOLE.LOG RETURNS [Object object] unless the language is changed, then it returns nothing
console.log("json: " + json);
var childTable = '<div id="rowdetails" class="slidera"><ul class="slider">';
childTable = childTable.concat(
'<div class="row rdstyle">' +
'<table class="detailstable detailserrors">' +
'<tr><td><b>Error class:</b></td><td>' + json[0].ERRTRIEDA + '</td></tr>' +
'<tr><td><b>Error group:</b></td><td>' + json[0].ERRSKUPINA + '</td></tr>' +
'<tr><td><b>Error:</b></td><td>' + json[0].ERRPOPIS + '</td></tr>' +
'</table>' +
'</div>
);
});
}
details.php :
$language = $_POST['langy'];
if ($language == 'chDe' ) {
$setLang = 'DE';
}else if($language == 'chEn') {
$setLang = 'EN';
} else{$setLang = 'RU';}
and $setLang is used in SQL query to filter data by language.
I hope I'm not far away from working solution, because it's working already, just the language switch don't work. Sorry not to attach working sample. I don't know how to implement all these parts including mysql db and several differenct php scripts :(
I am new to Coding and I got stuck for hours solving this problem:
The response from AJAX is a Json two-dimesional array jqXHR[][] the first index
describes each product id, the second one holds product details like prices etc.
So all i want to is to iterate through the first index by using the button "New_Suggestion" and to update the html content in the "result_wrapper".
The response works fine, but updating the html content doesn't work at all.
Thank you for your help.
$.ajax({
type: "POST",
url: "productsuggestion.php",
data: "criteria1=" + crit1 + "&criteria2=" + crit2 + "&criteria3=" + crit3 + "&criteria4=" + crit4 + "&criteria5=" + crit5,
dataType: "json",
success: function(jqXHR) {
var sug = 0;
$('#New_Suggestion').on('click', function() {
sug = sug + 1
});
$("#result_wrapper").html(
'<div id="prod_name">' + jqXHR[sug][0] + '</div> <br>' +
'<img id="prod_pic" src="' + jqXHR[sug][4] + '">' +
'<div id="prod_price">' + jqXHR[sug][2] + '</div> <br>'
);
}
});
Firstly, your "click" handler just increments a variable when it's clicked. It doesn't touch the output at all.
Secondly, every time the ajax runs, you add another click event handler to the button, without removing the previous one(s). It's easier to declare this outside the ajax context, and set a global variable for the suggestion count.
Something like this, I think (untested):
var sugCount = 0;
var sugData = null;
$.ajax({
type : "POST",
url : "productsuggestion.php",
data : "criteria1="+crit1+"&criteria2="+crit2+"&criteria3="+crit3+"&criteria4="+crit4+"&criteria5="+crit5,
dataType: "json",
success: function(data){
//reset global data after each ajax call
sugCount = 0;
sugData = data;
writeSuggestions(sugCount, sugData); //output the initial set of suggestions
}
});
$('#New_Suggestion').on('click',function(){
sugCount = sugCount + 1;
writeSuggestions(sugCount, sugData); //output updated suggestions
});
function writeSuggestions(count, data)
{
$("#result_wrapper").html('<div id="prod_name">'+data[count][0]+'</div> <br>'+
'<img id="prod_pic" src="'+data[count][4]+'">'+
'<div id="prod_price">'+data[count][2]+'</div> <br>');
}
I have been working on a e-commerce web application. There is a wishlist module which I'm trying to implement. I'm adding the products into wishlist using ajax calls and also removing it with ajax. The adding part works fine but I have a problem in removing part . What I'm trying to do is, making an ajax call to fetch the wishlist items from the database and adding a remove button dynamically using jquery. Although I know that I have to use a .live function to attach an event to it which I did but when i click on the button all the items which are present in the wishlist are removed . I see multiple ajax request was made in console under network tab and I don't get it why , although I clicked it only once. The following is a snippet of my code
$.ajax({
type: "POST",
url: "fetchdata1",
data: "cat=" + cat,
success: function(data) {
productContainer.innerHTML = "";
var $productContainer = $('#productContainer');
$.each(data, function(key, value) {
if (value['newVar'] === 1) {
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id=" + value['id'] + "'><img src='" + value["image"] + "'/></a><br/>\n\
<a href='product.jsp?id=" + value['id'] + "'><span class='black'>" + value['name'] + "</span></a><br/>\n\
<span class='black'>By " + value['company'] + "</span><br/><span class='red'>RS." + value['price'] + "</span>\n\
<br/><br/><a id='remove' href='#'>REMOVE</a></div>");
foo(value['id']);
} else {
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id=" + value['id'] + "'><img src='" + value["image"] + "'/></a><br/>\n\
<a href='product.jsp?id=" + value['id'] + "'><span class='black'>" + value['name'] + "</span></a><br/>\n\
<span class='black'>By " + value['company'] + "</span><br/><span class='red'>RS." + value['price'] + "</span></div>");
}
});
}
});
function foo(value) {
var pid = value;
$('#remove').live("click", function() {
$.ajax({
type: "POST",
url: "removeFromWishlist",
data: "pid=" + pid,
success: function(response) {
}
});
});
In the first ajax request I'm fetching products from the database then adding remove button to it dynamically then calling function foo which attach the click event using .live function and then make call to database to remove it.
Hey guys I'm not pro at web, so go easy on me if I made some silly mistake.
Thanks!
Problem:
You have same id for multiple hyperlink and you are using .live function on "id based" selector. It is applying click function again & again on first element.
Solution:
Update your hyperlink
<a href='#' onclick="foo(this)" pid=value['id']>REMOVE</a>
Then in foo() function
function foo(obj) {
var pid = $(obj).attr("pid");
$(obj).bind("click", function() {
$.ajax({
type: "POST",
url: "removeFromWishlist",
data: "pid=" + pid,
success: function(response) {
}
});
});
i don't get why you using same id multiple times.
and afaik, jQuery.live already deprecated.
you can use this if you want to get live behavior:
$(document).on('click', 'element-selector', function(){
...
});
with your code, it can rewriten to:
$(document).on('click', '[id=remove]', function(){
...ajax call...
});
now the problem with your fetch data function is this:
$.each(data, function(key, value) {
if (value['newVar'] === 1) {
...append element...
**foo(value['id']);**
} else {
...append element...
}
});
as we know foo() are your function that bind remove behavior.
based on your code, whenever that fetch data has newVar = 1, it will directly call foo. which mean binding remove behavior multiple times, as many as newVar = 1 was.
solution:
you can put pid as a attribute on your a element
maybe something like remove
and within remove click function, you can use $(this).attr('pid') to get that value.
and remove that foo() content to outside the function, since $(element).live(...) or $(document).on(event, element, ...) will listen the element, even the element dynamicly added to the page.
The issue happened because you register listener multiple times in each loop. So to resolve, you need to register once after all button has been populated. I also change selector to class ".remove" because you going to have multiple remove button so using id is will be duplicated, and using jquery .on() instead of .live() (deprecated)
$.ajax({
type: "POST",
url: "fetchdata1",
data: "cat=" + cat,
success: function(data) {
productContainer.innerHTML = "";
var $productContainer = $('#productContainer');
$.each(data, function(key, value) {
if (value['newVar'] === 1) {
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id=" + value['id'] + "'><img src='" + value["image"] + "'/></a><br/>\n\
<a href='product.jsp?id=" + value['id'] + "'><span class='black'>" + value['name'] + "</span></a><br/>\n\
<span class='black'>By " + value['company'] + "</span><br/><span class='red'>RS." + value['price'] + "</span>\n\
<br/><br/><a class='remove' id='remove' data-pid='" + value['id'] + "' href='#'>REMOVE</a></div>");
} else {
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id=" + value['id'] + "'><img src='" + value["image"] + "'/></a><br/>\n\
<a href='product.jsp?id=" + value['id'] + "'><span class='black'>" + value['name'] + "</span></a><br/>\n\
<span class='black'>By " + value['company'] + "</span><br/><span class='red'>RS." + value['price'] + "</span></div>");
}
});
foo();
}
});
function foo() {
$('.remove').on("click", function() {
var pid = $(this).data("pid");
$.ajax({
type: "POST",
url: "removeFromWishlist",
data: "pid=" + pid,
success: function(response) {
}
});
});
So the problem is that I'm loading JSON files from url into my html and it's working perfectly besides for the fact that it shows the information twice..
Does anyone know why this is the case?
Here's the Jquery/Javascript code that I use to load the JSON into my html.
$.ajax({
url: 'http://datatank4.gent.be//bevolking/totaalaantalinwoners.json',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
i = 0;
var access;
var url;
$(data).each(function(index, value) {
wijkname = value.wijk;
year = value.year_2010;
i++;
$('#pagewrap2').append(
'<div class="dataond col col-xxs-12 col-md-3"> <h2> ' + wijkname + '</h2><p>' + year + '<div id="maps">' + "<iframe width='100%' height='100%' frameborder='0' scrolling='no' marginheight='0' marginwidth='0' src='https://maps.google.com/maps?&q="+ encodeURIComponent( wijkname + ' ' + 'Gent' ) +"&output=embed'></iframe>" + '</div>' + '</p></div>'
);
});
}
});
First check the response of this ajax call.
If the response look fine maybe you're making the ajax call twice.
For example when you add an event listener twice. (add off() function before click() if you're using jquery)
I've found the problem. Really stupid but I linked my file twice in my index.html...
Thanks everyone for your replies.
<script type="text/javascript">
$(document).ready(function() {
var categoriesId = [];
$.getJSON("http://datatank4.gent.be//bevolking/totaalaantalinwoners.json", function(data) {
$.each(data, function(index, item) {
categoriesId.push(item.wijk);
}
);
for (i = 0; i < categoriesId.length; i++) {
alert(categoriesId[i]);
var newInProductPriceDiv = document.createElement('div');
newInProductPriceDiv.setAttribute('id', "recentlyViewedProductPriceDiv" + i);
newInProductPriceDiv.setAttribute('class', "subcategoryListPriceDiv");
newInProductPriceDiv.innerHTML = newInProductPriceDiv.innerHTML + categoriesId[i];
document.getElementById('pagewrap2' + i).appendChild(newInProductPriceDiv);
}
}
);
}
);
</script>
if you have any confusion then tell me ok . and if you not get your exactly output then also tell me.
i know this question has been asked lot many times but not sure after seeing so many examples, i cannot figure why it is not happening..
this is my code
function update(tid,sid) {
var getTID = tid;
var getSID = sid;
$("#flow_" + getTID + "~" + getSID).html('Loading...');
$.ajax({
url: 'generate.cfm?tID=' + getTID + '&sID=' + getSID,
type: "GET",
cache: false,
success: function(data){
var k = $(data).find("img");
$("#flow_" + getTID + "~" + getSID).empty();
$("#flow_" + getTID + "~" + getSID).append(k);
}
});
}
here is the div code
<div id="flow_#tid#~#sid#" style="margin: 0 10px 0 0;float:right;height:150px;" class="code">
<img src="#request.webbaseurl#assets/codes/#code#.jpg" style="max-height: 230px;">
</div>
i am missing something here, not sure what like timeout or something but after successful call, it should reload that div
Update#1
Here i had made changes which i did the following after response,to make sure i get the image, rather than image tag, i used the div id and it loads the inside img element in alert, i tested that
success: function(data){
var k = $(data);
var hiddenField = $('<div type="hidden" ></div>');
hiddenField.append(k);
var images = hiddenField.find('#inner');
$("#ystack_" + getTID + "~" + getSID).hide();
$("#flow_" + getTID + "~" + getSID).empty();
$("#flow_" + getTID + "~" + getSID).append(images.html());
}
but it does reload the div, if i refresh the whole page, it do show me the changed contents
you are not able to find image object directly in response.
var k = $(data).find("img");
this will not work.store response HTML code in hidden element.and find for image tag .
HTML code
<div id="hiddendiv" style="display:none;"> </div>
JQuery ajax success
success: function(data){
$('#hiddendiv').HTML(data);
var obj =$('#hiddendiv').find(img);
$("#flow_" + getTID + "~" + getSID).empty();
$("#flow_" + getTID + "~" + getSID).append('<img src="'+obj.attr("src")+'"/>');
}