URL &callback parameter - javascript

What does the &callback parameter in a URL do? The reason I am asking is because I am running a query with jquery's $.ajax function and when I include &callback=? in the end of the url I get a 400 (bad request) error.
Here is my javascript code:
var energy_query_array = [];
var masterEnergyTable_tableid = '145TOXaanydD63tvgVMmCVH0hei0NXNCEK8ekZBg';
var current_date = 'Jan-12';
var energy_query = 'SELECT * FROM ' + masterEnergyTable_tableid;
var encoded_energy_query = encodeURIComponent(energy_query);
var energy_url = ['https://www.googleapis.com/fusiontables/v1/query'];
energy_url.push('?sql=' + encoded_energy_query);
energy_url.push('&key=' + apiKey);
//energy_url.push('&callback=?');
$.ajax({
url: energy_url.join(''),
datatype: 'jsonp',
success: function(data) {
var name_array = data['columns'];
var data_array = data['rows'][0];
for(var i = 1; i < data['columns'].length; i++) {
energy_query_array[name_array[i]] = data_array[i];
}
}
});
console.log(energy_query_array);
I have commented out the line where I add &callback=? to the url because when I leave it in the query returns the error:
"message":"Invalid value for parameter callback: ?"
However, earlier in the code I performed a similar query to google fusion tables using the same parameter for callback.
The console.log call at the end of the code displays an empty array to the console.

Callback is used for JSONP requests which is mean't to be used when doing a cross domain request to fetch JSON data. Instead of using the XHR wrapper, it uses a script tag which then passes a callback querystring parameter which points to the function that is used to execute passing in all the JSON data inside. This way you can have a datapoint which has no idea of how your application works, but when you pass in a callback then it will fire a function with the data. This allows you to use it's API from any browser.

Like any other piece of data in a query string (or anywhere else between the hostname and the fragment id), it provides some data to the server. The meaning is entirely determined by the software running on that server.
There is a convention to use callback as the key for a value that will be used as the name of the function to call in a JSON-P response in a RESTful API. JSON-P is a means to provide a web service accessible across origins for browsers which do not support CORS.
e.g.
http://example.com/foo?callback=asdf
would give you
asdf([1,2,3]);
JSON-P, obviously, requires that the server support the sending of JSON-P responses. If you try to perform a cross-origin request with jQuery it will (by default) modify the request on the assumption that the server will support JSON-P with the usual conventions.

Read about Query Strings
They start with a ?, and additional parameters get concatnated with &. The ? should never be anywhere but the beginning of the string unless it's encoded.
The key value pairs then are available to the server, as this is how a standard GET request is performed.
For example:
http://myserver.com?name=josh&age=24&state=il
Your web server is probably choking on the query string somewhere.

Related

How to pass a JavaScript array as parameter to URL and catch it in PHP?

I have an array in JS and I am trying to pass it as parameter to URL and catch it in PHP but I cant get to understand how to do it:
var trafficFilterHolder = ["roadworks","snow","blocking"];
var filters = encodeURI(JSON.stringify(trafficFilterHolder));
FYI: I am using windows.fetch for posting.
in PHP:
$trafficFilters = $_GET["trafficFilters"];
$obj = json_decode($trafficFilters);
var_dump($obj);
You are passing the data to php with fetch() intead of ajax, so the alternative of my first answer to do the same with the fetch() is:
var trafficFilterHolder = ["roadworks","snow","blocking"];
var trafficFilterHolderJoin = trafficFilterHolder.join(); // comma-separeted format => "roadworks,snow,blocking"
Now add the trafficFilterHolderJoin variable to the traffic query of the URL of your fetch(), like:
fetch('script.php?traffic=' + trafficFilterHolderJoin)
Then in your php script file you will convert the comma-separeted format to php array format using the explode function:
$traffic = explode(",", $_GET['traffic']);
It's quite simple, you are passing these data to php with ajax, correct?
First of all, you are creating the javascript array incorrectly:
var trafficFilterHolder = [0: "roadworks", 1: "snow", 2: "blocking"];
Don't use brackets to create arrays with keys, use this format instead:
var trafficFilterHolder = {0: "roadworks", 1: "snow", 2: "blocking"};
Now, in the ajax, just add the array in the data:
$.ajax({
data: { trafficFilters: trafficFilterHolder }
});
All demands to the server are executed as an http requests. Ther are two types of HTTP requests - GET and POST.
https://www.w3schools.com/tags/ref_httpmethods.asp
What you're describing is called GET request. With GET request the parameters are passed via the address bar. For making an http request you have two options.
The direct HTTP GET request.
For this you need simply open a new page with
window.location.href = 'http://your_site.com/file.php?name1=value1&name2=value2'
This will open a new page in your browser and pass a request with your parameters.
An Ajax HTTP GET request.
You have a lot of options here:
an old-fashion way with xmlHttpRequest object
a modern fetch API with promises
third-part libraries like jQuery.ajax etc.
AJAX request can send and receive information from the server (either in GET or POST request) without renewing the page. After that the result received can be managed with your javascript application however you want.
Hope, it makes more clear for you. You can search about all this technologies in the google. This is the way how to exchange data from front-end to back-end.
Try using ajax and pass that array and retrieve values at the PHP end.
var filters = encodeURI(JSON.stringify(trafficFilterHolder));
$.ajax({
type: "POST",
url: "test.php",
data: {data : filters},
cache: false,
success: function(){
alert("OK");
}
});

Cannot carry out Ajax request from wikipedia

I want to use wikipedia API in my project to grab images of people, but fail. I use this url:https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100
When i console browser says the following
Refused to execute script from 'https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=Albe…Callback&callback=jQuery22409288979864744966_1470068280411&_=1470068280412' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
My code
var general = {
// The URL to the quote API
url: 'http://api.forismatic.com/api/1.0/',
// What to display as the author name if s/he's unknown
unknownAuthor: 'Uknown',
// Base URL for the tweet links generation
tweetURL: 'http://twitter.com/home?status=',
wikiURL:'https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=Albert Einstein&pithumbsize=100&callback=wikiCallback'
};
var wikirequest = function() {
$.ajax({
url:general.wikiURL,
dataType: 'jsonp',
success: function(wikData) {
console.log(wikData);
//var image = wikiData.
displayQuote(image);
} // end of success
});
}// wikirequest
wikirequest();
Pen
Has anyone met the same issue?
You are trying to load the data using JSONP, but you are making a request to a URL that returns an HTML document. JSONP requests have to be answered with JavaScript programs (since that is a fundamental feature of how they work … and also why they are dangerous and should be avoided in favour of plain JSON and CORS).
To make it return JSONP you need to provided two additional query string parameters:
format=json
callback=YourCallbackName
… where YourCallbackName is the name of the function that should be executed and passed the data you are fetching as an argument. Most Ajax libraries will generate that name (and the function itself) dynamically when you specify callback=?.
https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100&format=json
You are missing the &format=json on the URL - The page was displaying the data with the html header and you would have been attempting to decode this. The above answer is actually better.

Rendering mongodb database results from POST request in .ajax jquery wrapper in node js

I am creating a basic piece of functionality to allow users to send their location to a server which then queries a database and returns locations near to them. I am using the below jQuery .ajax wrapper to POST data to the server. This takes the form of a latlon point which is then used as the basis for a geosearch in MongoDB using nodejs and express on the backend. The results of the search are then intended to be returned to the client and rendered by the createMapListings function.
The /find page is initially rendered through a GET request to the database via mongodb separate from the below code. However subsequent to initial rendering, I then want to return results dependent on the location provided.
The POST method works fine and the location is posted to the server, with the search results being returned as I can print contents out through the console log.
However, I then want to render the results on the client-side. As mentioned, the results of the search render in the console, but when I attempt to pass through to the client, I can render the data itself (in the form of an array of objects) in the #output div, but the createMapListings function does not seem to catch the data.
In fact, the below function appears to be called but prints out over a thousand rows with the data that should be caught described as 'undefined'. I have tried to use res.render and res.redirect, but in the first case, the view renders in the div (which I suppose is expected) and the redirect fails.
The createMapListings function works fine when a simple GET request is made to the server, for example, for all objects in a collection, using ejs template. However, I think the issue here may be a combination of a POST request and then wanting to pass the results back to the AJAX request using the complete callback.
I apologise if the below code is somewhat obtuse. I’m definitely what you would call a beginner. I appreciate the above functionality may not possible so if there is a better way, I would of course be open to it (res.direct perhaps).
Here is the relevant client side script:
$(document).ready(function(){
$("#geolocate").click(function(){
navigator.geolocation.getCurrentPosition(geolocate, function(){
});
});
});
function geolocate(pos){
var latlonpt = [];
var x = pos.coords.latitude;
var y = pos.coords.longitude;
latlonpt.push(x);
latlonpt.push(y);
var obj = {
userlocation: latitudelongitudept
};
$.ajax({
url: "/find",
type: "POST",
contentType: "application/json",
processData: false,
data: JSON.stringify(obj),
complete: function (data) {
$('#output').html(data.responseText);
$('#infooutput').children().remove();
createMapListings(data.responseText);
}
});
};
function createMapListings(maps) {
for (var i = 0; i < maps.length; i++) {
var url = maps[i]._id;
var fullurl = "<a href='/show?id=" + url + "'>Route</a></div>";
var title = "<div>" + maps[i].title + " - " + fullurl +"";
$('#infooutput').append(title);
};
};
</script>
Here is the relevant route used in a basic express app to handle the post request made by the above .ajax wrapper.
exports.findbylocation = function(req, res) {
console.log(req.body.userlocation);
var userlocation = req.body.userlocation;
Map.ensureIndexes;
Map.find({loc :{ $near : userlocation }}, function(err, maps) {
if (err) {
console.log(err)
}
else {
var jmaps = JSON.stringify(maps);
console.log(jmaps);
res.send(jmaps);
}
});
};
By convention, the data variable name in an $.ajax callback signature refers to the parsed HTTP response body. Since your callback is on complete, we're actually passed the XMLHttpRequest used, by convention called xhr. You rightly grab the responseText property, but this needs parsing to be useful. So long as we take care over our Content-Type's and don't explicitly disable processData, jQuery will do the encoding/unencoding for us - we just deal with objects. This is a good thing, since the transport format isn't usually of any particular importance to the application logic. If we use res.json(maps) in place of res.send(jmaps), we can write our call more simply:
$.ajax({
url: '/find',
type: 'POST',
data: obj,
success: function(data) {},
error: function(xhr, text, err) {}
});
Here data is a Javascript object already parsed and ready to use. We also use a default application/x-www-form-urlencoded request rather than explicitly setting a contentType. This is the same as far as express is concerned: it will just be parsed by urlencoded instead of json.
Assuming you solved your client-sie problem.
As you are using express there is no need for JSON.stringfy,
you can use res.json(maps).

issue with JSONP getting a cached response from a WCF service

I use JSONP on a client to get data from a server using a WCF service that can return results using HTTP GET (It gets a 'callback' parameter which is a 'function name' and returns callback({data}), you know... JSONP).
Everything works, but if I enable caching (using 'AspNetCacheProfile')on one of the service's operations - then something is wrong, and I'm not sure what...
The way I get the JSONP is by using a function I picked up some time ago from a question here on SO (http://stackoverflow.com/questions/2499567/how-to-make-a-json-call-to-a-url)
function getJSONP(url, success) {
var ud = 'fc_' + + Math.floor(Math.random()*1000000),
script = document.createElement('script'),
head = document.getElementsByTagName('head')[0]
|| document.documentElement;
window[ud] = function(data) {
head.removeChild(script);
success && success(data);
};
script.src = url.replace('callback=?', 'callback=' + ud);
head.appendChild(script);
}
This creates a random id ('fc_xxxx') then assigns it as a function inside the window object, then use it as the 'callback' parameter for the url of the dynamic javascript that is injected to the document, and then the 'ud' function runs, removes the script and calls the 'success' callback function with the received data.
When using it on normal uncached operations from the service, it usually takes about 200ms to get back the response, and it works ok. The cached responses takes ~10ms -
and I get an error that the 'fc_XXXXX' function is undefined.
It's as if the response is "too fast" for it.
I also tried using jQuery.getJSON() - and, again the callback doesn't trigger.
In all cases when I look at the network traffic in Firebug - I can see the GET request, and I can see that the right data does in fact gets returned.
Does anybody have an idea how can I make it work right with the cached responses...?
I got it! The name of the response-function is different on each call (on both my manual jsonp implementation and that of jQuery).
The name of the function is part of the response from the server (as that's part of how jsonp works...).
So, if the response is a cached response - it will actually return the old name of the function (which will no longer exist on the client's context).
So I just need to give a constant name for the callback function in this case and it should bee fine. :)

Write jquery.ajax from existing javascript

I found this article:
http://msdn.microsoft.com/en-us/library/dd251073.aspx
How could I write 'get' request using jquery.ajax?
You could use the .get() method.
http://api.jquery.com/jQuery.get/
Or just use the regular $.ajax() method (http://api.jquery.com/jQuery.ajax/), which defaults to a GET request.
It depends on whether Bing's API respects the standard ?callback=function method for specifying JSONP callbacks, but if so, then this simplified version of the Search() function should do it:
// Bing API 2.0 code sample demonstrating the use of the
// Spell SourceType over the JSON Protocol.
function Search()
{
var requestStr = "http://api.bing.net/json.aspx?"
// Common request fields (required)
+ "AppId=" + AppId
+ "&Query=Mispeling words is a common ocurrence."
+ "&Sources=Spell"
// Common request fields (optional)
+ "&Version=2.0"
+ "&Market=en-us"
+ "&Options=EnableHighlighting"
$.getJSON(requestStr, SearchCompleted);
}
Keep in mind that neither approach is directly triggering a GET, like you might be used to in AJAX requests to a local server using XMLHttpRequest.
To circumvent the cross-domain restriction on XHR, JSONP works by injecting a new script element into your document which then causes the browser to load (via GET) and execute that remote script. That remote script's contents are a single function call to your callback function, with the entire JSON payload as its parameter.
If that doesn't work, including those Bing-specific callback options should work fine in conjunction with jQuery:
// Bing API 2.0 code sample demonstrating the use of the
// Spell SourceType over the JSON Protocol.
function Search()
{
var requestStr = "http://api.bing.net/json.aspx?"
// Common request fields (required)
+ "AppId=" + AppId
+ "&Query=Mispeling words is a common ocurrence."
+ "&Sources=Spell"
// Common request fields (optional)
+ "&Version=2.0"
+ "&Market=en-us"
+ "&Options=EnableHighlighting"
// JSON-specific request fields (optional)
+ "&JsonType=callback"
+ "&JsonCallback=SearchCompleted";
$.getJSON(requestStr);
}
Keep in mind that, at this point (and somewhat before), you aren't really using jQuery itself for much at all. Even though $.getJSON() or $.ajax() or $.get() seem like they're doing something more powerful than the MSDN example, jQuery is going to do exactly the same thing in this case (inject a script element with its srcpointed at requestStr).

Categories

Resources