1

I am updating historic JS code from another author but having problems converting the below to the JQuery alternative:

var xhr = new XMLHttpRequest();
xhr.open('GET', songurl, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
    document.getElementById('songdiv').innerHTML = '';
    song.src = (window.webkitURL ? webkitURL : URL).createObjectURL(this.response);
}
}
xhr.send();

This is more so to aide consistency, Chrome - developer tools is also suggesting the code to be re-factored.

Here is what I have started with (appreciate it's not much!), the issue I'm having is checking the status code and returning the response if the status code is 200.

$.ajax({
    url: songurl,
    method: 'GET'
);

2 Answers 2

2

You want to attach a function for success.

$.ajax({
    url: songurl,
    method: 'GET',
    success: function(response){
        //do stuff with response
    }
})
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this, was torn between which to accept but accepted the other due to extra commentary.
I'm surprised you accepted the other one since it uses a different function than what you originally went with.
1

ajax(), or the shorthand get(), will do all that for you. There's a success() function that's only called on a successfull, 200-status request:

$.get( songurl, 
  function(data) {
    document.getElementById('songdiv').innerHTML = '';
    song.src = (window.webkitURL ? webkitURL : URL).createObjectURL(data);
  },
  'blob'
);

3 Comments

@A.Wolff Just being explicit about the unused data parameter. Unnecessary, though... I'll remove it.
Oh but usually better is to be explicit... :) I was wondering it because i'm not familiar with blob and it could have a specific reason
Appreciate the response, learnt something new...although sadly JQuery does not support blob by default!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.