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
Related
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
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.
I'm using ajax to make a request to a webservice.
$(document).ready(function(e) {
var token = "123";
$.ajax({
type: "POST", //REQUEST TYPE
dataType: "json", //RESPONSE TYPE
url: "http://ws/mehtod"+token,
success: function(data) {
console.log(data);
$.each(data, function(i) {
$('#list_countries').append("<option>" + data[i].Name + "</option>"); //fILL THE DDL. FOR EACH ITEM RETURNED ADD DATA[NAME] TO ONE LINE OF THE DDL.-
});
},
error: function(err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
}).always(function(jqXHR, textStatus) {
if (textStatus != "success") {
alert("Error: " + jqXHR.statusText);
}
})
});
and the question is: I have multiple elements in my html that have the ID "list_countries" (they're all the same element but in different panels inside the page) and my rerquest works and treats the data well but for some reason it only fills one of the elements. The others don't fill with the data requested. What can be the cause of this?? Thank you all in advance.
Most likely because you use identificator #list_countries multiple times. Better use class selector or unical ids:
$('#list_countries, #list_countries_2, #list_countries_3');
// or
$('.list_countries');
Try This:
$('#list_countries').each(function() {
$(this).append("<option>" + data[i].Name + "</option>");
});
The selector that you're using tells jQuery to internelly use the native document.getElementById() method for fetching the DOM wich returns ONLY the first node which appears in the page that matches the selector regardless to any other node(s) with the same ID.
So, you have to enforce jQuery to NOT use the native document.getElementById() method and here's a trick for you:
$.each(data, function(i) {
$('body #list_countries').append("<option>" + data[i].Name + "</option>");
});
Note the body before #list_countries, here we enforce it to use the Sizzle for this job instead of document.getElementById() method.
PS: I strongly suggest that you use the same class for different elements instead of the ID which must be unique in the page.
I am seeing a sporadic issue that is causing me a headache to investigate.
I have a PHP page with a basic form with a few simple text fields.
jQuery is used to send this POST data back to the server which in turn saves a record in MySQL and sends email notifications. This works fine throughout the day but randomly (I cannot recreate it). the server will add the same record 5-10 times in the DB and send the same amount of emails.
The only clue to me which is causing this is that random a random jQuery string is included in some of the returned data (see below)
Comments: Please can you sendjQuery17209552029577380006_1461157696021
this to me.
I am using jQuery 1.7.2 which explains the jQuery172, but not sure what the rest of this is.
Any ideas on where I should go with this? I may upgrade jQuery to see if this resolves it but thought I would ask here also?
jQuery 1.7.2 Code Below:
$(document).ready(function() {
$('#quick_form').submit(function(e) {
e.preventDefault();
$.ajax({
url: baseUrl+'products/send_quote',
dataType: 'json',
type: "POST",
async: true,
cache: false,
data: 'prod_id='+$('input[name="prod_id"]').val() + '&' +
'quote_name='+$('input[name="quote_name"]').val() + '&' +
'quote_email='+$('input[name="quote_email"]').val() + '&' +
'quote_phone='+$('input[name="quote_phone"]').val() + '&' +
'quote_company='+$('input[name="quote_company"]').val() + '&' +
'quote_cols='+$('input[name="quote_cols"]').val() + '&' +
'quote_size='+$('input[name="quote_size"]').val() + '&' +
'quote_qty='+$('input[name="quote_qty"]').val() + '&' +
'quote_comments='+$('#quote_comments').val() + '&' +
'token='+$('input[name="token"]').val(),
success: function(response) {
if(response.success) {
$('#quote').slideUp('fast',function() {
$('#quote').empty().html('<div class="successMessage">'+response.message+'</div>');
}).slideDown('fast');
}
else {
$('.errMess').empty();
$.each(response.messages,function(k,v) {
$('.errMess').append('<div>'+v+'</div>').show();
});
}
}
});
});
});
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.