So, the Javascript code which can be found below doesn't seem to be functioning properly.
The goal is to get the text below the map to change on hover of the rooms.
Map Page
The JSON (zadias.me/SVG/rooms.json) data that pulls the data seems to be where I'm faulting, I think. When I test/debug the code by placing .innerHTML statements that would print in the text field, it would work if I placed the .innerHTML before the $.ajax, however, if I put the .innerHTML function in the "success" part of the .ajax, it wouldn't work..
Javascript:
$(document).ready(function(){
var json = (function () { //this function obtains the data
var json = null;
$.ajax({
'async': false,
'global': false,
'url': 'http://zadias.me/SVG/rooms.json',
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
function hashTag(){
var hashTag, hash2;
hashTag = location.hash; //obtains the part of the URL with the hash tag and what follows
hashTag = hashTag.replace(/#*/, ''); //replaces the hash tag
if(hashTag.length > 0){
for(i=0 ; i<json.rooms.length ; i++){
if (json.rooms[i].roomId == hashTag) //linear search through array of rooms to see if any equal the hashTag
{
document.getElementById('room_info').innerHTML = '<img src="images/' + json.rooms[i].image + '" /><h4>' + json.rooms[i].name + '</h4>' + json.rooms[i].HTMLdescrip;
} //loads the data from the JSON data.
}
}
};
function setHash(){
window.location.hash = this.id; //creates the hash link based on the object's id (object id acquired from the JSON data) and sets it
};
function setHTML(){
for(i=0 ; i<json.rooms.length ; i++){
if (json.rooms[i].roomId == this.id)
{
document.getElementById('room_info').innerHTML = '<img src="images/' + json.rooms[i].image + '" /><h4>' + json.rooms[i].name + '</h4>' + json.rooms[i].HTMLdescrip;
}
}
};
window.onload = hashTag();
$(".active").click(setHash);
$(".active").mouseenter(setHTML);
//$(".active").mouseover(setHTML);
$(".active").mouseleave(hashTag);
});
I understand that it's a bit localized, how could I change this up?
If I'm getting it right, you need the variable json to be global. Just take off the var at the beginning and see if that helps.
You may want to try something more along these lines:
// this returns a promise
var json,
response = $.ajax({
'async': false,
'global': false,
'url': 'http://zadias.me/SVG/rooms.json',
'dataType': "json",
'success': function (data) {
json = data;
}
});
window.onload = function() {
// ensures that the ajax has returned a value
response.done(hashTag);
};
The document doesn't really have to be ready for you to run an AJAX request.
You may want to take a look here for accessing the SVG elements: How to access SVG elements with Javascript. Requires a change from <embed> to <object>
Here's a version of your code with a few updates:
var json;
$(document).ready(function(){
$.ajax({
'global': false,
'url': 'http://zadias.me/SVG/rooms.json',
'dataType': "json",
'success': function (data) {
json = data;
hashTag();
$(".active")
.click(setHash)
.mouseenter(setHTML)
.mouseleave(hashTag);
}
});
});
function hashTag(){
//get everything in the URL after the #
var hash = location.hash.replace(/#*/, '');
if(hash.length > 0){
//linear search through array of rooms to find the hashTag
$.each( json.rooms, function( room ) {
if (room.roomId == hash) {
$('#room_info').html(
'<img src="images/' + room.image + '" /><h4>' +
room.name + '</h4>' + room.HTMLdescrip
);
} //loads the data from the JSON data.
});
}
};
// creates the hash link based on the object's id
// (object id acquired from the JSON data) and sets it
function setHash(){
window.location.hash = this.id;
}
function setHTML(){
$.each( json.rooms, function( room ) {
if (room.roomId == this.id) {
$('#room_info').html(
'<img src="images/' + room.image + '" /><h4>' +
room.name + '</h4>' + room.HTMLdescrip
);
}
});
}
What I changed:
Made the json variable global.
Removed the async:true. Never use that!
Removed global:false. You don't have any global Ajax event handlers, so this flag has no effect.
Removed unnecessary quotes around the $.ajax() property names.
Removed the event handler setup at the end of the code.
Moved that initialization inside the $.ajax() callback since that is when the data is ready.
Chained together the event handler setup on $(".active") instead of repeating the selector call.
Used $.each() instead of the for loops for simplicity.
Changed the json.rooms[i] references to room thanks to $.each().
Used $('#foo').html(html) instead ofdocument.getElementById()and.innerHTML`, again for simplicity.
Simplified the setup of the hashTag variable and changed its name to hash to avoid confusion with the function name.
Removed unnecessary semicolons at the end of function definitions.
Made the indentation and formatting more consistent.
Shortened the excessive line lengths.
Some of these changes are just stylistic, but they're things I recommend. Naturally you can pick and choose among those after looking through the code.
The important point is making sure that the json data is available not just where it's needed, but when it's needed, and without using async:false.
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.
test.xml
<Bock1>
<No>123</No>
<RoomNo>10</RoomNo>
<UpdateTime>1230</UpdateTime>
</Block1>
run.js
$.ajax({
type: "GET",
url: test.xml,
dataType: "xml",
success: function (xml) {
$(xml).find('Block1').each(function () {
var updateTime = $(this).find("UpdateTime").text();
var no= $(this).find("No").text();
var roomNo = $(this).find("RoomNo").text();
var status = no + '<br/>' + roomNo + '<br/>' + updateTime;
});
}
});
$('<div>')
.attr({
'data-role': 'collapsible', 'data-collapsed': 'false', 'data-mini': 'true'
})
.html('<h4>' + item_name + '</h4><p>' + status + '</p>')
.appendTo(collapsibleset);
}
});
I'm using this to generate collapsibleset with xml data,
but status can't correctly fill into
<p> + status + </p>
status will get correctly inside ajax, but can't get to collapsibleset.
I've tried to use global variable, but get same situation.
How could I fill it in correctly?
I'm new to jquery & javaScript,
Thanks for any answers!!!
jQuery.ajax() is expecting string for the URL value.
Therefore your URL just needs wrapping in quotes.
Then your DOM reference of the
$('< div >')
is wrong.
To reference an element in JQuery, you have several options, but the easiest is to give an element an id and then reference that (think CSS)
$('div') would get all divs
$('div#my_id') would get this particular element:
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
My code is as follows:
$('*[data-pickup]').change(function(){
var value = $(this).val();
console.log(value);
$.ajax({
type : "POST",
cache : false,
url : "a.php?pickup",
data : {'X': value},
success: function(data) {
$("*[data-pick='" + $(this).attr("data-pickup") + "']").html("HELLO");
}
});
$("*[data-pick='" + $(this).attr("data-pickup") + "']").html("HELLO 2");
$("*[data-pick='" + $(this).attr("data-pickup") + "']").show();
})
The AJAX call shows a response when viewed through Firebug, which wasn't being refreshed on the screen, so I changed it to a simple "Hello" response, which still doesn't work.
If I comment out the .html("HELLO 2") line, it shows the once hidden div containing the HTML5 data element of data-pick=1 or data-pick=2, etc. (depending on what attr("data-pickup") is) which is automatically filled with "Test", so it shows "Test".
If I uncomment the .html("HELLO 2") line, the div once shown says "HELLO 2". But, in the case of the commented out .html("HELLO 2") line, it should be being updated from "Test" to "Hello" via the AJAX call, but it isn't. If I change the data* to a simple HTML id element and update all the code to #" + $(this).attr("data-pickup") + ", it works the exact same with the data attribute (the AJAX call doesn't update anything).
And when I make a var called "el" and make it equal to *[data-pick='" + $(this).attr("data-pickup") + "'], and then print it to the console it appears as: "[data-pick='1']" or "[data-pick='2']", etc. Then if I update all the code from $("*[data-pick='" + $(this).attr("data-pickup") + "']").whatever to $(el).whatever (thinking there might be a bug somewhere), it still works the same as before.
So, what have I done wrong? Why won't the div get refreshed via the AJAX call but it will after the AJAX call?
The problem is that 'this' in the success handler of the ajax function is the ajax function itself not the element that triggered the event handler. What you need to do is store the value of the element var el = $(this) then reference that whenever you want to access the element taking advantage of closures.
$('*[data-pickup]').change(function(){
var value = $(this).val();
var el = $(this);
console.log(value);
$.ajax({
type : "POST",
cache : false,
url : "a.php?pickup",
data : {'X': value},
success: function(data) {
$("*[data-pick='" + el.attr("data-pickup") + "']").html("HELLO");
}
});
$("*[data-pick='" + el.attr("data-pickup") + "']").html("HELLO 2");
$("*[data-pick='" + el.attr("data-pickup") + "']").show();
})
Try this:
$('*[data-pickup]').change(function() {
var self = this;
var value = $(self).val();
console.log(value);
$.ajax({
type : "POST",
cache : false,
url : "a.php?pickup",
data : {'X': value},
success: function(data) {
$("*[data-pick='" + $(self).attr("data-pickup") + "']").html("HELLO");
}
});
$("*[data-pick='" + $(self).attr("data-pickup") + "']").html("HELLO 2");
$("*[data-pick='" + $(self).attr("data-pickup") + "']").show();
})
this inside the success function is not the same this as elsewhere in the change handler.
Here's a solution :
$('*[data-pickup]').change(function(){
var value = $(this).val();
var $el = $("*[data-pick='" + $(this).attr("data-pickup") + "']");//here keep a reference to the element(s) of interest.
console.log(value);
$.ajax({
type: "POST",
cache: false,
url: "a.php?pickup",
data: {'X': value},
success: function(data) {
$el.html("HELLO");//$el is still available here, from the closure formed by the outer function
}
});
$el.show().html("HELLO 2");
});