Request JSON by AJAX in two ways - javascript

I don't know why but when I do request JSON in this way console log prints nothing:
var xhr = new XMLHttpRequest();
function elenco_studenti() {
var url = "/controller?action=student_list";
xhr.responseType = 'text';
xhr.open("GET", url, true);
xhr.onreadystatechange = print();
xhr.send(null);
}
function print(){
console.log(xhr.responseText);
}
Instead when I do request JSON in this way, it works:
$(document).ready(function(){
$.ajax({
url: '/controller?action=student_list',
dataType: 'json',
success: function (data) {
console.log(data);
}
});
});
Can you help me? Thank you very much.

Assign the function reference instead of invoking the function
xhr.onreadystatechange = print();
to
xhr.onreadystatechange = print;
and wait for the actual response to be ready
function print() {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
}
link to docs

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...');
}
}
});

Why wikipedia ajax call is not working

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);
}
});

converting javascript code to jquery

I have following code of javascript for search function. It works well when written inside html/php file it self, however, when I try to add this in my jQuery file, it doesn't work anymore.
<script type="text/javascript">
function findmatch(){
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if ( xmlhttp.readyState == 4 && xmlhttp.status == 200 ){
document.getElementById('search_result').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'php/search.php?search_text='+document.search.search_text.value , true);
xmlhttp.send();
}
</script>
I tried replacing 'getElementById' with $('#') and few some ways. But didn't work. I want to convert in jQuery so I can manage/animate 'search_result' div according to size of result returned. I don't know how will I do that. But, if you can guide me fir that extra, It would be great/
If i understand correctly, it's Ajax call:
<html>
<head>
<script src="jqueryLibrary.js"></script>
<script type="text/javascript">
function findmatch() {
$.ajax({
url: 'php/search.php?search_text=' + document.search.search_text.value,
type: 'get',
success: function(responseText){
$('#search_result').text(responseText);
}
})
}
</script>
</head>
</html>
try this one
function findmatch(){
$.ajax({
type : "GET",
url : 'php/search.php?search_text='+document.search.search_text.value,
cache : false,
async : false,
success : function(data) {
$('#search_result').text(data);
},
error : function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
So this should work:
function findmatch() {
$.post('php/search.php?search_text='+document.search.search_text.value,function(response){
$('#search_result').html(response);
});
}
//EDIT: Made a mistake, semikolon after function findmatch() { }; <<
Greetings

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