elusive jQuery JSON Parser error - django

I have a an ajax call returning JSON to a loop to populate form fields. The raw data looks fine, but it never makes it though the loop and into the form, and an "Uncaught SyntaxError: Unexpected token :" error is thrown at line 1 of the document.
This is the ajax function:
$(function() {
$('#id_license' ).blur( function() {
q = $( '#id_license' ).val();
$.ajax({
datatype: 'json',
type: "POST",
data: 'lic='+q,
url: "/usr/xhr_license_search/?xhr",
success: function(data)
{ $.each(data, function(field, value){
$("#id_"+field).val(value);
});
console.log(data);
}
});
});
});
This is the raw JSON returned:
(manually anonymized)
{"First_Name":"Jon","Last_Name":"Doe","address":"2 A st.","city":"anthtown","grade":"T5","licNum":"08933","state":"TA","user":1099,"zipCode":09117}
I'm using json.dump() in Django to format the response.
Thank you in advance for your incites.

I've had this problem quite a few times before, it's something to do with the return dataType. By using $.get or $.post instead of $.ajax I've been able to solve the problem, so for you:
$.post('/usr/xhr_license_search/?xhr', 'lic='+q, function(data){
$.each(data, function(field, value){
$("#id_"+field).val(value);
});
}, 'json');
Doing that should give you no error.

I'm pretty sure JSON will be confused by the leading 0 in the zipCode; that shouldn't parse as a number, according to json.org . Are you sure you didn't intend that to be a string?

Try adding a pair of parentheses around the raw json, which makes it like
({"First_Name":"Jon","Last_Name":"Doe","address":"2 A st.","city":"anthtown","grade":"T5","licNum":"08933","state":"TA","user":1099,"zipCode":09117})

Related

Lucee ColdFusion.Ajax.submitForm

I'm converting a site from ColdFusion to Lucee (for the first time). In ColdFusion, after using the cfajaximport tag, I can run JS code similar to this:
ColdFusion.Ajax.submitForm('runMe', 'runCode.cfm', callback_testMe, errorHandler_testMe);
I seem to be unable to run this in Lucee. I'm looking for some kind of Lucee alternative, but can't seem to find anything.
Basically, I'm wanting to submit form data, run some server side stuff, then return the results without refreshing the page.
Any help would be greatly appreciated.
Lucee does not have CF UI tags, you're going to have to do this with jQuery AJAX or similar.
var formID = "runMe"; // formId Param
$("#"+formID).on("submit", function (e) {
e.preventDefault(); // Prevent page load
$.ajax({
type: "POST", // httpMethod Param
url: "runCode.cfm", // URL Param
data: $(this).serialize(),
success: function (data) {
console.log(data); // callbackhandler
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError); // errorHandler
}
});
})
This should do exactly the same thing and I even pointed out the similar params from ColdFusion.Ajax.submitForm

How to get the Rendering Datasource after an AJAX postback

I have the ajax code below:
$.ajax({
url: 'api/sitecore/SmartAds/GetSmartAddsItem',
type: "GET",
dataType: "json",
success: function (result) {
alert(result);
}
});
The problem is the Sitecore.Context.Item.ContextRendering is null in the ajax call.
Question: How do I get the rendering datasource during AJAX call?
I found the below code here, but I am having trouble getting it to work:
public class FormModelBinderProvider : Dictionary, IModelBinderProvider
{
public IModelBinder GetBinder(Type modelType)
{
var binders = from binder in this
where binder.Key.IsAssignableFrom(modelType)
select binder.Value;
return binders.FirstOrDefault();
}
}
I am getting an error that says that Dictionary requires 2 type arguments.
Any help is appreciated.
The first issue with your code is that the AJAX request you are making is a 'GET' request rather than a post, so it won't be passing in the hidden field value for the datasource item. To clarify, the article covers situations where a form is posted back, not AJAX GET requests.

ajax - jquery - xml - webservice

I am trying to access the method GetWeatherByPlaceName from the service http://www.webservicex.net/weatherforecast.asmx. In my "data" attribute included city name as "newyork" but it is not showing any result. Please let me know if it is correct way of representing method name in the url.
$(document).ready(function(){
$.ajax({
type:"POST",
url:"www.webservicex.net/weatherforecast.asmx/GetWeatherByPlaceName",
data:"newyork",
contentType:"text/xml; charset=utf-8",
dataType:"xml",
success:function(msg){
$('span').html(msg);
}
});
});
I'm not sure if it will help, but the service should either receive an url encoded parameters string or a soap formated message.
So, i think you should replace your call by
$(document).ready(function(){
$.ajax({
type:"POST",
url:"www.webservicex.net/weatherforecast.asmx/GetWeatherByPlaceName",
data:"PlaceName=newyork",
dataType:"xml",
success:function(msg){
$('span').html(msg);
}
});
});

Display JSON response text from ajax in jQuery Template

I need to pass the response from ajax call to a jquery template.The response json is not malformed.I have checked this by using alert statements in the ajax fn.When the response is passed to the template,it does not get recognized.For example,when I use ${field1} in template,nothing gets displayed in the browser.No error messages are displayed at the browser.Can someone help me fix this issue?
Json response from server:
{
"field1": 23432434,
"field2": "sometext",
}
Ajax fn:
function getinfo(uri)
{
jQuery.ajax({
url: 'http://{{request.META.SERVER_NAME}}'+uri,
success: function(info) {
return info;
},
async: false,
dataType: 'jsonp'
});
}
Template:
<script id="infoTemplate" type="text/x-jQuery-tmpl">
<div>${field1}</div>
</script>
Code to Bind JSON to template:
<script id="Template1" type="text/x-jQuery-tmpl">
{{tmpl(getinfo(uri)) "#infoTemplate"}}
</script>
Note: I can't use the following method to bind JSON with template.That's a long story.
function getinfo(uri)
{
$.getJSON('http://{{request.META.SERVER_NAME}}'+uri, function(data) {
$("#infoTemplate").tmpl(data).appendTo("#somedivid");
});
}
That's not how callbacks work. You're returning info to the callback function, and not to getinfo.
You either have to do something like you proposed after, or keep the result from the ajax call in a global var and call the tmpl function after while, to be sure that you have already got the answer from the ajax call. The first way is the way to go.

Mobile Application Using Sencha Touch - JSON Request Generates Syntax Error

I started playing a bit with Sencha Touch.
So I've built a really simple application based on one of the examples just to see how it goes.
Basically it creates a JSON Request which executes a Last.FM web service to get music events near the user's location.
Here's the JSON code:
var makeJSONPRequest = function() {
Ext.util.JSONP.request({
url: 'http://ws.audioscrobbler.com/2.0/',
params: {
method: 'geo.getEvents',
location: 'São+Paulo+-+SP',
format: 'json',
callback: 'callback',
api_key: 'b25b959554ed76058ac220b7b2e0a026'
},
callback: function(result) {
var events = result.data.events;
if (events) {
var html = tpl.applyTemplate(events);
Ext.getCmp('content').update(html);
}
else {
alert('There was an error retrieving the events.');
}
Ext.getCmp('status').setTitle('Events in Sao Paulo, SP');
}
})
};
But every time I try to run it, I get the following exception:
Uncaught SyntaxError: Unexpected token :
Anyone has a clue?
A couple of things. First of all the "Uncaught SyntaxError: Unexpected token :" means the browser javascript engine is complaining about a colon ":" that has been put in the wrong place.
The problem will most likely be in the returned JSON. Since whatever the server returns will be run though the eval("{JSON HTTP RESULT}") function in javascript, the most likely thing is that your problem is in there somewhere.
I've put your code on a little sencha test harness and found a couple of problems with it.
First: My browser was not too happy with the "squiggly ã" in location: 'São+Paulo+-+SP', so I had to change this to location: 'Sao+Paulo,+Brazil', which worked and returned the correct results from the audioscribbler API.
Second: I notice you added a callback: 'callback', line to your request parameters, which changes the nature of the HTTP result and returns the JSON as follows:
callback({ // a function call "callback(" gets added here
"events":{
"event":[
{
"id":"1713341",
"title":"Skank",
"artists":{
"artist":"Skank",
"headliner":"Skank"
},
// blah blah more stuff
"#attr":{
"location":"Sao Paulo, Brazil",
"page":"1",
"totalpages":"1",
"total":"2"
}
}
}) // the object gets wrapped with extra parenthesis here
Instead of doing that I think you should be using the callbackKey: 'callback' that comes with the example in http://dev.sencha.com/deploy/touch/examples/ajax/index.js.
Something like this for example:
Ext.util.JSONP.request({
url: 'http://ws.audioscrobbler.com/2.0/',
params: {
method: 'geo.getEvents',
location: 'Sao+Paulo,+Brazil',
format: 'json',
api_key: 'b25b959554ed76058ac220b7b2e0a026'
},
callbackKey: 'callback',
callback: function(result) {
// Output result to console (Firebug/Chrome/Safari)
console.log(result);
// Handle error logic
if (result.error) {
alert(result.error)
return;
}
// Continue your code
var events = result.data.events;
// ...
}
});
That worked for me so hopefully it'll work for you too. Cherio.