JSON parseerror when % is in data content - json

I need to fix problem on site, and i can't figure out how. I have function which dynamically download articles, but when it contain % sign it throws parseerror. Can anyone help me to change this function to work with % sign and explain me that JSON behavior?
$('.funfan_more').click(function(){
if((offset*fun)+fun>=fun_count && (offset*fan)+fan>=fan_count){
$('.load_more').html('').css('height','30px').css('background','none');
}
ajaxLoader.show();
if(!loading) {
loading = true;
$.ajax('<?php echo URL::site('load_posts'); ?>',{
async: false,
type: 'GET',
data: {
offset: offset
},
dataType: 'json',
cache: false,
error: function( jqXHR, textStatus, errorThrown ) {
alert('Ups, some we have some' + textStatus + ' error here.');
},
success: function( data, textStatus, jqXHR ) {
$('.ff_left').append(data.a);
$('.ff_right').append(data.b);
offset++;
setTimeout(function(){
Cufon.refresh();
loading = false;
ajaxLoader.hide();
}, 1000);
}
});
}
return false;
});

I found the solution. Script wrongly preapared feed for site. It was a Kohana object pushed to string witch sprintf function, which was giving error if % was in website feed. Changing sprintf for normal casting to String type helped.

Related

Partial View loading using javascript : Possible XSS by HP FORTIFY

I have a js function , which Fortify identified as XSS vulnerable as below. Can you suggest any solution for this since the method is intensively used in my app.
I am here trying to call a partialview in ajax and the result html am appending to a specified dom div
My function look like the below
function loadPartialViewToDiv(div, obj, api) {
try {
const myUrl = new URL(window.location.origin + api); // always local URL only
$.ajax({
url: myUrl ,
data: obj,
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
if (data != undefined && data != null) {
$('#' + div).html(data);
}
}
});
} catch (e) {
('#' + div).html('Error');
}
}
The dynamic DOM element id was the issue ($('#' + div).html(data); ), we fixed it using two methods
giving a static id. $('#abcd').html(data);
OR
change as $('#' + div).text($(data));

Not able to get external API data through JQuery

I am trying to get external REST API data through JQuery, but it returs undefined. But when I use my local REST API url, it works. Can anybody explain whats is the problem. Any code sample will be appreciated.
This how i am accessing external Rest API via JQuery.
function GetCompanyName(id) {
jQuery.support.cors = true;
$.ajax({
url: 'http://novacompanysvc.azurewebsites.net/api/companies' + '/' + id,
type: 'GET',
dataType: 'jsonp',
success: function (data) {
WriteResponse(data);
},
error: function (x, y, z) {
alert("company" + x + '\n' + y + '\n' + z);
}
});
}
result is XML so you need to set dataType: "text/xml" and then parse it:
success: function (data) {
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(data,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(data);
}
I tried to test this but I got: is not allowed by Access-Control-Allow-Origin that is same-origin restriction so make sure you have access to this API or you will have to do it on the server using CURL in PHP for example.
Your are getting id variable in the function you showed in your question, but you are no using it,
if you want to send it add:
,data:{ id:id }
Request should look something like this:
function GetCompanyName(id) {
jQuery.support.cors = true;
$.ajax({
url: 'http://novacompanysvc.azurewebsites.net/api/companies',
type: 'GET',
data:{ id:id },
dataType: "text/xml",
success: function (data) {
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(data,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(data);
}
WriteResponse(data);
},
error: function (x, y, z) {
alert('error');
}
});
}

How to read the JSON file using jQuery in ASP.NET?

I have tried this alot but always I am getting the failure problem .Can any one guide how can we read the json file using jQuery?I have a json file in my project as given in this image
i have written the code as given below
$(document).ready(function () {
$('#btnLoad').click(function () {
$.ajax({
url: "example.json",
dataType: "text/json",
type: "GET",
contentType: "application/json;charset=utf-8",
success: function (msg) {
AjaxSucceeded(msg);
},
error: AjaxFailed
});
});
});
function AjaxSucceeded(result) {
alert(result.d);
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
But It is always AjaxFailed is firing.
dataType should be 'JSON'
There are only 4 accepted values for dataType, which you can see here:
http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests
Also, your error function takes 3 parameters:
errorFn(jqXHR, textStatus, errorThrown) {
// your code
}
Additionally, this:
success: function (msg) {
AjaxSucceeded(msg);
},
Can be this:
success: AjaxSucceeded
Your success function also takes 3 parameters:
success(data, textStatus, jqXHR)
For reference on $.ajax parameters: http://api.jquery.com/jQuery.ajax/

Success function in .ajax() doesn't execute

When I debug using Firebug I see the control jumping to error section after hitting success. I am unable to find out what is going wrong. Can some body please point out what is wrong with this code.
$(function(){
$.ajax({
type: "POST",
url: "service/MyService.asmx/GetAsgInfo",
data: "{id: " + parseInt($('#AsgId').val()) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// var s = eval('(' + msg.d + ')');
alert(msg.d[0].SubmittedCount);
},
error: function (e) {
alert("error : " + e);
}
});
});
POST :
{id: 5301}
RESPONSE :
{"d":[{"__type":"Proxies.AFARServiceRef.AssignmentInfo","ExtensionData":
{},"AssignDate":"\/Date(1319526000000)\/","AssignFileName":null,"ClaimId":"MH001025","ClaimantName":"Deborah C Plaid","FirstContactDate":"\/Date(1319526000000)\/","FirstContactTime":
{"Ticks":420000000000,"Days":0,"Hours":11,"Milliseconds":0,"Minutes":40,"Seconds":0,"TotalDays":
0.4861111111111111,"TotalHours":11.666666666666666,"TotalMilliseconds":42000000,"TotalMinutes":700,"TotalSeconds":42000},"Id":5301,"InspectionDate":"\/Date(1319612400000)\/","StatusId":1,
"SubmittedCount":4,"UploadedCount":14}]}
Instead of using the success and error functions, try using complete:
complete: function(jqXHR, textStatus) {
alert(textStatus);
}
I had a similar problem with handling json, and it turns out I wasn't setting the content-type properly on the server side. Even valid json sometimes causes weird errors when it is in a response labeled as "text/plain" or even "text/json". Make sure your content type is right.

JSON returned data it is in {d:"data"} format

I am trying to get JQueryUI's Autocomplete code working with an ASMX web service. I am getting close, but hit yet another wall yesterday. The JSON data is being returned in {d:"data"} format (see http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx). My data now looks like:
d: "[{"DOTNumber":"001061010","JobTitle":"Project Architect"},{"DOTNumber":"003061005","JobTitle":"Principal Electrical Engineer"}]"
My code is:
$(function() {
function log(message) {
$("<div/").text(message).prependTo("#log");
$("#log").attr("scrollTop", 0);
}
});
$("#dotmatch").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "/AutoSuggestJSTest/AutoSuggest.asmx/DOTFind",
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ prefixText: request.term, count: 20 }),
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
success: function(data) {
var safe = data;
response($.map(safe.d, function(item) {
return {
label: item.JobTitle + "(" + item.DOTNumber + ")",
value: item.DOTNumber
}
}));
}
});
},
minLength: 2,
select: function(event, ui) {
log(ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value);
$get("DOTNumber").value = ui.item.value;
},
});
The problem lies in the success function.
What is the right syntax to get past the "d" issue?
Your data should look like this:
{"d":[{"DOTNumber":"001061010","JobTitle":"Project Architect"},"DOTNumber":"003061005","JobTitle":"Principal Electrical Engineer"}]}
It appears you are missing quotes around your "d" and you have extra quotes around your array.
Don't eval() your data - this opens you up to more security issues than the d: prevented.. You should have access to JSON.parse() or if not jQuery.parseJSON() (which wraps JSON.parse() if available... depends on your target platform(s)).
This has been an incredibly difficult process, but I finally got it working. There were a number of hurdles:
1) My JSON return string was getting wrapped in an XML blanket, so it would not parse
2) Solving this problem required the contentType: 'application/json' line
3) With that content type, a POST was required. GET would not work
4) POST required putting the data together using the JSON.stringify. I am still not sure about this one, but I found some code somewhere that did it.
5) Data coming back from the POST was prefixed with a "d " (see: http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
6) getting access to the data itself required the "eval(data.d)" line.
$("#dotmatch").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "/AutoSuggestJSTest/AutoSuggest.asmx/DOTFind",
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ prefixText: request.term, count: 20 }),
success: function(data) {
var output = eval(data.d);
response($.map(output, function(item) {
return {
label: item.JobTitle + "(" + item.DOTNumber + ")",
value: item.DOTNumber
}
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
If I ever have this much trouble writing a few lines of code again, I am going to take a very large guage shotgun to my computer!
Bob Jones
If you use a WCF JSON service with the webHttpBehavior (instead of enableWebScriptBehavior), it will not emit the "d"