Wikipedia API. File not found Error - javascript

I'm trying to make a wikipedia search bar. The idea is to send a new AJAX request every time search input is changed. I'm using https://www.mediawiki.org/wiki/API:Search_and_discovery as a guideline.
var search = $('#search');
search.keyup(function() {
if (search.val() === '') {
result.html('');
}
$.ajax({
url: '//en.wikipedia.org/w/api.php',
data: {
action: 'query',
list: 'search',
format: 'json',
srsearch: search.val()
},
dataType: 'jsonp',
success: function(response) {
console.log("success!");
}
});
});
However, success function is not even triggered.
On any keypress the error I get is this ("d" pressed):
jquery-2.1.1.min.js:4 GET file://en.wikipedia.org/w/api.php?>callback=jQuery21107844703783826772_1484403407494&action=query&list=search&srse>arch=d&format=json&_=1484403407495 net::ERR_FILE_NOT_FOUND
Thank you in advance for any help or guidance!

Well, you're probably trying to do a AJAX request without a local server (opening your file directly in the browser).
First of all, your url options starts with //en... (without the protocol). It indicates that it'll construct your full url using the same protocol you're using. In this case: file://. That's because your browser is trying to reach file://en.wikipedia.org/....
So, you can set your url to https://en.wikipedia.org/w/api.php to make it work.
Just replace:
url: '//en.wikipedia.org/w/api.php',
with:
url: 'https://en.wikipedia.org/w/api.php',

Looks like you're running it from a simple html file located in your filesystem, in other words not running it from a web server (even local).
Try calling the api with
url: 'https://en.wikipedia.org/w/api.php'
or run the file from a web server (can be a local one).

Related

JavaScript URL issue with Permalinks enabled

I am using the following JavaScript function to fetch the data using ajax call
function findName() {
var name = "Jhon";
$.ajax({
method: "POST",
url: "oc-content/themes/bender/ajax-test.php",
data: { name : name },
success: function (data) {
alert(data);
},
})
}
It calls the following php file and works fine.
http://127.0.0.1/osclass/oc-content/themes/bender/ajax-test.php
But when I enable SEO friendly Permalinks in my CMS current page URL is appended in start of link and I get the following error in Chrome Console.
GET http://127.0.0.1/osclass/fashion-beauty/oc-content/themes/bender/ajax-test.php?name=Jhon 404 (Not Found)
Anybody tell me how to solve this issue?
The url you've provided in the ajax call is document relative. When you changed the server's url generation scheme, you also caused the url pointed at by the ajax call to change.
Adjust the ajax url, changing:
url: "oc-content/themes/bender/ajax-test.php",
To:
url: "/osclass/oc-content/themes/bender/ajax-test.php",
Why don't you make the URL server-relative? Something like this:
function findName() {
var name = "Jhon";
$.ajax({
method: "POST",
url: "/osclass/oc-content/themes/bender/ajax-test.php",
data: { name : name },
success: function (data) {
alert(data);
},
})
}
As you have not posted the php code. I would mention that any url directly navigated through addressbar of browser causes in the GET request and i can see you have a POST request in the ajax, so, it can't work.
Workaround would be to use $_REQUEST super globals at php end. $_REQUEST would work for $_GET/$_POST requests.

Get proper root in javascript file

I'm having a problem with resolving the root of a URL between my local machine and after deploying an application on IIS to our dev server.
The url when running locally is something like this.
http://localhost:57173/
the url when running on the dev server is something like this.
http://ServerName/AppName
I have JQuery Ajax calls to a web api and it won't find the location on the dev server if the trailing slash is left off.
Here's the call
$.ajax({
type: "GET",
url: "api/MyApi/Get",
data: { period: selectedPeriod },
cache: false,
success: function (data) {
}
});
If I look in FireBug at the api call on the dev server, with the trailing slash left off, it will show
http://ServerName/api/MyApi/Get
If I do have the trailing slash, it will resolve correctly to this. (Notice the AppName now included.)
http://ServerName/AppName/api/MyApi/Get
What am I missing here? It looks like it's not finding the proper root of the application when I move it to this server. The trailing slash makes no difference locally. It will find the api either way. Any ideas how to resolve this?
I also had this issue, the way to solved it was declare a javascript variable that contains the part of the url that differs in both environments (dev and local) and prepend that to every ajax request:
I put that variable in the layout file (Views/Shared/_Layout.cshtml), so that it could be automatically filled by ASP.NET and then used globally (make sure to create the script before the #RenderSection call):
...
<script>
var baseUrl = #Html.Raw(Json.Encode(Url.Content("~")));
</sctipt>
#RenderSection("scripts", required: false)
</body>
...
Then prepend that variable in the url of the ajax call (for example View/Home/Index.cshtml):
#section scripts {
$.ajax({
type: "GET",
url: baseUrl + "api/MyApi/Get",
data: { period: selectedPeriod },
cache: false,
success: function (data) {}
});
}
A url without a leading slash is considered a relative url. Your url "api/MyApi/Get" will be resolved by the browser relative to the url of the page containing the script.
http://ServerName/AppName appears to the browser as if it is a page request, with AppName being the name of the page and the AppName is not considered when resolving the url.
http://ServerName/AppName/ (trailing slash) appears to the browser as a directory request and becomes the base of your relative url.
The best fix for this is probably to redirect requests for http://ServerName/AppName to http://ServerName/AppName/
To do the redirect from within your application, insert the following into your /Home/Index controller action (before any other code)
if (!Request.Url.AbsolutePath.EndsWith("/"))
{
return Redirect("~/");
}
This will redirect any request for http://ServerName/AppName to http://ServerName/AppName/ As a side effect, it would also redirect any requests for http://ServerName/AppName/Index to http://ServerName/AppName/ but I don't think that would cause you any problems.
Javascript typically doesn't run unless the user causes an event to occur. I prefer to use the following because it allows MVC to get the exact route properly everytime no matter where you deploy.
Html
<button data-url="#Url.Action("MyApi", "Get")"></button>
Javascript
$(document).ready(function()
{
$('button').on('click', function()
{
var url = $(this).data('url');
$.ajax({
type: "GET",
url: url,
data: { period: selectedPeriod },
cache: false,
success: function (data) {
});
});
});
Hard coding a url in javascript I consider bad-practice.

How to get a json response from yaler

I create an account with yaler, to comunicate with my arduino yun. It works fine, and i'm able to switch on and off my leds.
Then i created a web page, with a button that calls an ajax function with GET method to yaler (yaler web server accept REST style on the URL)
$.ajax({
url: "http://RELAY_DOMAIN.try.yaler.net/arduino/digital/13/1",
dataType: "json",
success: function(msg){
var jsonStr = msg;
},
error: function(err){
alert(err.responseText);
}
});
This code seem to work fine, infact the led switches off and on, but i expect a json response in success function (msg) like this:
{
"command":"digital",
"pin":13,
"value":1,
"action":"write"
}
But i get an error (error function). I also tried to alert the err.responseText, but it is undefined....
How could i solve the issue? Any suggestions???
Thanks in advance....
If the Web page containing the above Ajax request is served from a different origin, you'll have to work around the same origin policy of your Web browser.
There are two ways to do this (based on http://forum.arduino.cc/index.php?topic=304804):
CORS, i.e. adding the header Access-Control-Allow-Origin: * to the Yun Web service
JSONP, i.e. getting the Yun to serve an additional JS function if requested by the Ajax call with a query parameter ?callback=?
CORS can probably be configured in the OpenWRT part of the Yun, while JSONP could be added to the Brige.ino code (which you seem to be using).
I had the same problem. I used JSONP to solve it. JSONP is JSON with padding. Basically means you send the JSON data with a sort of wrapper.
Instead of just the data you have to send a Java Script function and this is allowed by the internet.
So instead of your response being :
{"command":"digital","pin":13,"value":0,"action":"write"}
It should be:
showResult({command:"analog",pin:13,value:0,action:"write"});
I changed the yunYaler.ino to do this.
So for the html :
var url = 'http://try.yaler.net/realy-domain/analog/13/210';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'showResult',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.action);
},
error: function(e) {
console.log(e.message);
}
});
};
function showResult(show)
{
var str = "command = "+show.command;// you can do the others the same way.
alert (str);
}
My JSON is wrapped with a showResult() so its made JSONP and its the function I called in the callback.
Hope this helps. If CORS worked for you. Could you please put up how it worked here.

Consuming web service in HTML

I have created a web service and saved its .wsdl file. I want to consume this service in my HTML file by providing its URL.
Can anybody tell me how to call the URL in HTML and use it?
Like its done here.
http://www.codeproject.com/Articles/14610/Calling-Web-Services-from-HTML-Pages-using-JavaScr/
The only difference is my web service does not have an extention like "asmx?wsdl".
Does that makes any difference.
I followed that tutorial too but it does not produce any output.
Thank You////
You definitly should get familiar with AJAX.
You could use the ajax functionalities provided by jQuery. That's the easiest way, I assume. Take a look at http://api.jquery.com/jQuery.ajax/
You can use this like
$.ajax({
url: "urltoyourservice.xml"
dataType: "xml",
}).done(function(data) {
console.log(data);
});
HTML itself cannot consume a webservice. Javascript ist definitely needed.
The existence of your WSDL File looks like you are probably using a XML format as the return of the web service. You have to deal with XML in javascript. Therefore take a look at Tim Downs explanation.
But keep in mind, that your web service URL must be available under the same domain as your consumption HTML-File. Otherwise you'll receive a cross-site-scripting error.
yes you can use ajax but keep in mind you wont be able to make a request across domains. Consuming web services should be done in server side.
To further gain more knowledge about this, read How do I call a web service from javascript
function submit_form(){
var username=$("#username").val();
var password=$("#password").val();
var data = { loginName: username, password:password };
$.ajax( {
type: "POST",
url:"Paste ur service address here",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data){
var value = data.d;
if(value.UserID != 0){
alert.html('success');
}
},
error: function (e) {
}
});
}
Try this it will help

Ajax get request to wsdl web-service

i have wsdl file and i need get data from. How i can do this ? i'm trying do this with ajax
like this:
jq.ajax({
url: 'http://url.wsdl',
type: 'get',
success: function(data){
alert("OK " + data);
},
error: function (x, y, z) {
alert("ERROR");
}
});
what i do wrong ?
Any other way to get data from wsdl web service using javascript, jquery and etc. is?
I think what you are missing is a data: {}
I read that there was some sort of bug if you did not include that when using $.ajax
Oh, and most likely you are going to need dataType: "json" or whatever datatype the service is using.
Here is an example i am using against an online webservice:
jQuery.support.cors = true; //enables cross domain queries for Ajax
$('#jqueryBtn').click
(function ()
{
$.ajax
(
{
type: "GET",
url: "http://www.webservicemart.com//uszip.asmx/ValidateZip",
data: { 'ZipCode': '22553' },
dataType: 'html',
success: jqSuccess,
error: jqError
}
);
}
Hopefully you can use this example to fix your own code
http://forum.jquery.com/topic/jquery-ajax-to-call-a-wsdl-web-service
The following link should explain why you cannot use AJAX for cross domain queries:
http://www.w3schools.com/xmL/xml_parser.asp:
Access Across Domains
For security reasons, modern browsers do not allow access across
domains.
This means, that both the web page and the file it tries to load,
must be located on the same server.
The examples on W3Schools all open XML files located on the W3Schools
domain.
If you want to use the example above on one of your web pages, the file you load must be located on your own server.
You can create a proxy web page in your web server to access to WSDL web service and return result to the AJAX request

Categories

Resources