XMLHttpRequest different response vs. jQuery AJAX - javascript

I've made three requests to the same URL which should return the same response- but guess what, they don't.
First, the working one is with jQuery:
$.ajax({
dataType: "json",
url: "https://www.speedrun.com/api/v1/games?name=mkdd&callback=?",
type: "GET",
success: function(data){
console.log("Succes with AJAX - ?", data);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The second one is also with jQuery, but I changed the callback=? to callback=foo. I really can't figure out why this isn't working.
$.ajax({
dataType: "json",
url: "https://www.speedrun.com/api/v1/games?name=mkdd&callback=foo",
type: "GET",
success: function(data){
console.log("Succes with AJAX - foo", data);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Third one is just plain JavaScript - which I was planning on using. It's not working with whatever callback I'm using.
var request = new XMLHttpRequest();
request.open('GET', "https://www.speedrun.com/api/v1/games?name=mkdd&callback=?", true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
var resp = this.response;
console.log("Succes with JS", resp);
}
};
request.setRequestHeader('Content-Type', 'application/json');
request.send();
Can anybody help me with this problem? Am I missing something in my XMLHttpRequest? Why does the callback=? vs callback=foo matter so much?
Fiddle: https://jsfiddle.net/bobtrol/2okpebvn/2/

Related

WordPress AJAX live search without jQuery

I'm trying to make ajax live search on WP website without usage of jQuery cause I don't want to load additional 80kb for this feature. I already made it work with jQuery, but when I try to rewrite script to work with Vanilla jS, I always got the issue
wp-admin/admin-ajax.php 400 (Bad Request)
working code
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
VANILLA JS CODE that doesn't work
var request = new XMLHttpRequest();
request.open('POST', '<?php echo admin_url("admin-ajax.php"); ?>', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = function () {
if (this.status >= 200 && this.status < 400) {
console.log('if');
} else {
console.log('else');
}
};
request.onerror = function() {
console.log('onerror');
};
var data = document.getElementById('keyword').value;
request.send(data);
The obvious problem I see without knowing your problem is that request.send(data); does not equal to { action: 'data_fetch', keyword: jQuery('#keyword').val() } instead you should be writing something like this request.send('action=data_fetch&keyword='+data);
Also, depending on the data value you are passing you may need to encode it. Again, it is somewhat hard to help you without knowing exactly the problem you are having.

Send Webm buffer to php server

I'm recording video and audio from the browser using MediaRecorder. After I finish recording I try to upload it to the server with something like this:
function upload() {
var fileName = 'video.webm';
var formData = new FormData();
formData.append('filename', fileName);
formData.append('blob', blobs);
$.ajax({
type: 'POST',
url: '/upload.php',
data: formData,
processData: false,
contentType: false
}).done(function(data) {
console.log(data);
});
xhr('upload.php', formData, function (fName) {
window.open(location.href + fName);
});
function xhr(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
alert('Done');
}
};
request.open('POST', url);
request.send(data);
}
}
Apparently the $_FILES variable doesn't get set in php, but the $_POST does. The file name has been passed correctly, but if I output the blobs to a file, I'm not able to reproduce the file in an html5 video object, so I guess something is wrong with that.
Could anyone explain what's the best way to accomplish this upload?
Thanks

get html result of php in html file

This code will send request to post parameters to php file:
var param = //some parameters;
var url = file.php;
xhttp.open("POST", url, true);
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhttp.send(params);
I got the response but the php file produce some output like <td><tr>.....
How to get this result of php in some div of my html?
Thanks,
You use onreadystatechange to get the response:
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
$('#mydiv').html(xhttp.responseText);
}
};
XHR is pretty complicated without using a Framework. Just use jQuery it will make this 1000x easier.
$.ajax({
url: "myfile.php",
type: "POST",
data: {
/* Params */
},
success: function(response){
/* Use your response here */
}
});
http://api.jquery.com/jquery.ajax/

Calling finance.yahoo api using jquery

I want to send http request for fetching finance.yahoo stock data with url like : http://finance.yahoo.com/d/quotes.csv?s=GAIL.NS+BPCL.NS+%5ENSEI&f=snl1hgp which returns a csv file. I want to read the response data and fill it in a listview using Javascript or JQuery mobile. None of the links I referred helped me.
I tried using the following code:
$.ajax({
type: "GET",
url: "http://finance.yahoo.com/d/quotes.csv",
data: "s=GAIL.NS+BPCL.NS+%5ENSEI&f=snl1hgp",
dataType: "text/csv",
success: function(data) {
alert(JSON.stringify('data is :' + data));
}
});
I get blank data as alert.
Any sample code or useful link would be appreciated.
I think that the problem is the request is cross domain. There is another question about this here:
Cross-Domain get CSV file
and another answer here :Yahoo JSONP Ajax Request Wrapped in callback function
and a working example here: Displaying ajax results from yahoo finance using underscore.js
Here is a working jsfiddle which makes a jsonp request to d.yimg.com to get the data http://jsfiddle.net/gp6zL/
YAHOO.Finance.SymbolSuggest.ssCallback = function (data) {
alert(JSON.stringify(data));
};
var query;
query = 'Google';
if (query.length > 0) {
$.ajax({
type: "GET",
url: "http://d.yimg.com/autoc.finance.yahoo.com/autoc",
data: {
query: query
},
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "YAHOO.Finance.SymbolSuggest.ssCallback",
});
}
I try to take jQuery out of the equation. The following code will work as long as you whitelist "finance.yahoo.com".
var request = new XMLHttpRequest();
request.open("GET", "http://finance.yahoo.com/d/quotes.csv?s=GAIL.NS+BPCL.NS+%5ENSEI&f=snl1hgp", true);
request.onreadystatechange = function() {//Call a function when the state changes.
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
console.log(request.responseText);
}
}
}
request.send();

Ajax request monitoring flow

I have an AJAX Request in a JavaScript script where I GET a file like that:
$.ajax({
type: "GET",
url: "./" + img_type + ".bmp",
dataType: "html",
timeout: test_timeout,
cache: false,
success: function(msg)
{
//some stuff
}
});
The code itself is correct and works perfectly.
Is there a way to know HOW much of the file I've downloaded while the request is still ongoing?
I mean, once the request gives to me the success message I know that I've downloaded the entire file, but what if I want to know after two seconds of beginning?
Check out the "monitoring progress" section here:
https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest
Here's an example:
var xhr = new XMLHttpRequest;
xhr.onprogress = function(e){
if(e.lengthComputable){
var progress = e.position || e.loaded;
var total = e.totalSize || e.total;
var percent = progress/total*100;
//do something with progress here
}
};
xhr.onload = function(){
var content = xhr.responseText;
//do something with the result here
};
xhr.open('GET','./'+type+'.bmp',true);
xhr.send();

Categories