Json call&loop inside json call&loop with each - javascript

I have two json files in which I have all news headlines and content for particular topic for that news (don't ask me why), so what I am trying to do is to load url with all headlines and after search by id for the right content.
It is looking like that:
$.ajax({
url: 'http://website.com/news.json?=list',
dataType: 'json',
success: function (data) {
$.each(data.news, function (newsId, newsHeadline) {
$('h1').after('<h2 id="question-' + newsId + '">' + newsHeadline + '</h2>');
$.get('http://website.com/news.json?=list&id=' + newsId, function (data) {
$('h2').after('<div class="accordion-content">' + data.result.newscontent + '</div>');
});
});
}
});
So far its working almost as expected, its is loading headlines and after loading content.
Problem is that it is loading all contents for each of headlines. For example by first url there is 2 headlines.
So it should be:
Headline 1
Content 1
Headline 2
Content 2
But instead it giving me:
Headline 1
Content 1
Content 2
Headline 2
Content 1
Content 2

You're not qualifying the reference to <h2> when you append in the $.get() handler. Thus, the content is appended to all <h2> elements.

it's because of the async way ajax call works.
in the first loop you do ajax call with callback and continue to the second loop call (without waiting for the ajax to complete).
the ajax callback can be during another loop so instead of getting 1-1,2-2.3-3 you'll get 1-2,2-2,3-2,4-3 ...
if you need it to remain the same you should think on doing it on a linear way instead of nested async callbacks.

I think it might have something to do with the use of the data variable twice. Try this:
$.ajax({
url: 'http://website.com/news.json?=list',
dataType: 'json',
success: function (data) {
$.each(data.news, function (newsId, newsHeadline) {
$('h1').after('<h2 id="question-' + newsId + '">' + newsHeadline + '</h2>');
$.get('http://website.com/news.json?=list&id=' + newsId, function (data2) {
$('h2').after('<div class="accordion-content">' + data2.result.newscontent + '</div>');
});
});
}
});
Edit:
Oops... looks like Pointy is correct. The $('h2') selector inside the $.get() function is getting ALL the h2 HTML elements on the page.

Related

Parsing BBCode on AJAX success

I am in a spot here trying to parse BBCode upon a AJAX success : item.message object. I am using jQuery 1.11. I have tried passing the var result in place of item.message, and only shows the [object] errors. I have tried wrapping item.message with XBBCODE and same thing.
Im not sure what to do, the script is great otherwise. We must parse bbcode to HTML or a method that can be managed PHP-side, but I don't think this is possible over JSON data.
Currently this is my jQuery code:
$(document).ready(function () {
$.ajax({
url: "/ajax/shoutbox.php",
method: "GET",
dataType: 'JSON',
success: function (data) {
var html_to_append = '';
$.each(data, function (i, item) {
// Object array repeated - not working
var result = XBBCODE.process({
text: 'item.message',
removeMisalignedTags: false,
addInLineBreaks: false
});
/*
currentPost = jQuery(this);
postHTML = bbcodeToHTML(currentPost.html());
currentPost.html(postHTML);
*/
html_to_append +=
'<div class="shoutbox-container"><span class="shoutDate">' +
jQuery.timeago(item.date) +
' <span style="color:#b3b3b3">ago</span></span><span class="shoutUser"><img src="' +
item.avatar +
'" class="shout-avatar" /></span><span class="shoutText">' +
item.message +
'</span></div><br>';
});
$("#shoutbox").html(html_to_append);
$(".shoutbox-container").filter(function () {
return $(this).children().length == 3;
}).filter(':odd').addClass('shoutbox_alt');
$(".shoutbox-container").each(function () {
$(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('shoutbox_alt');
});
}
});
});
As you see, I'm trying to make use of the following javascript:
https://github.com/patorjk/Extendible-BBCode-Parser
I've followed the instructions exactly, before moving into the JS above with no success either way. I get this:
[object][Object]
For each iteration of the message object coming back (its a custom AJAX shoutbox).
Commented, you can see another method I have tried to no success. Any help is appreciated!
Update: Working
Thank you, Quiet Nguyen for the suggestion for replacing item.message with result.html and updating text: object

Why am I getting a '$' is not defined when running an AJAX query?

Possibly a dumb question, but I have a page where I'm trying to load list data into a customer table to display as a front-end. I'm retrieving this list from a SharePoint list using an AJAX call in a Javascript function, however when I'm using this function my console returns a SCRIPT5009: '$' is not defined error. Previously, I've used an AJAX call successfully using very similar code, but to return a single item from the list using the list ID to search for a specific item, and I've run the query successfully directly from the URL that returns the data I'm after - I'm just not sure what's happening with this one.
function getIncidents(){
$.ajax({
url: "SharepointURL/_api/web/lists/getbytitle('Incident List')/items?$select=Title,Id,Priority,IncidentStart,IncidentStatus,IncidentTitle,UpdateResolution",
type: "GET",
headers: {"accept": "application/json;odata=verbose"},
success: function (data) {
var dResponse = data.d.results;
var results = document.getElementById('Results');
results.innerHTML += "<tr><td>Incident<br>Reference</td><td style='width:20px'></td><td>Priority</td><td style='width:20px;'></td><td>Start Time</td><td style='width:20px'></td><td style='width:170px'>Issue</td><td style='width:20px'></td><td style='width:170px'>Latest Update</td><td style='width:20px'></td></tr>";
for(var obj in dResponse){
results.innerHTML += "<tr style='font-size:10pt'><td>"+dResponse[obj].Title + "</td><td></td><td>" + dResponse[obj].Priority + "</td><td></td><td>" + dResponse[obj].IncidentStart + "</td><td></td><td>" + dResponse[obj].IncidentTitle + "</td><td></td><td>" + dResponse[obj].UpdateResolution + "</td></tr>";
}
}
});
}
Previous example where I have this call working:
function getIncident() {
var listName="Incident List";
var incidentID = $("#incidentReference").val();
if(incidentID!=""){
$.ajax({
url: "SharepointURL/_api/web/lists/getbytitle('Incident List')/items?$filter=Title eq '" + incidentID + "'&$select=Title,Id,SystemOrService,Priority,IncidentStatus,IncidentTitle,UpdateResolution,IncidentStart,ImpactedArea,IncidentEnd",
type: "GET",
headers: {"accept": "application/json;odata=verbose"},
success: function (data) {
if(data.d.results.length>0){
var item=data.d.results[0];
$("#systemImpacted").val(item.SystemOrService);
$("#incidentPriority").val(item.Priority);
$("#incidentState").val(item.IncidentStatus);
$("#incidentTitle").val(item.IncidentTitle);
$("#incidentUpdate").val(item.UpdateResolution);
$("#startTime").val(item.IncidentStart);
$("#impactedAreas").val(item.ImpactedArea.results);
$("#endTime").val(item.IncidentEnd);
updateImpact();
getStartTime();
getEndTime();
actionsFormat();
}
},
error: function (data) {
alert("Incident Reference incorrect or not found");
}
});
}
}
The issue is that jQuery ($) is not yet loaded to the page. If you used it before, this means that loading is already setup, so you don't need to add more references to the jQuery.
In most of the cases, when you working with jQuery, you will subscribe on DOM event ready event and do your code there.
So, all you need is to find the
$(document).ready( ...
statement and insert your code there.
If you want to separate your code from already existed, you may write your own $(document).ready subscription.
If you will not find this $(document).ready function, you can search in html for the reference to the jQuery, and insert your script after it. But, than you need to be sure, that reference doesn't include async or defer attribute.
As mentioned in comments, if you decide to add your own subscription, you also need to place it after jQuery reference, because it will not work, if $ isn't available.

Why append part does not work in ajax call

In the code below after I upload my document I wrote a loop which is supposed to add some images into a division called Divnavigation, but this part doesn't work.
Also when I make it uncommented even my documentViewer can not be loaded. Am I allowed to add something to my division from AJAX call?
function navigate(target) {
$.ajax({
url: '#Url.Action("Download", "Patient")',
type: 'GET',
async: true,
dataType: 'json',
cache: false,
data: { 'filepath': target },
success: function (results) {
// documentViewer.loadDocument(results);
documentViewer.uploadDocumentFromUri(results[results.length -1]);
documentViewer.addEventListener(gnostice.EventNames.afterDocumentLoad, function (eventArgs) {
document.getElementById("TotalPage").textContent = documentViewer.viewerManager.pageCount;
document.getElementById("pageNumber").value = documentViewer.viewerManager.currentPage;
$("#Divnavigation").empty();
//Get all images with the help of model
for (var i = 0; i < results.length; i++) {
$("#Divnavigation").append(" <ul> " +
"<li>" +
"<img src=" + results[i] + ">" + "</img>" +
"" + "" +
"</li>"
+ "</ul>");
}
});
//showImages();
},
error: function () {
alert('Error occured');
}
});
}
Hi Answer to your question first:
Am I allowed to add something to my division from .ajax call?
you are 100% allowed to add something to your division from .ajax call. there is no doubt in that. I done personally many times
This time you are not getting because of some other reason.
Now my suggestion is try using $("#Divnavigation").html().
Official doc: https://api.jquery.com/html/
so first as first step try by putting simple html like this $("#Divnavigation").html("<p>test</p>) and see whether you get the output. if you get then change, html string whatever you want ,that can be hardcoded string or even you can get that string from the action method.
Hope above information was helpful. kindly share your thoughts
Thanks

How to refresh a table inside a div tag using ajax php

I have an ajax table click event that gets database data according to the clicked name from the first table and display the second table with employee information. The problem now is that the employee information data only pile up in the second table, I want to refresh the second table every name that the user clicked. By the way the second table is inside a div tag.
Here is my ajax code:
function putThis(control){
var getid = control.innerText;
var first = $("#from[name=from]").val();
var second = $("#to[name=to]").val();
$.ajax({
type:'POST',
url: 'testtable.php',
data: {id: getid,from: first,to: second},
cache: false,
global: false,
success:function(data)
{
$("#result").append(data);
alert("Success: " + getid + " " + first + " to " + second);
}
});
}
If I am reading your question properly (and correct me if I am not), you want to replace the contents of the element rather than append the data to the element.
This can be accomplished with your code by changing this line :
$("#result").append(data);
To this :
$("#result").html(data);
append will put data at the end of the element before the closing tag, while html will consume the element with the data you are inserting.
In your code as I can see you want to click on user name from left panel and call ajax for his/her information from database .
But as you are appending that information to div and this append call append the data a the end of the div instead you can call $("#result").html(data);.
So final ajax call will be-
$.ajax({
type:'POST',
url: 'testtable.php',
data: {id: getid,from: first,to: second},
cache: false,
global: false,
success:function(data)
{
$("#result").html(data);
alert("Success: " + getid + " " + first + " to " + second);
}
});
if still issue persists you can do following steps -
1. check any error in console tab in firebug.
2. if ajax is failing at any point .

Limit number of elements from AJAX response

The AJAX response returns a list of <a> elements:
One
Two
Three
How do I select only the first n a elements from the response?
$.ajax({
url: '/' + page,
success: function (res) {
btn.after($('a', $(res)).slice(0,20));
}
});
That's what I'm currently trying but I'm getting a Uncaught Error: Syntax error, unrecognized expression followed by the whole response.
The response had two closing div elements at the end but no two openings, so I had to make one:
$.ajax({
url: '/' + page,
success: function (res) {
btn.after($('a', $($.trim('<div><div>'+res))).slice(0,20));
}
});
Here is what I would do:
$.ajax({
url: '/' + page,
success: function (res) {
btn.after(res.split('</a>').splice(0, num).join('</a> ') + '</a>');
} });
It splits it and only gives back the elements you want.
JSFiddle: http://jsfiddle.net/howderek/VamZt/
The problem you have is the fact that the context selector returns nothing. A simple test shows it.
console.log($('a', $(res)))
Break it up into pieces. You need to use filter on the content that is return from the server because it is a list of anchors.
var content = $(res);
var anchors = content.filter("a");
var anchorLimit = anchors.slice(0,20);
btn.after(anchorLimit);
Other option is to do what you were doing, but wrap it in a div.
$('a', $("<div>" + res + "</div>"))
JSFiddle

Categories