Why wikipedia ajax call is not working - javascript

var url = 'http://en.wikipedia.org/w/api.php?action=opensearch&format=json&limit=15&search=' + search;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', url);
ourRequest.onload = function() {
var data = JSON.parse(ourRequest.responseText);
console.log(data);
};
ourRequest.send();
Can someone tell me why i am not able to get parsed data in my console.

You need to add one more parameter to your url variable to make this request work -
origin=*. Add it and your code will be fine.
Check how I've changed the url variable. Wikipedia API requires the request origin included in the parameters string.
document.getElementById('do-search').addEventListener('click', search);
function search(){
var search = document.getElementById('search').value;
var url='http://en.wikipedia.org/w/api.php?action=opensearch&format=json&limit=15&origin=*&search='+search;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', url);
ourRequest.onload = function() {
var data = JSON.parse(ourRequest.responseText);
document.getElementById('results').innerHTML = data;
};
ourRequest.send();
}
<input id="search" type="text">
<button id="do-search">Search</button>
<div id="results"></div>

Well i made it to work with the following code.
$.ajax({
url: url,
jsonp: "callback",
dataType: "jsonp",
success: function(data) {
console.log(data);
}
});

Related

How to get PHP variable from JS AJAX request?

I make an AJAX request:
//javascript
var rq = new XMLHTTPrequest();
rq.open('POST','test.php', true);
rq.send(JSONString);
In "test.php" I make something like:
//php
$data = "Hello";
And I want to return $data back to my JS (via rq.responseText I suppose) how should I do it?
You can use XMLHttpRequest.response to get the response.
Please see the following code snippet and check out the documentation for details.
var url = 'test.php'; //A local page
function load(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.response);
}
}
xhr.open('POST', url, true);
xhr.send(JSONString);
}
You can return JSON from PHP. EX
in javascript:
$.ajax({
url : url_api,
method : 'GET',
dataType : 'json',
data : {},
success : function (data) {
var hello = data.data;
}
});
In PHP:
<?php
$array = ['data' => 'hello'];
echo json_encode($array);
Dammit, the problem was that I did
rq.onload = alert(rq.response);
Instead of
rq.onload = function()
{
alert(rq.response);
}
Sorry pals

Using AJAX GET request to pass the value of <option> tags to the URL

I want to pass options' values to the URL whenever the users select an option. For example these are the options:
Option 1
Option 2
Option 3
And this is the URL: http://example.com/products
When he selects an option among those 3, the URL changes into this: http://example.com/products?option=option1
I tried vanilla Javascript XMLHttpRequest for this, and this is my code:
function ajaxFormValidate(_method, _url, _callback, _fallback, _sendItem) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState < 4) {
return;
}
if(xmlHttp.status !== 200) {
_fallback(xmlHttp.response);
return;
}
if(xmlHttp.readyState === 4) {
_callback(xmlHttp.response);
}
};
xmlHttp.open(_method, _url, true);
xmlHttp.send(_sendItem);
} //Set a function for AJAX Request
//Actual performance
window.addEventListener('load', function(){
var _sort = document.getElementById('sort'), _filter = document.getElementById('filter'); //Get the elements
_sort.addEventListener('change', function(){ //If the value of the field changes
var _frmData = new FormData(); //Create a new FormData object
_frmData.append('sort', _sort.value); //Append the value to this object
ajaxFormValidate('GET', location.href, function(response){
//Perform the redirection here (without reloading the page)
}, function(response){
alert("Request cannot be sent!");
}, _frmData);
}, false);
});
Recently, I don't have any ideas for this. Any help is appreciated. Thanks
This is a good way of using GET in pure Javascript:
var ajax = new XMLHttpRequest();
ajax.open("GET", "example.com/products.php?option=YOUR OPTION VALUE GOES HERE", true);
ajax.send();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
console.log(data);
}
}
And this is the jQuery way (my preferred method):
var myOption = $('.your-elenet-calss-name').val();
var myurl = "http://example.com/products.php";
var dataString="&option="+myOption+"&check=";
$.ajax({
type: "GET",
url: myurl,
data:dataString,
crossDomain: true,
cache: false,
beforeSend: function(){//Do some stuff here. Example: you can show a preloader///},
success: function(data){
if(data =='success'){
alert('done deal...');
}
}
});

How can I parse HTML returned from AJAX call

I am making a GET call to the server and it returns a String of HTML. I want to parse this HTML and only get the HTML with the id 'container'.
Here is my code:
$("#name").click(function() {
$.ajax({
type : 'GET',
url : "/",
dataType : 'text',
success : function(data) {
var object = $('<div/>').html(data).contents(); //Convert the String into an object.
var container = object.find('container'); //This successfully gets the object with the id 'container'
console.info(container.html()); //Here is where I want to output just the HTML of the container.
},
error : function(data) {
console.error("Error getting homepage");
}
});
return false;
});
I want to just output the HTML that has the id 'container'. Right now it is outputting nothing. I don't think I am doing this in the best way.
ALSO: I am going to be loading the HTML into another element on the page.
I was able to accomplish what I wanted with the following:
$("#name").click(function() {
$.ajax({
type : 'GET',
url : "/",
dataType : 'text',
success : function(data) {
var parser = new DOMParser();
doc = parser.parseFromString(data, "text/html");
var remainder = doc.getElementById("main-content").innerHTML;
$("#r-div").replaceWith("<div id=\"main-content\">" + remainder + "</div>");
},
error : function(data) {
console.error("Error getting homepage");
}
});
return false;
});
This gets a HTML response then extracts "main-content" div and replaces "r-div" in the current page with the HTML
This is what I used in my own code:
var xhr = new XMLHttpRequest();
var url = "http://....";
xhr.open("GET", url, true);
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
html = $.parseHTML( xhr.responseText );
var container = $("#container", html);
}
}

Ajax parsexml without jquery

I have a piece of code to get the unread count of Gmail. It is using jQuery, and I would like to know how to do it without a Javascript library, just with Javascript.
$.ajax({
type: "GET",
url: "https://mail.google.com/mail/feed/atom",
dataType: "xml",
success: parseXml
});
function parseXml(xml)
{
var result = $(xml).find("fullcount").text();
alert("count:" + result);
}
try this
var xmlhttp=new XMLHttpRequest();
xmlhttp.setRequestHeader("Access-Control-Allow-Origin","https://mail.google.com");
xmlhttp.open("POST","https://mail.google.com/mail/feed/atom",false,"username","pwd");
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var mailCount=xmlDoc.getElementsByTagName("entry").length;
ok, Solved
xhrGmail = new XMLHttpRequest();
xhrGmail.open('GET','https://mail.google.com/mail/feed/atom')
xhrGmail.onload = function() { console.log(xhrGmail.responseText.split("<fullcount>") [1].split("</fullcount>")[0]) }
xhrGmail.send(null);

how to set a dynamic URL to the XHR POST parameter?

Note : Please note the question may be silly as I've just begun client-side development.
I need to make an XHR POST request to a dynamic link retrieved through JSONP. However for some reasons it doesn't work. Basically the POST url "youtube_url_upload" becomes undefined. xhr.open("POST", youtube_url_upload);
Here is the code snippet :
var get_youtube_service_url ="http://video.example.com/youtubeupload?jsoncallback=?";
$.ajax({
type: "GET",
url: get_youtube_service_url,
dataType: "jsonp",
cache : false,
success: function(data) {
// get youtube
// var y_url = data.url;
var token = data.token;
var youtube_url_upload = data.url + "?nexturl="+encodeURIComponent("http://selling.example.com/youtube.html");
calltoken(token);
uploadFile(youtube_url_upload);
}
});
var bytesUploaded = 0;
var bytesTotal = 0;
......
function uploadFile(youtube_url_upload) {
var xhr = new XMLHttpRequest(youtube_url_upload);
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", youtube_url_upload);
xhr.send(fd);
intervalTimer = setInterval(updateTransferSpeed, 500);
}
.....
the success callback get the a string as "data", not object
it's may be a json so use
$.parseJSON ( data )

Categories

Resources