Having trouble with Bing search API not functioning properly with AJAX?

Looking to incorporate Bing's search API using JavaScript. My goal is to allow the user to input a query and retrieve only images from Bing.

I attempted to use Ajax for this task. When entering the URL directly in the browser, I successfully retrieved an XML document.

However, I encountered issues when using XMLHttpRequest.

<html>

<body>

<script>

var xhr = new XMLHttpRequest();
var url="http://api.search.live.net/xml.aspx?Appid=[YOURAPIKEY]&sources=image&query=home"
xhr.open("GET", url, true );
xhr.onreadystatechange=function(){
    /*if( xhr.readyState == 4 && xhr.status == 200) {
        document.write( xhr.responseText );
    }*/
    alert( "state: "+xhr.readyState +" status: "+xhr.status +" statusText: "+xhr.statusText +" respText: "+xhr.responseText);
};
xhr.send(null);



</script> 

</body>
</html>

Questions: 1) Any insights on why the previous code snippet doesn't function as expected? 2) Are there alternative methods to achieve this without using XMLHttpRequest?

Thank you in advance.

By the way, my focus is on resolving this issue specifically for Firefox and without relying on external libraries like jQuery.

Answer №1

Performing XHR cross-domain requests is restricted, JSONP is the recommended approach.

<script type="text/javascript">
function handleBingData(response){
  ...
};
</script>
<script type="text/javascript" src="http://api.search.live.net/json.aspx?Appid=[YOURAPIKEY]&sources=image&query=home&JsonType=callback&JsonCallback=handleBingData"></script>

If necessary, the process can be made dynamic (using createElement("script"), etc.). Refer to this answer for more information.

By specifying JsonType=callback, we indicate the use of JSONP, with the JsonCallback parameter triggering the callback to handleBingData. More information can be found in the MSDN documentation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Add an unidentified element into a sealed directive's scope

Is it possible to inject a value into a directive's close scope? I couldn't find any information about this in the angularjs documentation, so I decided to experiment. Does anyone know of a more elegant solution to this issue? Here is my current ...

Sort table rows by checkbox value in javascript

Is there a way to use javascript or JQuery to group the rows in this table by Office or Age based on the checkbox option selected? For example, if the Office checkbox is checked, the table rows should be grouped by Office. If the Age checkbox is checked, ...

Trouble initiating Jquery on a dynamically generated table

I am currently working on a project in ASP.Net where I need to dynamically build an HTML Table. I have implemented the ability for users to resequence rows in the table, but I'm facing issues with the delegate events I've written. Sometimes they ...

serverless with Node.js and AWS encountering a 'TypeError' with the message 'callback is not a function'

Within my handler.js file, I am utilizing the getQuotation() function from the lalamove/index.js file by passing the string "hi" as an argument. 'use strict'; var lalamove = require('./lalamove/index.js'); module.exports.getEstimate = ...

What is the process for performing a redirection in Node JS?

I have been working on a task to redirect a page to the home page with the route '/search' upon form submission. Within my submit.html file, there is a form that utilizes the '/submit' post method to submit the form data when the submit ...

Phantom.js: Exploring the Power of setTimeout

Below is a snippet of code that intends for Phantom.js to load a page, click on a button, and then wait for 5 seconds before returning the HTML code of the page. Issue: Utilizing setTimeout() to introduce a delay of 5 seconds leads to the page.evaluate fu ...

Tips for delivering a variable to a React Native Stylesheet

Is there a way to pass a variable to the "shadowColor" property in my stylesheet from an array declared in the code above? I keep encountering a "Can't find name" error. Attempting to use a template literal has not resolved the issue. Any assistance w ...

Notify user with a Javascript alert if there are no search results found

I have developed a search index for Chicago employees and want to create an alert if no matching records are found. However, I am struggling to determine the value that needs to be inserted in case of an empty result set. Ideally, upon submission of the fu ...

Have you ever wondered why req.body returns as undefined when using body parser?

Every time I attempt to make a post request, I keep receiving an error message stating that req.body is returning as undefined. Below is the content of my server.js file: import express from 'express'; import bodyParser from 'body-parser&ap ...

Saving the created PDF documents on the server

Utilizing the jsPDF plugin, I am currently generating a .pdf file upon clicking a button to initiate a download. Rather than downloading the file, I would like it to be saved onto my server when the button is clicked. Specifically, I want the file to be sa ...

Could someone please explain how to obtain a compiled string within an AngularJS directive?

Check out the following code snippet for my custom directive: mymodule.directive("test", function($compile) { return { restrict: 'E', replace: true, template: '<div data-date="{{avail}}"></div>', ...

Is it possible to achieve the same @ResponseBody functionality with ModelAndView in Spring MVC?

One aspect where Rails excels in its controller design is the flexibility of using the index controller action for various purposes such as listings, searches, and ajax calls without explicitly specifying a return type. On the other hand, working with Spr ...

The order in which JQuery is executed can sometimes be unpredictable

Review this code snippet. It is supposed to: Perform an ajax request to save the latitude and longitude values Utilize these values in the following line: var center = new google.maps.LatLng(resplat, resplon); The issue lies in the fact that the code do ...

Retrieve the scope object using angular.element and the $ID parameter

In order to transfer data from an angular application to scripts that operate outside of angular, I am seeking a solution since I cannot modify the code of the angular app. By utilizing Angular Batarang and NG-Inspector extensions in Chrome, I have identi ...

Where is the function returned by redux-thunk invoked?

Can you help me understand where the function returned by addUser is being called in this action creator and redux thunk function? const userAdded = () => ({ type: types.ADD_USER, }); export const addUser = (user) => { return function (dispat ...

Automatically generated error notifications for Express-Validator

I am looking to implement an Express API and incorporate request input validation using express-validator. Here is my current validation middleware: protected validate = async (request: Request, response: Response, next: NextFunction): Promise<void> ...

The issue of Access-Control-Allow-Origin not functioning properly when using Ajax for a POST request

I am encountering an issue with the header "Access-control-allow-origin" when making a request using the following code: <script type='text/javascript'> function save() { $.ajax( { type: 'POST', ur ...

How to handle an undefined value in a jQuery ajax call when utilizing promises

I've been struggling with the issue of jQuery ajax calls returning values before they've been updated. Despite trying numerous solutions found through Google searches, none seem to work for me. The problem lies in getting an undefined value becau ...

What defines a quick or sluggish load time when it comes to a webpage?

Recently, I constructed a webpage with multiple JavaScript elements incorporated. I am wondering what constitutes a fast load time versus a slow one. Currently, my load time is averaging around 490ms with four different JavaScript components. Is this con ...

What prevents variables defined in outer blocks from being accessed by nested describe() blocks?

In my real code, I encountered a problem that I wanted to demonstrate with a simple example. The code below functions properly. I defined a variable in the root describe() block that can be accessed in the it() blocks of nested describe()s. describe(&apo ...