I am trying to search for a given term on the Wikipedia API and am able to retrieve a list of titles and snippets, but I want the JSON to also include the Wikipedia "curid" or "pageid" so I can use that for links.
Here is the (unhelpful) documentation as far as I can tell, and here is what I have so far:
var jsonresult=null;
$.ajax({
dataType: "jsonp",
url: "http://en.wikipedia.org/w/api.php?action=query&format=json&list=search&utf8=1&srsearch=Einstein&callback=?",
success: function(result){
console.log(result);
jsonresult = result;
printAjax(result);
},
error: function(error){
console.log("oh no");
}
});
}
I don't know how to change the API request URL.
To get "pageid" try query with generator instead list, and use extracts property for text snippet:
https://en.wikipedia.org/w/api.php?action=query&generator=search&utf8=1&gsrsearch=Einstein&prop=extracts&exintro=1&exlimit=20&exchars=200
Alternatively, you could use the url query in the ajax request and append the percent encoded title from the returned object encodeURI(data["query"]["search"][index]["title"]) to "https://en.wikipedia.org/wiki/" and use that for your page links.
Related
I'm trying to get only the BTC_BTS data from this endpoint:
https://poloniex.com/public?command=returnTicker
How can I format the url to only return that data and not the rest of the ticker pairs?
You can set up a get request to that endpoint and go through the response depending on your language. For JavaScript and jQuery:
$.ajax({
url: "https://poloniex.com/public?command=returnTicker",
method: "GET"
}).then(function(response) {
console.log(response.BTC_BTS);
});
I'm creating a website where I want to perform CRUD operations to a dataset. For the sake of simplicity, assume a table of books. I understand that example.com/books should return a list of books, and example.com/books/24 should return the book with id 24.
Now, imagine that my list of books is very large, and I want to allow the user to browse the book list using a table with pagination, but as the dataset is very large I want to retrieve only the current page using AJAX.
The question is: should example.com/books return the HTML containing the table with all pagination controls and other widgets? or should it return the data in JSON format? What would be the right way to perform both calls.
Thanks in advance
In your controller you could do something like this:
function index (Request $request){
$books = Book::paginate(10);
if($request->ajax()){
//ajax request
return Response::json(view('books', compact('books'))->render());
}
//html request
return view('books', compact('books'));
}
You can pass a page parameter to the route to navigate to pages.
Example : example.com/books?page=2 will fetch the second page of results.
Suggested Approach
Render the initial request with as html like you would normaly do. Then for the next page, get the second page rendered as an ajax call and append it to the DOM.
return Response::json(view('books', compact('books'))->render());
$('.pager a').on('click', function (e) {
var page = $(this).attr('href').split('page=')[1];
e.preventDefault();
$.ajax({
type: "GET",
url: 'page=' + page,
dataType: 'json',
success:function(json){
alert("Success"+json);
},
error:function(){
alert("Error");
}
});
});
});
Take a look at Laravel Pagination
Based on this documentation: https://developer.chrome.com/extensions/webRequest.html#event-onHeadersReceived
I tried to display the response via the console like:
console.log(info.responseHeaders);
But its returning undefined.
But this works though:
console.log("Type: " + info.type);
Please help, I really need to get the responseHeaders data.
You have to request the response headers like this:
chrome.webRequest.onHeadersReceived.addListener(function(details){
console.log(details.responseHeaders);
},
{urls: ["http://*/*"]},["responseHeaders"]);
An example of use. This is one instance of how I use the webRequest api in my extension. (Only showing partial incomplete code)
I need to indirectly access some server data and I do that by making use of a 302 redirect page. I send a Head request to the desired url like this:
$.ajax({
url: url,
type: "HEAD"
success: function(data,status,jqXHR){
//If this was not a HEAD request, `data` would contain the response
//But in my case all I need are the headers so `data` is empty
comparePosts(jqXHR.getResponseHeader('redirUrl')); //where I handle the data
}
});
And then I silently kill the redirect while scraping the location header for my own uses using the webRequest api:
chrome.webRequest.onHeadersReceived.addListener(function(details){
if(details.method == "HEAD"){
var redirUrl;
details.responseHeaders.forEach(function(v,i,a){
if(v.name == "Location"){
redirUrl = v.value;
details.responseHeaders.splice(i,1);
}
});
details.responseHeaders.push({name:"redirUrl",value:redirUrl});
return {responseHeaders:details.responseHeaders}; //I kill the redirect
}
},
{urls: ["http://*/*"]},["responseHeaders","blocking"]);
I actually handle the data inside the onHeadersReceived listener, but this way shows where the response data would be.
I'm trying to consume the json services from broadbandmap.gov so that I can display broadband providers and their speeds in an area. Here is a sample url:
http://www.broadbandmap.gov/internet-service-providers/70508/lat=30.1471824/long=-92.033638/%3Ejson
I'm using jquery to consume the service, however it's giving me an invalid label error in firebug:
var url = "http://www.broadbandmap.gov/internet-service-providers/70508/lat=30.1471824/long=-92.033638/%3Ejson";
//var url = "http://www.broadbandmap.gov/broadbandmap/broadband/fall2010/wireline?latitude=" + lat + "&longitude=" + long + "&format=json";
$.ajax({
url: url,
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (result) {
console.debug("in success");
console.debug(result);
//success, execute callback function.
},
error: function (result) {
console.debug("in error");
console.debug(result);
}
});
The strange thing is that under the Invalid Label error in Firebug it actually has the correct response:
{"status":"OK","responseTime":7,"messa...//www.cscic.state.ny.us/broadband/"}}}
I have tried setting the dataType to json, jsonp, and other types as well to no avail. I have also tried GET instead of POST but that didn't work either. Does anyone know what I'm missing?
That error is occurring because the service is returning JSON and not JSONP. Your browser is not going to let you process straight JSON from a cross-domain source.
In order to make the service return JSONP you have to use a specially formatted URL. If you go to the search results page without the "/>json" modifier (link) you'll see a link on the page that reads "API Call". If you hover over this link it will give you the correct URL to use for the wireless/wired API call. Use one of those URL's in your ajax call with a JSONP return type & callback and you should be all set.
I created an updated fiddle at http://jsfiddle.net/qsY7h/1/.
This is a cross-domain request so you should use JSONP datatype - the API supports this return type. The URL you provided in your example didn't return anything for me so I checked out Broadbandmap's Developer Docs and found an alternate call. Please find an example at http://jsfiddle.net/szCAF/.
The most important point to note is "callback=?" in the URL. jQuery uses this to tell the API what function name to wrap around the output (this is all done transparently by jQuery).
I have a modal dialog (done through jquery UI) that submit a form to a remote controller Action.
This is the jquery function called:
$("fpForm").submit(function() {
$.ajax({
type: "POST",
url: "ForgotPassword",
data: $("#fpForm").serialize(),
success: function(response) {
alert(response);
},
error: function(response) {
alert(response);
}
});
});
The action does some verification on the data and then send back a response in JSON format. Let's say, for example, that this is a sample response:
{"result":"NOK","message":"The user is not registered on the system"}
My questions are:
Why the debug alert that I have set in the "success" and "error" block does not are get executed?
How I can write my code to parse the response while remaining in wait for it on the dialog?
How can I write code to block the form elements during the ajax call?
I am sorry if the question could seem stupid for most of you but I am completely new to ajax and I am trying to learn throgh some experienced pattern that I know.
Thank you for your responses
The first error is the usage of $("fpForm").submit instead of $("#fpForm").submit.
If the server sand back JSON data, for example as JsonResult, you should include dataType: "json" to convert result to the object in object. After that you can replace alert(response); to
alert('Result: ' + response.result + ', Message: ' + response.message);
To block the form element I'll recommend you to use jQuery BlockUI Plugin. On the demos you will find different examples of usage and find the way which you like.
My questions are:
Why the debug alert that I have set in the "success" and "error" block
does not are get executed?
How I can write my code to parse the response while remaining in wait
for it on the dialog?
How can I write code to block the form elements during the ajax
call?
If you meant to use the id then you missed the # designator:
$("#fpForm")
Add the sync : true option on the call?
You could either: set the disabled attribute on the form elements AFTER posting the request, or else mask the page with an element (possibly semi-transparent) to divert the inputs.