vanilla js vs jQuery ajax call - javascript

I want to do an ajax call with vanilla js.
In jQuery, I have this working ajax call:
$.ajax({
url:"/faq/ajax",
datatype: 'json',
type:"POST",
data: {search:'banana'},
success:function(r) {
console.log(r['name'])
}
});
Vanilla JS:
var search = document.getElementById('searchbarfaq').value;
var r = new XMLHttpRequest();
r.open("POST", "/faq/ajax", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
console.log("Success: " + JSON.parse(r.responseText));
var a = JSON.parse(r.responseText);
console.log(a.name); //also tried a['name']...
};
r.send("search=banana");
The vanilla js call just logs this to the console:
"Success: [object Object]"
Array [ ]
Can someone tell me what I am doing wrong?

You haven't told the server how you are encoding the data in the request.
r.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
Presumably whatever server side handler you are using to process the data isn't parsing it correctly, so isn't finding the data it needs, and then returns a blank array as the result.

Beyond printing out r.responseText to the console, you can also inspect the HTTP response from dev tools built into the browser itself.
On Firefox, for instance:
Tools -> Web Developer -> Network
(this should open a panel listing all the HTTP requests and responses)
Go through the process you use to execute your AJAX call
Look at the corresponding HTTP request by clicking on the item in the list in the panel shown in step 1 (a panel on the right should appear with more details about the request and subsequent response)
Digging around in these tools can give you a lot of insight into the the HTTP request your code is making and the values it's getting back in the response.
A similar process can be performed for all the major browsers out there.

You can use this simple and lightweight Ajax module with the following syntax:
import {ajax} from '/path/to/ajax.min.js';
ajax('https://api_url.com')
.data('key-1','Value-1')
.data('key-2','Value-2')
.send()
.then((data) => { console.log ('success', data) })
.catch((status) => { console.log ('failed', status)} );

Related

jQuery getJSON() method is returning an error in the console [duplicate]

I am trying to use a vanilla JS AJAX request to pull back a JSON string from a locally stored JSON file (specifically trying not to use JQuery) - the below code is based on this answer - but I keep getting an error in the Chrome console (see below). Any ideas where I'm going wrong? I have tried changing the positioning of the xhr.open & .send requests, but still get error messages. I suspect the issue lies with the .send() request?
//Vanilla JS AJAX request to get species from JSON file & populate Select box
function getJSON(path,callback) {
var xhr = new XMLHttpRequest(); //Instantiate new request
xhr.open('GET', path ,true); //prepare asynch GET request
xhr.send(); //send request
xhr.onreadystatechange = function(){ //everytime ready state changes (0-4), check it
if (xhr.readyState === 4) { //if request finished & response ready (4)
if (xhr.status === 0 || xhr.status === 200) { //then if status OK (local file || server)
var data = JSON.parse(xhr.responseText); //parse the returned JSON string
if (callback) {callback(data);} //if specified, run callback on data returned
}
}
};
}
//-----------------------------------------------------------------------------
//Test execute above function with callback
getJSON('js/species.json', function(data){
console.log(data);
});
The console in Chrome is throwing this error:
"XMLHttpRequest cannot load file:///C:/Users/brett/Desktop/SightingsDB/js/species.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource."
Would be grateful for any insights - many thanks.
Basically as Felix, error msg, et al below say - simply can't run an AJAX request against a local file.
Thanks.
Try to run the application on local server like apache or wamp then you will not face any issue

JQuery Promise failing on ComponentDidMount React.JS

In my components' ComponentDidMount life cycle method, I'm attempting to initiate an AJAX request to get data client-side (Data needs to be available when app has loaded). Upon inspection, I've noticed that my promise chain keeps deferring to the fail property. This is confusing because, upon inspection via the Chrome Developer tools, the request is made and data is successfully returned to the promise (see Screenshot). I suspected it could be the speed at how fast my component loads, and I tried a componentWillMount life cycle method, and it yields the same results. I was retrieving data fine, synchronously via an AJAX request, but I'm now trying to improve the code with asynchronously functionality.
new code tried:
componentDidMount: function(){
var returnedClassesString;
var user = window.globalValue;
function getQueries(user){
returnedClassesString = $.ajax("/portals/0/js/get_classes_front.aspx?userName="+user).done(function(data,err){
console.log('good' + data);
}).fail(function(data,err){
console.log(err);
});
}
getQueries(user);
},
componentDidMount method:
componentDidMount: function(){
var returnedClassesString;
var user = window.globalValue;
$.when($.ajax("/portals/0/js/get_classes_front.aspx?userName="+user)).then(function(data, textStatus, jqXHR) {
// Handle both XHR objects
console.log(data);
}).fail(function(){
console.log('failed');
});
}
Screenshot of Chrome Dev-Tools (Network Traffic, I request the first file in the stack):
Screenshot of Chrome Dev-Tools (JavaScript console w/ 'failed' message):
Issue was on my server-side code. Using .Net code-behind, switched Response.ContentType from Response.ContentType = "text/xml"; to Response.ContentType = "text";. Thank You to Dave Methvin for spotting out my JSON error. Code posted above in both examples still valid.

difference between youtube's request and mine

i want to make a script that makes every video's comment section look like the ones that still have the old kind.
for example, videos on this channel:https://www.youtube.com/user/TheMysteryofGF/videos
in Firebug, in the Net tab, i noticed the comment JSON file's URL it is requested from is different.
i tried to run a code on the youtube watch page which would request the file the same way, but it doesnt work, and in firebug it says it was forbidden.
the URL is the same, they are both POST, and i cant figure out what is different. i can even resend the original request in firebug and it works... so anyway, here is a code i tried on a video with "1vptNpkysBQ" video url.
var getJSON = function(url, successHandler, errorHandler) {
var xhr = typeof XMLHttpRequest != 'undefined'
? new XMLHttpRequest()
: new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('post', url, true);
xhr.onreadystatechange = function() {
var status;
var data;
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
if (xhr.readyState == 4) { // `DONE`
status = xhr.status;
if (status == 200) {
data = JSON.parse(xhr.responseText);
successHandler && successHandler(data);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
getJSON('https://www.youtube.com/watch_fragments_ajax?v=1vptNpkysBQ&tr=time&frags=comments&spf=load', function(data) {
alert('Your public IP address is: ' + data);
}, function(status) {
alert('Something went wrong.');
});
You are using Ajax to get data. Ajax has 1 restriction: You can only get data from your own server. When you try to get data from another server/domain, you get a "Access-Control-Allow-Origin" error.
Any time you put http:// (or https://) in the url, you get this error.
You'll have to do it the Youtube way.
That's why they made the javascript API. Here is (the principal of) how it works. You can link javascript files from other servers, with the < script > tag
So if you could find a javascript file that starts with
var my_videos = ['foo', 'bar', 'hello', 'world'];
then you can use var my_videos anywhere in your script. This can be used both for functions and for data. So the server puts this (dynamically generated) script somewhere, on a specific url. You, the client website can use it.
If you want to really understand it, you should try building your own API; you'll learn a lot.
Secondary thing: Use GET.
POST means the client adds data to the server (example: post a comment, upload a file, ...). GET means you send some kind of ID to the server, then the server returns its own data to the client.
So what you are doing here, is pure GET.

Chrome Dev tools won't show ajax request response

I have a nodejs application where I make some ajax request using jquery. In developer tools response of last ajax request is empty if I make redirection, otherwise response exists. Is there any logic to why wouldn't it show response in case of redirection.
I don't understand redirection is made in ajax callback and based on values from response, redirection is made properly which means response exist but chrome dev tools won't show it, What am i doing wrong?
here is my callback
.done(function (response)
{
if (response.errorCode == "00") {
//window.location = "/"; //no response shown if dev tools if i uncomment this
console.log("Yeah i got some response " + response);
}
})
Make sure Preserve the log upon navigation is enabled in chrome dev tools settings.
Let
window.location = '/whatever/address';
be the last thing you call, or do it later using
setTimeout( function () {
window.location = '/whatever/address';
}, 1);`
Beware that all values of variables will be lost on a new page load / navigation
After redirection everything gets reloaded that's why you are not able to access response.
To solve this you can first use your response object & then redirect your page.

Implementing comet on the client side

I'm trying to implement comet in my application and, being inexperienced with JavaScript, I'm not sure how to do the client side.
When the server receives a request, it just keeps it open and writes data to it when necessary:
def render_GET(self, request):
print "connected"
request.write("Initiated\r\n")
reactor.callLater(random.randint(2, 10), self._delay, request)
return NOT_DONE_YET;
def _delay(self, request):
print "output"
self.count += 1
request.write("Hello... {0}\r\n".format(self.count))
reactor.callLater(random.randint(2, 10), self._delay, request)
I've been using jQuery on the client side so far, but I can't figure out how to make it work with the server. I've been looking at the jQuery.AJAX documentation and none of the callbacks say "Hey! I just received some data!", they only say "The request is finished."
I thought the dataFilter() function was what I wanted since it lets you handle the raw data before the request finishes, but it only lets you do it just before the request finishes, and not as you receive data.
So how can I receive data continuously through an open request? As you can see in the python example, each piece of data is delimited with \r\n so I want the JavaScript to behave like a line receiver. Is this possible with jQuery or do I have to play with XMLHttpRequest/ActiveXObject directly? Is there a (simple, lightweight) library available which implements a line receiver for me?
I'm hoping to hear about an existing library and how to implement this myself, since I've had bad bad luck with comet libraries so far, and at this point I'm hoping to just write the code I need and not bother with an entire library.
After looking at some other Comet/jQuery questions, I stumbled across this: http://code.google.com/p/jquerycomet/, which looks to be a jQuery plugin that does what you're after. If you're looking to see how it works, I'd just dig into the source.
The question where I found some great information is here.
A standard technique is to do a long polling request via AJAX (standard call with a really long timeout), then when receiving a response have your callback initiate another long poll when it is invoked. If the timeout expires, then you reissue the request using the error handling mechanism. Rather than having a single long request that periodically does something (like the "infinite iframe" technique), this uses a series of long requests to get data as the server has it available.
function longPoll( url, data, cb )
{
$.ajax({
url: url,
data: data,
timeout: Number.MAX_VALUE,
...other options...
success: function(result) {
// maybe update the data?
longPoll( url, data, cb );
cb.call(this,result);
},
error: function() {
longPoll( url, data, cb );
}
}
}
this code is the simpliest I have ever seen.
var previous_response_length = 0
, xhr = new XMLHttpRequest();
xhr.open("GET", "http://127.0.0.1:7379/SUBSCRIBE/hello", true);
xhr.onreadystatechange = checkData;
xhr.send(null);
function checkData() {
if(xhr.readyState == 3) {
response = xhr.responseText;
chunk = response.slice(previous_response_length);
previous_response_length = response.length;
console.log(chunk);
}
};

Categories