Ok this is my JavaScript
<script type="text/javascript" language="JavaScript">
function manageCart(task,item) {
var url = 'managecart.php';
var params = 'task=' + task + '&item=' + item;
var ajax = new Ajax.Updater(
{success: ''},
url,
{method: 'get', parameters: params, onFailure: reportError});
}
function reportError(request) {
$F('cartResult') = "An error occurred";
}
And this is HTML
<p>
Add to cart
</p>
This script doesn't work in Firefox, I've ran a few Firefox JS debuggers but they displayed no errors. I'm not so good in JavaScript so please help me if you can :)
This script actually uses Prototype library if it will make things clearer.
For this type of Ajax call do not use Ajax.Updater as that is designed to update a specific element with the contents of the ajax response. I believe that you want to just make a simple single ajax call so using Ajax.Request would be what you want to use.
Original Code using Ajax.Updater
var url = 'managecart.php';
var params = 'task=' + task + '&item=' + item;
var ajax = new Ajax.Updater(
{success: ''},
url,
{method: 'get', parameters: params, onFailure: reportError});
Code using Ajax.Request
var url = 'managecart.php';
var params = 'task=' + task + '&item=' + item;
var ajax = new Ajax.Request(url,
{
method: 'get',
parameters: params,
onFailure: reportError,
onSuccess: function(){
console.log('It Worked');
}
});
I put a success handler in this call just to confirm that it worked for you - and it should output to your console. You can remove it or comment the console.log() when you are satisfied it works
I've spent more time in FireBug and found the error.
Timestamp: 03.04.2013 10:36:38
Error: ReferenceError: invalid assignment left-hand side
Source File: http://www.example.com/index.php
Line: 413, Column: 18
Source Code:
('cartResult') = "An error occurred";
Firefox desperately wanted for the statement to look like this:
('cartResult') == "An error occurred";
Related
I am new to javascript, JQuery and Google API, so the answer to this question may be a very simple thing that I am overlooking. I've checked all available Google Calendar Freebusy Questions on this site, but I can't manage to make their answers fit my code in any way.
I am trying to write a script for an html page that checks a public calendar's freebusy query. Google says that the HTTP Request should be
POST https://www.googleapis.com/calendar/v3/freeBusy
with a request body of
{
"timeMin": datetime,
"timeMax": datetime,
"timeZone": string,
"groupExpansionMax": integer,
"calendarExpansionMax": integer,
"items": [
{
"id": string
}
]
}
My current html page includes the latest jquery library, and the script I'm writing. Calling the script on the page results in a Failed to load resource: the server responded with a status of 400 (Bad Request) error. A further dig into the error information returns a parse error with "This API does not support parsing form-encoded input."
My script looks like this:
(function ($) {
$.GoogleCalendarFreebusy = function (options) {
var defaults = {
apiKey: '[projectkey]',
getID: '[id]#group.calendar.google.com',
element: '#div'
};
options = $.extend(defaults, options);
$.post('https://www.googleapis.com/calendar/v3/freeBusy?key=' + options.apiKey,
{"items":[{"id": getID }],"timeMin":"2015-04-10T14:15:00.000Z","timeMax":"2015-04-20T23:30:00.000Z"}, "null", "json")
.done(function(data) {
loaded(data);
});
function loaded(data) {
var status = data.calendars[getID].busy;
console.log(status);
if(status.length !== 0 ) {
for(var i = 0; i < status.length; i++) {
var statusEntry = status[i];
var startTime = statusEntry.start;
var endTime = statusEntry.end;
}
var now = new Date().toISOString();
var element = options.element ;
var name = element.substr(1);
if (now > startTime && now < endTime){
$(options.element).append( 'Available!');
}
else {
$(options.element).append( 'Unavailable!');
}
} else {
$(options.element).append('Unavailable!');
}
}
};
})(jQuery);
My request is receiving the proper response in the Google Explorer "Try It", so I think it may be javascript error/json request I'm overlooking? Thanks in advance for your help and advice.
Google Calendar API Post requests need to have the content-type specified as JSON to avoid the above error. Processing the POST as an AJAX request with contentType specified solves this error.
$.ajax({
url: 'https://www.googleapis.com/calendar/v3/freeBusy?key=' + options.apiKey,
type: 'POST',
data: '{"items":[{"id": "[id]#group.calendar.google.com"}], "timeMin": "2015-04-10T14:15:00.000Z", "timeMax": "2015-04-20T23:30:00.000Z"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: 'null'
})
Thank you for the suggestions!
i'm trying to develop Firefox extension
problem :
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = response.json;
}
});
I want to use this request function to parse json to an array (List here) from php file.
The php my php file echo json form correctly, but I can't transform the data into javascript array to be able to use it in my addon.
if there is a better idea than using this function to do it please tell me :)
try this: MDN - JSON Object
JSON.parse and JSON.stringify
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = JSON.parse(response.json);
}
});
it's very important to use double quotes.
If you are having a problem with JSON.parse. Copy your array to scratchpad and then run JSON.stringify on it and then make sure your php file matches the strignified result.
if Addon-SDK doesnt have JSON then you gotta require the module if there is one. If there isn't one than require('chrome') and grab the component HERE
There's a bug in Noitidarts code.
why JSON.parse the request.json? If you want to parse do it on request.text
However no need to json.parse as the request module tries to parse and if successful retuns request.json
see here:
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=mozhacks&count=1",
onComplete: function (response) {
var tweet = response.json[0];
console.log("User: " + tweet.user.screen_name);
console.log("Tweet: " + tweet.text);
}
});
// Be a good consumer and check for rate limiting before doing more.
Request({
url: "http://api.twitter.com/1/account/rate_limit_status.json",
onComplete: function (response) {
if (response.json.remaining_hits) {
latestTweetRequest.get();
} else {
console.log("You have been rate limited!");
}
}
}).get();
so the likely problem is that your php is not outputting a json string that json.parse can read. make sure to use ". figure out what your php file should return by running json.stringify on a dummy object. ie:
var obj = {myarr:[1,8,9,7,89,0,'ji'],strr:'khhkjh',anothrtObj:{1:45,56:8}};
alert(JSON.stringify(obj)) //{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
so now in your php make sure your outputted text mateches this format
{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
if your php outputs something like below JSON.parse will fail on it so request.json will be null
{myarr:[1,8,9,7,89,0,"ji"],strr:"khhkjh",anothrtObj:{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,"ji"],'strr':"khhkjh",'anothrtObj':{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,'ji'],'strr':'khhkjh','anothrtObj':{'1':45,'56':8}}
I'm trying to fetch a custom JSON feed I have written with jQuery using the getJSON method. For an unknown reason the URL seems to be having cache_gen.php?location=PL4 stripped from the end and replaced with [object%20Object] resulting in a 404 error occurring.
Here's the jQuery I'm using:
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
console.log(api_location + '?location=' + user_location);
jQuery.getJSON({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
From the console log I can see the URL string is calculated correctly as: http://weatherapp.dev/cache_gen.php?location=PL4
However the second line in the console is: Failed to load resource: the server responded with a status of 404 (Not Found).
Can anyone point me in the right direction with this?
UPDATE 19/01/2013 23:15
Well, I've just converted so that is fits the docs perfectly using $.ajax. I've also added a fail event and logged all of the data that gets passed to it.
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
var url = api_location + '?location=' + user_location;
console.log(url);
jQuery.ajax({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log('textStatus: ' + textStatus );
console.log('errorThrown: ' + errorThrown );
console.log('jqXHR' + jqXHR);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
After this my console gives me the following information:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
I have ensured the headers for the JSON feed are current, and the feed is definitely serving valid JSON (it effectively caches a 3rd party service feed to save costs on the API).
The reason why you see this error:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
Is because your JSON is invalid. Even if a response comes back from the server correctly, if your dataType is 'json' and the returned response is not properly formatted JSON, jQuery will execute the error function parameter.
http://jsonlint.com is a really quick and easy way to verify the validity of your JSON string.
I was running into the same issue today. In my case I was assigning a JSON object to a variable named 'location' which is a reserved word in JavaScript under Windows and appearantly is a shorthand for windows.location! So the browser redirected to the current URL with [object%20Object] appended to it. Simple use a variable name other than 'location' if the same thing happens to you. Hope this helps someone.
Check out the actual function usage:
http://api.jquery.com/jQuery.getJSON/
You can't pass on object parameter into $.getJSON like with $.ajax, your code should look like this:
jQuery.getJSON('api_location + '?location=' + user_location)
.done(function() {
//success here
})
.fail(function() {
//fail here
});
To maybe make it a little clearer, $.getJSON is just a "wrapper function" that eventually calls $.ajax with {type:'get',dataType:'JSON'}. You can see this in the link I provided above.
I am getting different errors in FF, Chrome and IE, but it all boils down there is an error with the data in $.ajax. Following is the code. Please go easy if I made a dumb mistake. I have spent hours researching this and can't figure it out. Any help appreciated.
Edited to include the error messages
FF Error message: NS_ERROR_XPC_BAD_CONVERT_JS: Could not convert JavaScript argument
Chrome Error message:Uncaught TypeError: Illegal invocation
IE9 Error message: SCRIPT65535: Argument not optional
Here is the code
mc.mc_data.click_tracking = [];
var sequence = 0;
var send_it;
// the container click event will record even extraneous clicks. need to change it to extending the jquery on click handler
$('#container').on('click', function(event) {
logClicks(event);
if(!send_it){
sendIt()
}
sequence++;
});
function sendIt(){
var tracking = mc.mc_data.click_tracking;
var url = '/ajax/click_trackin';
console.log("clicks["+sequence+"] "+$.isArray(tracking));
$.each(tracking, function(i,v){
console.log(i + v.innerText + " - " + v.sequence);
});
send_it = window.setInterval(function(){
$.ajax({
type: 'POST',
url: url,
data: {
clicks:tracking
},
success: function(response)
{
if(response.result.length<1){
console.log(response+ ': no response');
}else{
console.log(response);
tracking = mc.mc_data.click_tracks = [];
}
mc.mc_data.click_tracks = [];
clearInterval(send_it);
sendIt();
},
error: function(a, b, c){
console.log(a+" - " + b+" - "+ c);
clearInterval(send_it);
}
});
}, 5000);
}
//
function logClicks(e){
var temp_click = {
'business_id':window.mc.businessid,
'userid':window.mc.userid,
'timestamp':e.timeStamp,
'leg':window.mc.currentLeg,
'workflow': 'dummy data',
'sequence': sequence,
'type':e.type,
'target':e.target,
'parent': e.target.parentElement,
'id':e.target.id,
'class':e.className,
'innerText': $(e.target).text()
}
mc.mc_data.click_tracking.push(temp_click);
}
For data, you are meant to pass an object which will later be converted into a query string. You are passing the variable tracking, which contains stuff like e.target.parentElement, which is a DOM Node, containing really a lot of further properties (like other DOM Nodes!). The error can originate from either having problems converting a DOM Node into a query string, or creating a way too long query string. It would not make much sense to send a DOM Node to the server anyways.
Only send what is necessary and can be reasonably converted to a query string.
As IE does not support cross domain issues, we have to use get or post method by using xdr, my problem is, I don't know how to pass data while using get method with xdr.
Code snippet for get method using jquery ajax is like -
$.ajax({
type: 'GET',
cache: false,
url: site_url,
data: params,
success: onsuccess,
error:onError
});
but suppose if I write this code for xdr it will be like -
var xdr = new XDomainRequest();
xdr.CacheControl = "no-cache";
xdr.open("get", site_url);
xdr.onload = function () {
var data = $.parseJSON(xdr.responseText);
onsuccess(data);
}
xdr.onerror = function() {alert('err');};
xdr.send();
Now in this, I do not know where to pass data!!!
Please help me out to solve this problem.
It all happens in the ".open" method.
Lets say you want to pass some JSON or an object to the request.
Do it like so...
var my_request_data = {
"whatever" : "whatever",
"again" : "whatever again",
"you get" : "the point..."
};
my_request_data = $.param(my_request_data);
xdr.open("get", "http://url.com/to/get/or/post/too/" + my_request_data);
jQuery turns the JSON object into URL friendly params and then it is sent to the server.
That is how you pass data!