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)));
?>
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.
You cannot use the file protocol to make an AJAX request locally.
URL is not required, if you make call to current page.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With