Parsing BBCode on AJAX success - javascript

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

Related

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

jquery ajax - form serialization issue on query parameter

I am using jquery ajax to post a html form . This works fine with Chrome and not with Firefox . When I analyze the issue ,the query parameter "Accept=Apply" is not shown in Firefox dev tool (Params tab)but I could see the proper string is in debug statement which i have added. Can anyone help on this?
Jquery :
function postSettings() {
var frm_data = $("#MyForm").serialize() + "&Accept=Apply";
console.log("frm_data >>"+frm_data);
var myobject = {"Accept":"Apply"};
var testdata =$("#MyForm").serialize() + '&' + $.param(myobject);
console.log("testdata >>"+testdata);
$.ajax(
{
type: "POST",
url: "https://10.20.12.30/Update.cgi",
data: frm_data,
success: function (successData) {
console.log("successData >>"+successData);
} else {
console.log("errorData1 >>"+successData);
}
},
error: function (errorData) {
console.log("errorData2 >>"+errorData);
}
});
}
Thanks
Best way to do this would be adding it as a hidden field
<input type="hidden" id="Accept" name="Accept" value="apply"/>
This way we can aviod passing it as query string and unexpected issues.

Call ajax in file .js

i have a problem with this :
function inicioConsultar(){
$(function(){
$('#serviciosU').change(function(){
if ($('#serviciosU').val()!= "-1")
{
$.ajax({
url: "#Url.Action("ObtenerCapas")",
data: {urlServicioUsuario:$("#serviciosU :selected").val()},
dataType: "json",
type: "POST",
error: function() {
alert("An error occurred.");
},
success: function(data) {
var items = "";
$.each(data, function(i, item) {
items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
});
$("#capas").html(items);
}
});
}
})
});
I put in my Index.cshtml "inicioConsultar()" and there is a problem with ajax, because if i delete the call ajax everything it is ok.
In loyout, i load jquery and the index it is inside layout.
Sorry for my english.
This is a syntax error:
"#Url.Action("ObtenerCapas")",
That isn't how strings work in JavaScript. You need to escape the inner double quotes, as they're terminating the string.
Try
"#Url.Action(\"ObtenerCapas\")",
However, that wont' solve your problem, unless #Url.Action(...) is a real URL on your server, or your AJAX set has some kind of ability to evaluate that string as a function call.

Get Javascript to work? $.ajax not working right?

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.

Categories