jQuery/Ajax

...now browsing by category

 

What is this error, “Uncaught SyntaxError: Unexpected token o”?

Wednesday, June 5th, 2013

It seemed that from time to time, we ran into this error “Uncaught SyntaxError: Unexpected token o“. Without more specific info, sometimes this can be very frustrating.

As matter of fact, this error was simply a result of sloppy coding in creating a JSON string that was not parsed correctly. Tracked down to the piece of code where error was thrown – it occurred where JSON.Parse was called. If the string s passed into the JSON.Parse(s)  is not properly formatted JSON string, the above error is thrown. In the sample code snipe below, r is a json string returned from a AJAX call from C# code; if I called JSON.parse(r), I would get the “Uncaught SyntaxError: Unexpected token o” error; and if r is not properly formatted, I also got the same error. Correct way to parse the returned json string is to call JSON.parse(r.d), instead of JSON.parse(r). I also tried to call JSON.parse(r.responseText), as it worked with the the xhr returned in the error function, but I got a different error, “Uncaught SyntaxError: Unexpected token u“, very interesting. Only r.d worked! Who came up with such super terse object name?!!

 

function fetchEmployer(code) {

        var account = null;
        var url = "<%=AjaxPath%>/GetEmployer";
        var json = JSON.stringify({EmployerCode: code});

        $.ajax({
            type: "POST",
            url: url,
            data: json,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function (r) {
                account= JSON.parse(r.d); //the error will be thrown if you just parse r instead of r.d
                //alert(r.d);

            },
            error: function (xhr, ajaxOptions, thrownError) {
                   if (xhr != null) {

                    var err = JSON.parse(xhr.responseText); //you can throw a code-behinde Exception and it will automatically                                                 //render to a valid JSON string when we rerieve the responseText
                    alert("ErrorMessage: " + err.Message + " StackTrace: " + err.StackTrace);

                }
            }
        });

        return account;

    }

One glitch to watch for while migrating jQuery lib from 1.3.2 to 1.7.1

Friday, September 14th, 2012

A recent deployment of my production website involved upgrading jquery library from jquery-1.3.2.min.js to jquery-1.7.1.min.js. Everything seemed to be fine except one place that was out of place – a customized div message box that initially displayed correctly next to mouse pointer now moved to the upper left corner of the screen.

What happened was that somehow 1.7.1 no longer supports $().mousemove() without passing in a definitive element identifier in the $(). Before the upgrade (jquery1.3.2.min.js), I used this code to capture the mouse position:

 var mouseX; var mouseY; $().mousemove(function(e){ mouseX=e.pageX; mouseY=e.pageY; }); 

And the mouseX and mouseY would have legit values. But these values were lost when I upgraded to jquery.1.7.1.min.js, if I kept the same code.

As it turned out, I needed to put a definitive html element id, either an id for a div or a table, in the $(). The new code that works the same as before the upgrade now should look like this:

var mouseX;
var mouseY;
$("#divid1").mousemove(function(e)
{
mouseX=e.pageX;
mouseY=e.pageY;

});

Now my popup box would display correctly to where I have my mouse over some item with this code below:


function showHints(msgDivId, msg,visible)
{
//alert("mouse position: " + mouseX + "," + mouseY);
var ch=$("#" + msgDivId);
ch.html(msg);
ch.addClass('hoverPopup');
ch.css({
left:mouseX+10,
top:mouseY-10
});
if (visible && msg.length>0)
ch.show();
else
ch.hide();

}

Inject custom message to warn user from closing browser window

Tuesday, June 26th, 2012

In a recent project, I needed to inject a custom message to warn user not to simply close a browser window; they might be doing some online course work and have not sent their course data back to server, and accidentally close down the browser. We didn’t want that to happen. At the beginning, I attempted the window.unload() event, and placed custom message there; but that, strangely, only works in IE7, but not in IE8,9, or recent versions of Chrome.

Naturally, I resolved to jQuery and found that this posting here at http://www.mkyong.com/jquery/how-to-stop-a-page-from-exit-or-unload-with-jquery/ was most useful. The author of this posting gave a good example and even embedded a demo. The thing I wanted to stress is that you must place the javascript code that handles the “beforeunload” event inside the body tag. At first, I placed in in <head> section and the event handler did not fire.

For jQuary library, I used direct reference from Google hosted solution, instead of referencing to local resource. Click hereto see what it looks like with different browsers and view the source. Try to enter a custom message to the text box on the lower part of the page, then try to close your browser. You will see the message you type in the box get added to the browser’s warning message while you try to close the page. For FireFox, it behaves quite differently – the custom message never got displayed and the default message differs from IE and Chorme, as shown in the image.

Return JSON data synchronously using jQuery.ajax()

Friday, September 10th, 2010

Normally, I would have used .getJSON(remotePageUrl,data,function(json){

//process JSON data here, for example

//if (json.length>0)

{

alert(json[0].Name);

}

});

 

to get a JSON object returned from the remotePageUrl that processes my request asynchronously and send back a JSON format string like ‘{“Name”:”steve”,”ID”: “1234”}’

But today, I found out that the .getJSON() cannot be set to process data request synchronously. In order to send data to remotePageUrl and return result synchronously (reason for this was because I had a jQuery dialog to be populated with data returned from this call before the dialog was displayed; first I used $.getJSON(), the dialog showed up before the data was processed on server side and returned), I needed to use $.ajax(). Here is the ajax call that actually worked to serve my purpose well:

 

var dataUrl = “<%=root%>/ajax/AsyncEventDataHandler.aspx”;

var userid; var eventTypeId; var userEventDesc=”;

var responseText = $.ajax({

url: dataUrl,

type: ‘GET’,

dataType: ‘JSON’,

//dataType: ‘text’,

contentType: ‘application/json’,

data: “UserCalendarID=” + userCalendarID,

async: false,

success: function (response) {

 

 

var data=$.parseJSON(response);

userid = data.UserID;

eventTypeId = data.EventTypeID;

userEventDesc = data.UserEventDesc;

 

 

},

 

error: function (msg) { alert(“error: ” + msg); }

 

}).responseText;

Here the response inside the function() is the same as $.ajax(….).responseText, and it should have a proper JSON string format or the jQuery.parseJSON() function will fail. The correct format example: ‘{“UserID”:”1211″,”EventTypeID”:”1″,”UserEventDesc”:”meeting”}’. I tried to put single quote around the field name and it did not go through $.parseJSON(). For example, this will not be parsed: “{‘UserID': ‘1211’,’EventTypeID':’1′,’UserEventDesc':’meeting’}”.

For that I attributed to this article at jQuery api site at: http://api.jquery.com/jQuery.parseJSON/. Otherwise, I would probably wasted more time in figuring out why the parsing was failing.

 

Using Google-hosted jQuery library

Monday, August 9th, 2010

Nice thing about using Google hosted jQuery is that I could call jQuery lib from anywhere and take advantage of versioning  and compression maintenance work done by Google. According to some source, the better caching provided by Google actually speed up the loading of the javascripts.

For example, below is a dialog box that uses jQuery UI hosted at Google. Click on the link to see it in action.

Show Dialog

Source code:

<link href=”http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css” rel=”stylesheet” type=”text/css” />
<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js”></script>
<script src=”http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js”></script>
<script type=”text/javascript”>
function showDialog() {

$(“#dialog”).dialog({autoOpen:false, modal:true,buttons: {OK:function(){$(this).dialog(‘close’); }}});

$(“#dialog”).dialog(‘open’);

}

</script>

<div id=”dialog” title=”hello dialog”></div>