jQuery JSON error: Syntax error, unrecognized expression - javascript

This is my first experience with using JSON so I'm probably doing something really dumb.
I built an app to scrape pages and return a JSON object.
My JSON returned looks like this (using Facebook as an example):
{"urlTitle":"Welcome to Facebook \u2014 Log in, sign up or learn more","urlDescription":" Facebook is a social utility that connects people with friends and others who work, study and live around them. People use Facebook to keep up with friends, upload an unlimited number of photos, post links and videos, and learn more about the people they meet."}
However, in FireBug I get the above error (also see screenshot).
My jQuery code gets the JSON via AJAX and looks simple right now:
$("#submitButton").on("click", function(){
$.ajax({
url: '/miscellaneous/scrape/scrape.cfm',
dataType: 'json',
data: {
strURL: $.param( $("#submitURL").attr("value") )
},
type: 'POST',
success: function(data) {
alert("yes!");
}
});
return false;
});
I never get my success message :( Just the error!
Am I doing something really obviously wrong here?
Thanks,
Michael.
EDIT
Here's my entire JSON as requested:
{"urlTitle":"Welcome to Facebook \u2014 Log in, sign up or learn more","urlImages":{"image_8":"http:\/\/static.ak.fbcdn.net\/rsrc.php\/v2\/yb\/r\/GsNJNwuI-UM.gif","image_6":"http:\/\/photos-g.ak.fbcdn.net\/photos-ak-snc7\/v85005\/226\/255889644513526\/app_104_255889644513526_1061222291.png","image_7":"http:\/\/secure-us.imrworldwide.com\/cgi-bin\/m?ci=ent156564&am=3&ep=1&at=view&rt=banner&st=image&ca=cmp7747&cr=crv72918&pc=plc220331&r=1346702536","image_4":"http:\/\/photos-a.ak.fbcdn.net\/photos-ak-snc7\/v85006\/156\/156324174503268\/app_104_156324174503268_1504955413.png","image_5":"http:\/\/photos-b.ak.fbcdn.net\/photos-ak-snc7\/v85005\/78\/344521295633922\/app_104_344521295633922_1943760717.png","image_3":"http:\/\/photos-c.ak.fbcdn.net\/photos-ak-snc7\/v85005\/14\/298987460188718\/app_104_298987460188718_170436975.png","image_2":"http:\/\/photos-g.ak.fbcdn.net\/photos-ak-snc7\/v85006\/196\/287530028007964\/app_104_287530028007964_853932327.png","image_1":"http:\/\/static.ak.fbcdn.net\/rsrc.php\/v2\/yY\/r\/2LiCtrj0cdC.png"},"urlDescription":" Facebook is a social utility that connects people with friends and others who work, study and live around them. People use Facebook to keep up with friends, upload an unlimited number of photos, post links and videos, and learn more about the people they meet."}

Hi Based on the comments on your question.. looks like you are looking for a way to avoid AJAX requests to do caching. For that you can try something like this..
$.ajax({
url: url,
data: inputs + '&ran=' + Math.rand(),
)};
or
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false
});
I hope this will help you.

Related

$.ajax anonymous function causing 500 error on Google App Engine

Frustratingly the GoogleAppLauncher can't replicate this and the error only occurs on production. Essentially I have a form submitting json to mailchimp. It is erroring at the javascript and I can't work out why. You can see the 500 error if you try to submit the form - https://v-sons.appspot.com/our-underwear/#subscribe
On the server looks to be a Call to undefined function add_theme_support() however the console tells a different story (I don't understand whether the two relate / not).
In my console, the jQuery error references:
xhr.send( ( s.hasContent && s.data ) || null );
However digging deeper it looks to be a problem with the $.ajax anonymous function of this code block that's being submitted:
jQuery.ajax({
url: action,
type: 'POST',
data: $stickyForm.serialize(),
success: function(data)
{
window.location.hash = 'nearly';
$('#modalOverlay').addClass('nearly').fadeIn();
$('#stickyEmail').val("");
$('#nickName').focus();
}
});
I've tried to cover as much as I can with this, because to be honest I'm not sure where the problem really lies. It'd be really great to get an answer / some help though because I've been bashing keys for hours trying to work this out. The main problem is this isn't a problem on my local server, and I don't know from what end to attack the problem.
//
Update: It has just occurred to me that this error might have been created by issuing the other fix I used on this other related question I asked the community - 500 Error when Migrating Wordpress to Google Cloud
See AJAX Mailchimp signup form integration which suggests adding dataType: 'json' and setting contentType.

Ajax Error: SyntaxError: Unexpected token < error

So I have searched the forum for similar questions unfortunately I have been unlucky to find an answer that suits my problem.
I am trying to make an ajax call in my jquery using the following code;
function submitForm(formData)
{
$.ajax({
type: 'POST',
url: 'addEvents.php',
data: formData,
dataType:'json',
cache:false,
timeout:7000,
success: function(data){
$('#addEventsForm #response').removeClass().addClass((data.error === true) ? 'error' : 'success').html(data.msg).fadeIn('fast');
if($('#addEventsForm #response').hasClass('success')){
setTimeout("$('#addEventsForm')",5000);
}
},
error:function(XHR,textStatus,errorThrown)
{
$('#addEventsForm #response').removeClass().addClass('error').html('<p> There was an <strong>' + errorThrown +
'</strong> error due to <strong>'+ textStatus +'</strong> condition.</p>').fadeIn('fast');
console.log(arguments);
//alert(XMLHttpRequest.responseText);
},
complete:function(XHR,status)
{
$('#addEventsForm')[0].reset();
}
});
}
But I am getting a sysntax error. I have tried doing this to see what errors I get in chrome
console.log(arguments);
but the responseText in the [Object, "parsererror" , SyntaxError] node seems to display the entire html of the page that contains the form where I am inserting the record.
I am still getting my feet wet in ajax so I am not yet a pro in absolutely understanding the error messages and what they mean.
Is the above js/jQuery code located on the addEvents.php page -- that is, on same page that you are posting the AJAX to? (In other words, are both the form/ajax and the AJAX destination on the same physical PHP page?)
If so, you will get exactly what you describe: the entire HTML of the page spat back at you.
AJAX, by design, must post to a different physical page on the server. That's just how it works.
Also, FWIW, note that dataType: 'json', refers to the data being returned, not the data being sent. Perhaps you already know this, but it is a common misunderstanding so is worth mentioning.
Edit:
As Felix points out, this answer is not technically perfect. It is possible to post AJAX code to the same page, but you must specifically allow for that. Perhaps FK or another could edit this post to add an example of what that additional code would look like?

Creating file from query with javascript

I'm working on a Project for pedestrian navigation. For blind people, I'd like to tell them if there are any objects in the same street as they are, so they can orientate themselves.
I have a Json-file full with coordinates of trees from a city. I query geonames (with $.ajax) to get the nearby streets of the trees and want to store this information in a file. A json-file would be great, but I have no idea how to do this.
Can anyone tell me how I can create such a file? It has to be made only once.
Or do you know an alternative to store the data in a better way?
What I tried so far in js:
function writeToJson(streetNames){
$.ajax({
type: 'POST',
url: "scripts/treeStreets.php",
data: streetNames,
dataType: 'json',
error : function(parameters){
console.log("error");
console.log(parameters);
},
success: function(){
console.log("success");
}
});
}
And the php-script:
$streetNames = $_POST[streetNames];
file_put_contents('/live%20access/data/treeText.txt', $streetNames);
But this gives me an error.
You need to write a service in a language like PHP, Ruby, Python or Java. JavaScript has no ability to create a file on either the client or server so you'll need a service that the AJAX operation can call which will write the data to disk.

How can I add an event to a Google calendar using v3 API and JQuery?

I am attempting to teach myself some JQuery/REST/Google API by putting together a simple page that does the following:
Authenticates with Google
Validates a token
Gets a list of Google Calendars for the user
List events for a selected calendar
Add an event for a selected calendar
I have #1 through #4 working (although no doubt in an ugly manner), and am getting tripped up on #5. Here's the JQuery ajax call:
var url = 'https://www.googleapis.com/calendar/v3/calendars/[MY_CALENDAR_ID]/events?sendNotifications=false&access_token=[GOOGLE_API_TOKEN]';
var data = { end: { dateTime: "2012-07-22T11:30:00-07:00" }
, start: { dateTime: "2012-07-22T11:00:00-07:00" }
, summary: "New Calendar Event from API"
};
var ajax = $.ajax({ url: url
, data: data
, type: 'POST'
}).done(addEventDone)
.fail(function (jqHXR, textStatus) {
console.log("addEvent(): ajax failed = " + jqHXR.responseText);
console.log(jqHXR);
});
The results are a global parseError: "This API does not support parsing form-encoded input.". The first four steps are all using GET ajax calls, so I'm not sure if that is what is tripping me up.
Here's the API in question: https://developers.google.com/google-apps/calendar/v3/reference/events/insert
I think I may be doing things the long and hard way, and my new approach is to tackle this using the javascript API instead of going straight at it with manual JQuery and REST. This is the approach I am attempting going forward http://code.google.com/p/google-api-javascript-client/wiki/Samples#Calendar_API, although I would still love to use this as a learning opportunity if there is something simple I am screwing up in the code above.
Thanks for any help, insights, pointers, etc. I will post updates if I make any progress using the javascript API.
Interestingly, I just answered a similar question here. Your intuition to use Google's JS client library is a good one. It's going to handle OAuth 2 for you, which is a requirement if you're going to do any manipulation of the Calendar data.
My other answer has both a link to a blog post that I authored (which demonstrates configuration of the client and user authorization), as well as an example of inserting a Calendar event.
you need to set contentType: "application/json", to do JSON.stringify for your data and method : 'POST'
var ajax = $.ajax({
url: url,
contentType: "application/json",
data: JSON.stringify(data),
method : 'POST',
});

Handling Twitter API Errors with jQuery $.getJSON

$.getJSON(twitter_url, function(data){
loadtwit(data);
});
I am querying the twitter url via $.getJSON, for instance:
http://twitter.com/statuses/friends/stevejobs.json?callback=?
Sometimes the browser response is UnAuthorized if the tweets are protected. How can I handle that response to avoid triggering a login form.
success: loadtwit(data);
else: die silently
You can use $.ajax and provide an error handler.
$.ajax({
url: twitter_url,
dataType: 'json',
success: function(data) {
loadtwit(data);
},
error: function(xhr, testStatus, error) {
// handle error
}
});
I think I found something close to a workaround, if not an answer finally.
In my case I wanted to show a user's location, name, photo and some tweets based on their username which I knew, so I was trying to use this:
http://api.twitter.com/1/statuses/user_timeline.json?&screen_name=stevejobs&count=20&callback=?
Which trigger the popup that looks like a phishing scam when querying users with protected tweets.
So you can query a search for tweets based on a user like this:
http://search.twitter.com/search.json?q=from:stevejobs&callback=?
And you can also query a user like this:
http://api.twitter.com/1/users/show/stevejobs.json?&callback=?
The first query will get back tweets and won't ask for passwords because the protected users do not appear in search. Works, but doesn't return location and meta data for the user.
The 2nd query doesn't return tweets, but does return a boolean value for protected.
So if you put it together, you can get a complete search.
I hope someone finds this useful. I've been googling and reading the API all day. After I write the function, I'll come back here and post it.

Categories