What do these AJAX Parameters do with Wikipedia's API? - javascript

I'm analyzing this CodePen's code, which lets the user search any item within Wikipedia (through Wikipedia's API), and the search engine shows the first 10 results and brief summaries. Analyzing other people's code is (IMO) one of my best ways to learn, along with reading guidebooks and finishing tutorials.
The AJAX code I couldn't understand, is this:
$.ajax({
url: "https://en.wikipedia.org/w/api.php",
jsonp: "callback",
dataType: 'jsonp',
data: {
action: "query",
list: "prefixsearch",
pssearch: $(".searchbox").val(),
pslimit: "10",
format: "json"
},
xhrFields: {
withCredentials: true
},
success: updateSuggest,
error: function(err) {
console.log(err);
}
});
Idont understand what these 4 data parameters (action, list, pssearch, pslimit) do. What exactly are these 4 parameters' functions... can someone explain them? For example, what does pssearch and list and pslimit do?
I tried looking these terms up on the API, jQuery website and Google searches, but no avail.

These properties are for searching the title prefix:
action: "query": Queries for data action.
list: "prefixsearch": "Perform a prefix search for page titles." (docs, prefixsearch)
pssearch: The search string. - (docs)
pslimit: Limit the number of entries to returned. - (docs)
The Prefixsearch has a short explanation of most of these parameters.

They create the url query parameters that will end up looking like:
https://en.wikipedia.org/w/api.php?action=query&list=prefixsearch.....&format=json
when the actual request is made. The api documentation will provide the specifics for each option

Related

asp.net webservice jquery populate textbox

I want to get 3 values from a web service by providing current URL and current user. My webservice accepts 2 parameter URL and user. Web service works fine.
Now I want to put this 3 values in 3 different textboxes using jquery.in txtOrgCity = city, in txtPin = pin, in txtCountry = country
bellow is code for txtOrgCity
$(document).ready(function () {
$('#txtOrgCity').val({
source: function (request, response) {
$.ajax({
url: '../lead_hunter.asmx/GetOrgCity',
method: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ url: "http://srv3.testsrv.com/homepage", user: "testuser#testsrv.com" }),
dataType: 'json',
success: function (data) {
response(data.d);
},
error: function (err) {
alert(err);
}
});
when I run it gives me [object object] in text box.
How do I define to grab City for txtOrgCity, pin for txtOrgPin, country for txtOrgCountry in response(data.d).?
and do I need to duplicate the same code for other 2 text boxes or any better way.?
Given code is just for some txtbox autocomplete and it works perfectly so I just wanted it to modify a bit for my need. $('#txtOrgCity').val was $('#txtOrgCity').autocomplete
Any help would be appreciated.
--
Thanks
I recommend that you open this up in google chrome. Open up your developer tools (press f12) and, open up resources and select the page you are currently working on. Then use the find box to search for your javascript method which fires the ajax and put a break point inside the success part of your ajax call. Now run your code and wait to hit the break point. Now you can see what is inside your data.d object. Do not resume and keep debugging. Open up your console tab and type data.d. you should see an intelicence option box with all the variables inside your data.d object. You should see the variable for city, pin and country in whatever way you named them when you deserialized your data and returned it as json to your ajax call.
If, for example, you write data.d.city in your console it should write out the corresponding value. The same goes for any other json variable your service passed back to the browser.
With that information it is easy enough to use jquery and do what you want with the data. So in the succes part of your ajax call you can write:
$("#txtOrgCity").val(data.d.city);
$("#txtPin").val(data.d.pin);
$("#txtCountry").val(data.d.country);
p.s. im writting on a phone.
For your example you should not write out the same code two more times. Do not call ajax inside a jquery .val(), that is wrong. Make a new function which handles your ajax, call it from the page load or anywhere you need :
function loadData(//put your user parameter in here if you need){
$.ajax({
url: '../lead_hunter.asmx/GetOrgCity',
method: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ url: "http://srv3.testsrv.com/homepage", user: "testuser#testsrv.com" }),
dataType: 'json',
success: function (data) {
$("#txtOrgCity").val(data.d.city);
$("#txtPin").val(data.d.pin);
$("#txtCountry").val(data.d.country);
},
error: function (err) {
//welldone for handling your error message. Many people neglect this. As a developer that is like coding blindly. At the very least you can console.log(err); if you don't want the user to see
alert(err);
}
});
}
Instead of $('#txtOrgCity').val({})
In your .ready function make the AJAX call first.
Store d.OrgCity, d.OrgPin & d.OrgCountry into some local JavaScript variables. In the Ajax call success use these values to deposit into textboxes like
$('#txtOrgCity').val(d.OrgCity)
You are after JSON.stringify(). So where you specify your .val() You want .val(JSON.stringify());

Access-Control-Allow-Origin header is not present on the requested resource

DISCLAIMER: This question is a question about question. So that makes this question a meta question. It does not have any connection to the previously asked questions. If you find any resemblance, lemme tell you one thing- it's purely coincidental.
I want to make an AJAX request from my web page. I have been trying to do this, but none of the methods worked perfectly. The only post that I found something close to reality is this.
I tried various other methods from SO & other similar sites, but all of those posts said only one thing to me.
"No 'Access-Control-Allow-Origin' header is present on the requested resource."
I know now you are gonna mark this question as duplicate since there are loads of questions similar to this. Now..Lemme tell ya' one thing. I tried every piece of sh*t I found in SO, but none of 'em gave me the result that I was looking for. It's not because they all are wrong. It because I ain't got no knowlegde on how to use 'em. Then finally...I settled on the link I provided above. It's easy..but I need to know certain things about the code.This is the first time I am hearing the beautifully sodding acronym- CORS. So, if anyone can help me understand the questions I raise, Up votes for all of ya'. I wanna resolve this son-of-a-b*tch question before I celebrate my birthday for the third time this year. I will tell ya' what all I have-in form of resources & questions.
1) A rotten server located at Elizabeth town.
2) I need to access it.
3) I am planning to make a HTTP GET request.
4) I have a url. (eg. http://whereismyweed.com)
5) I store it into a JavaScript variable. var stoner='http://whereismyweed.com'
6) I have a HTML div tag in my webpage. (<div id="myprecious"></div>)
7) I wanna display the response I get from the server inside of 'myprecious' div.
8) And last but not the least... my AJAX function. (Courtesy: some website I visited)
$.ajax({
url: stoner,
data: myData,
type: 'GET',
crossDomain: true, // enable this
dataType: 'jsonp',
success: function() { alert("Success"); },
error: function() { alert('Failed!'); },
beforeSend: setHeader
});
What is 'myData'?? What does it contain. How can I get the response for this request? What is 'setHeader'?? Does it have any significance??? How can I display the response inside myprecious div? What changes should I make in the function? Is this function correct?
Too many question, Right???? Well...I need only one common answer for it?
Your function is correct.Follow below steps do achieve your goal-
//for getting response modify your code like
success:function(response){
alert(response);
$('#myprecious').html(response); //myprecious is id of div
}
// myData variable is jSon object which contains request parameter has to send.Eg.
var myData = {'first_name':'Foo','last_name':'Bar'} // now on server first_name and last_name treated as request parameter.
// If server not required any special headers to validate request 'setHeader' does not require. by default $.ajax will take care of it. you can remove it.
/// final code looks like
$.ajax({
url: stoner,
data: myData,
type: 'GET',
crossDomain: true, // enable this
dataType: 'jsonp',
success: function(response ) { $('#myprecious').html(response);
},
error: function() { alert('Failed!'); }
});

JQuery Autocomplete - multiple data post not working

$("#textjawatan" + noid).autocomplete({
source: function( request, response ) {
$.ajax({
url: "pendaftar_table.php",
dataType: "json",
data: { term : "pe" } ,
success: function( data ) {
response( data );
}
});
},
minLength: 2,
select: function(event, ui) {
$("input#jawatan" + noid).val(ui.item.no);
}
});
when i use
data: { term : "pe" }
its work, but when i use
data: { term : "pe", id : "jawatan" }
its doesnt work, what is the problem ?
I actually had this problem not too long ago. Let me explain in quick words.
As jQuery Autocomplete explain in their site http://api.jqueryui.com/autocomplete/ jQuery Autocomplete only accepts TERM as output for server. Let me quote the page
Function: The third variation, a callback, provides the most
flexibility and can be used to connect any data source to
Autocomplete. The callback gets two arguments: A request object, with
a single term property, which refers to the value currently in the
text input. For example, if the user enters "new yo" in a city field,
the Autocomplete term will equal "new yo". A response callback, which
expects a single argument: the data to suggest to the user. This data
should be filtered based on the provided term, and can be in any of
the formats described above for simple local data. It's important when
providing a custom source callback to handle errors during the
request. You must always call the response callback even if you
encounter an error. This ensures that the widget always has the
correct state.
In other words, if you even add 250 extra hashes to the json dict, it will only work TERM to server side.
How did I fix this?
What I did was this. Based on jQuery docs, the source can also be an ARRAY, so i did an ajax call to my server BEFORE setting the jQuery autocomplete and then feed the autocomplete plugin.
Note: This is not a very good fix, and I'm aware of it. But I had to do it due to my work's details and is just an option.

Using multiple ajax calls in one javascript function

Thanks in advance for any help.
Is it bad practice and/or inefficient to use multiple $.ajax calls in one javascript function? I've been working on one and have a simple testing environment set up on my computer (apache server with php/mysql), and I've noticed that the server will crash (and restart) if I have multiple ajax calls.
I have two ajax calls currently: one passes 4 pieces of data to the php file and returns about 3 lines of code (pulling info from my sql database), the other simply gets the total rows from the table I'm working with and assigns that number to a javascript variable.
Is it just that my basic testing setup is too weak, or am I doing something wrong? See below for the two ajax calls I'm using:
$.ajax({
type: "GET",
url: "myURLhere.php",
cache: false,
data: {img : imageNumber, cap : imageNumber, width : dWidth, height : dHeight},
})
.done(function(htmlpic) {
$("#leftOne").html(htmlpic);
});
$.ajax({
type: "GET",
url: "myotherURLhere.php",
cache: false,
success: function(data) {
lastImage = data
}
})
Short answer: two ajax request on a page is absolutely fine.
Longer answer:
You have to find the balance between minimalising the number of ajax calls to the backend reducing the traffic and communication overhead; and still maintaining a maintainable architecture (so do not pass dozens of parameters in one call to retrieve everything - maybe only if you do it in a well designed way to collect every parameter to send)
Also most likely there's something wrong with your backend setup, try looking into webserver logs

search autocomplete performance with many records

I'm developing an application that is essentially a search bar. The source is a SQL table that has about 300,000 records.
Ideally, I would like to have some sort of autocomplete feature attached to this search bar. I've been looking into several ones like jquery autocomplete.
However, as one can imagine, loading all of these records as the source for the autocomplete is impossible. The performance would be abysmal.
So my question is, what is an efficient way to implement a search autocomplete feature for a source that contains thousands and thousands of records?
I thought of something like this. Essentially I'm querying the database each time they type something to get a list of results. However, querying a database via ajax doesn't seem optimal.
$( "#search" ).keyup(function( event ) {
$.ajax({
//query the database when the user begins typing, get first 1000 records
//set the source of the autocomplete control to the returned result set
});
});
You should not start querying the db on very first keyup, (not even in three-four) keyup.
For example, User is typing Albatross. When He hit 'A', if you do a Query search it will send you almost 300,000 results right away, cause every set of data must have the letter "A".
So, should ignore first few (3-5) letters. it will be better, if you can store the search keywords. Cache the top results, when 1-3 keyup you show the top search keywords. Auto complete might not be good feature for searching in a that big DB,
Last Tips for the problem, Your users use google and facebook everyday. They are more then 300,000 result for each of search in any of the applications above. Google or facebook does not show 1000 result at once. It is not good for UI Design or your Servers bandwidth. Just think, how can you categorizes and present the data to user, so that they get what they want and you keep your servers bandwidth and processing cost optimal.
always, remember the context.
Do not bind any events yourself. jQuery Autocomplete already performs bindings.
The proper way to implement this is to set the source: object to a an AJAX callback:
source: function (request, response) {
$.ajax({
url: 'yourQueryUrl.php', // <- this script/URL should limit the number of records returned
async: true,
cache: false,
type: 'GET',
data: {q: $('#searchBox').val()},
dataType: 'json',
success: function (data) {
response(data);
}
});
}
I am assuming you have added indexes to your table, if not that would be your first step, then if performance is insufficient and if your queries often repeat, you might want to look at this.
http://memcached.org/
or some other caching mechanism.
Upon request of some key you would return that key and add it to the cache, opon subsequent request for same key data would be read from cache instead of hitting database. That would reduce the load and increase the speed.
source: function (request, response) {
$.ajax({
url: 'yourQueryUrl.php', // <- this script/URL should limit the number of records returned
async: true,
cache: false,
type: 'GET',
data: {q: $('#searchBox').val()},
dataType: 'json',
success: function (data) {
response(data);
}
});

Categories

Resources