Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get specific part of external webpage through ajax which has http auth

I am trying to load the content(specific part) of external webpage through ajax request on my webpage. The curl url for the request is as follow

http://useraname:[email protected]:PORT

So, I tried the following ajax call to get the webpage

var username,password;
$.ajax
  ({
    type: "GET",
    url: "http://X.X.X.X:PORT/",
    dataType: 'text/html',
    async: false,
crossDomain: true,
    data: '{"username": "username", "password" : "secret"}',
    success: function (){
    alert('Thanks for your comment!'); 
    },
error: function (err){
alert(err);
},
beforeSend: function (xhr) {
    xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
}
});

This gives me a CORS error (Cross-Origin Request Blocked:). After changing dataType from text/html to jsonp. The I received the response with the following error

[Exception... "Failure" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js :: .send :: line 5" data: no]

The success part of the ajax call is not getting executed in either case. Only it goes to error part. If I received the page than I can fetch the specific part by the following method.

  var data = $.parseHTML(res);  //<----try with $.parseHTML().
  $(data).find('div.content').each(function(){
      $('#here').append($(this).html());

How to get the required result?

After suggestion of @GuRu, I tried the following, but still the success method is not getting called.

var username,password;
$.ajax({
  type: "GET",
  url: "http://X.X.X.X:PORT/",
  data: '{"username": "user", "password" : "secret"}',
  async:true, 
  dataType : 'jsonp',  
  crossDomain:true,
    success: function (){
    alert('Thanks for your comment!'); 
    },
  beforeSend: function( xhr ) {
    xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
    xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
  }
  });
like image 394
Ajeet Khan Avatar asked Dec 23 '15 05:12

Ajeet Khan


1 Answers

For JSON text:

The MIME media type for JSON text is application/json. The default encoding is UTF-8. (Source: RFC 4627).

For JSONP with callback:

application/javascript

Here are some blog posts that were mentioned in the comments that are relevant.

  • Why you shouldn't use text/html for JSON
  • Internet Explorer sometimes has issues with application/json
  • A rather complete list of Mimetypes and what to use them for

Please check What is the correct JSON content type?

like image 130
Parth Trivedi Avatar answered Sep 19 '22 20:09

Parth Trivedi