Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: Running AJAX locally without a webserver

I have the following function in a .js file in index.html

function getValues(){

 $.ajax({
   type: 'POST',
   url: "http://localhost/getData/getdata.php",
   success: function(data){
     var dataValues;
     var apnd;

     dataValues = String(data.NSE);
     apnd = "a";
     updateValues(dataValues, apnd);

     dataValues = String(data.BSE);
     apnd = "b";
     updateValues(dataValues, apnd);
    },
   dataType: "json"
 });

}

this works fine when I run it in a webserver like wamp. But I want to run index.html locally i.e without a webserver, The user just double clicks index.html and it should run but it doesn't. data is always null. What could be the problem? Sorry I am a super JQuery Noob.

the code in getdata.php file is

<?

echo json_encode(array("NSE"=>rand(5000, 20000),"BSE"=>rand(5000, 20000))); 

?>
like image 652
Steven Avatar asked Aug 03 '10 14:08

Steven


People also ask

Can we use AJAX without server?

This example isn't using a lot of data, but chances are in real life, you wouldn't use Ajax unless you had a lot of extra data to get back from the server. Otherwise, it wouldn't be worth going to the server to get the data, and you might as well just put the data directly into the page.

Can you run AJAX locally?

You cannot use the file protocol to make an AJAX request locally.

Can we use AJAX without URL?

URL is not required, if you make call to current page.

Can I use AJAX with jQuery?

jQuery | ajax() Method. The ajax() method in jQuery is used to perform an AJAX request or asynchronous HTTP request. Parameters: The list of possible values are given below: type: It is used to specify the type of request.


2 Answers

When you run your index.html from a file the AJAX works. But the problem occurs because you are viewing the file at address "file://....../index.html" and you are making a AJAX request to "http://localhost/..../something.php" which IS NOT ALLOWED because of cross site scripting. All AJAX requests must go to the same domain/server.

This is a assuming that you are viewing the file by double clicking it and still making the AJAX request to the web server.

like image 109
Bob Fincheimer Avatar answered Sep 23 '22 03:09

Bob Fincheimer


AJAX needs a webserver to communicate with for it to be able to retrieve any data; otherwise its just talking to a wall. Running the script without a webserver is like trying to make a call with no cell-service. :D

like image 35
Gordon Gustafson Avatar answered Sep 21 '22 03:09

Gordon Gustafson