My jquery script only works in Firefox, why? - javascript

<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
</head>
<body>
<div id="div1">dv1</div>
<div id="div2">dv2</div>
<script type="text/javascript">
function getData(){
$.ajax({
type:"GET",
url:"j.json",
dataType:"json",
success: function(jsondata){
output(jsondata);
}
});
}
function output(json){
//var Data = eval('(' + json + ')');
var html = '';
//alert(Data.length);
for(var i=0;i<json.length;i++){
html += ' name:' + json[i].name + ' age:' + json[i].age;
}
document.getElementById('div1').innerHTML = html;
document.getElementById('div2').innerHTML = json[0].name;
}
setTimeout(getData, 3000);
</script>
</body>
</html>
j.json file is
[{"name":"aaa","age":18},{"name":"bbb","age":19}]
The aim of above code is to update div content with data in local json file. I've tried that in IE & Chrome, but neither worked. I've googled a lot but still can't figure it out.
Anyone got any hints? Thanks in advance.

Do you use web server?
AJAX calls doesnt work with URL starting with file://. This because of the same-origin requirements which were instituted to help deal with cross-site scripting (XSS). See here for more details.
And as I noticed, you should use $(document).ready(function(){ your code }) instead of setTimeout(getData, 3000);

Related

How to use AJAX to POST to PHP?

As I asked here I would like to know how I could pass the data from a simple JS function to php, and log it there.
I found this answer and tried to follow it. This is my code right now (both in the same file)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
</head>
<body>
<script>
function getClientScreenResolution() {
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
console.log(screenResolutionW + ' ' + screenResolutionH)
$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
}
</script>
<script type="text/javascript">
getScreenResolution();
</script>
</body>
</html>
<?php
$screenResolutionW = $_POST['screenResolutionW'];
$screenResolutionH = $_POST['screenResolutionH'];
if(isset($_POST['screenResolutionW'])) {
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Screen res: '."".$screenResolutionW .'x'."".$screenResolutionH
."\r\n");
fclose($fh);
}
?>
However, this does not work.
I wouldn't know how to fix this, whenever I try to google this problem people use more advanced methods, that I wouldn't even know how to start with.
Edit: My PHP and HMTL are in the same file (index.php).
Edit 2: Removed old code for clarity.
This results in these error messages:
Notice: Undefined index: screenResolutionW in index.php on line 153
Notice: Undefined index: screenResolutionH in index.php on line 154
What you want to do with $.post is include your data like this:
$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
where the first of the pair is the POST identifier (the ['screenResolutionW']) and the second of the pair is the variable value.
You will also want to change your POST identifiers to be quoted:
$screenResolutionW = $_POST['screenResolutionW'];
$screenResolutionH = $_POST['screenResolutionH'];
Otherwise, you will get a warning about constants. I have also corrected the spelling in these variables, to reflect what you're trying to write into your file.
fwrite($fh, 'Screen res: '."".$screenResolutionW .'x'."".$screenResolutionH ."\r\n");
EDIT
Part of the problem is that you never call the function to execute it. Here is your HTML with the additions I have suggested, plus calling the function:
EDIT TWO
Added an onload handler for the document:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
</head>
<body>
<script>
function getScreenResolution() {
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
console.log(screenResolutionW + ' ' + screenResolutionH);
$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
}
</script>
</body>
<script type="text/javascript">
$(function() {
getScreenResolution();
});
</script>
</html>
OTHER NOTES
You really should separate the PHP code and place it in a different file because when you run the page as it is now you should get one line logged that has no variables when the page initially runs, then one logged line when the JavaScript fires after the page loads.
Then once separated you should not run your PHP until you test for the existence of a variable, for example:
if(isset($_POST['screenResolutionW'])) {
// your code to write to the file here
}
EDIT THREE
I placed all of the JavaScript in the same script block in the head of the file and have tested again:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
<script type="text/javascript">
$(function() {
function getScreenResolution() {
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
console.log(screenResolutionW + ' ' + screenResolutionH);
$.post("post_test.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
}
getScreenResolution();
});
</script>
</head>
<body>
</body>
</html>
Here you can see the variables are being posted:
Adapting the others answers.
try it:
function getScreenResolution() {
"http://example.com/index.php", screenResolutionW + screenResolutionH
$.ajax({
url: '/index.php',
method: 'POST',
data: {
screenResolutionW : screen.width,
screenResolutionH : screen.height
},
success: function(data) { console.log(data); }
});
}
And in your PHP
$screenResolutionW = $_POST['screenResolutionW'];
$screenResolutionH = $_POST['screenResolutionH'];
echo $screenResolutionW . " - " . $screenResolutionH;
you have to use serialize the array before doing post request.
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
var serializedArr = {
width: screenResolutionW,
height: screenResolutionH
};
$.post('/index.php', serializedArr, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
In the server end, you will get values in $_POST variable.
Apart of all those mistakes you have discovered thanks to other replies, you have these:
$screenResoltuionW = ...
Notice you wrote "ltuion" and in the fopen command you have it correct. screenResolutionW
Same thing with $screenResoltuionH...
That's why you don't get any value in the file, because those variables doesn't exists.

How to get an php echo with jquery

I know this question was asked many times before, I searched really long for the solution but I couldn'd find one, that's why I'm asking. First: I'm trying to connect my HTML-File to my JavaScript file and that worked pretty well. What I want to do now is to display data from my MySql-DB on my HTML-Site, that's why I'm using PHP. I wanted to start simple, that's why I tried to echo "Hello World". But when I run my site, I don't get only "Hello World", I'm getting the whole PHP-Code. How can I fix that problem?
test.php
<?php
echo 'Hello World';
index.html
<!DOCTYPE html>
<html>
<head>
<title>MySite</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<input type="text" id="size">
<button id="saveBtn" value="Click" type="button" >Save</button>
<script src='test.js'></script>
</body>
</html>
test.js
window.addEventListener("load", function () {
$('button#saveBtn').on('click', function () {
var in= $('input#size').val();
if (size== '')
alert("Error");
else {
$.post("test.php", { input: size}, function (data, status) {
alert("data + " : " + status);
});
}
});
});
Everything is actually working fine, except you have some typos in your Javascript file:
You can't use the word in as a variable name, because it is reserved as a Javascript keyword.
The second parameter that you had on the $.post() function is illegal.
The way you concatenated the message in the alert was faulty.
It should look like this to work:
window.addEventListener("load", function () {
$('button#saveBtn').on('click', function () {
var theInput = $('input#size').val();
if (size== '')
alert("Error");
else {
$.post("test.php", function (data, status) {
alert(data + ":" + status);
});
}
});
});
ALSO
It looks like you're trying to prevent the user from sending off the AJAX request until there is something in the input. If this is what you are trying to do then you can do it like this:
window.addEventListener("load", function () {
$('button#saveBtn').on('click', function () {
var theInput = $('input#size').val();
if (!theInput.length) // Checking to see if there's something in the input
alert("Error");
else {
$.post("test.php", function (data, status) {
alert(data + ":" + status);
});
}
});
});
NOTE: It's important to note that in order for your PHP to run at all, you need to set up a local server (This might be why you are getting
PHP errors). You can do that by either installing XAMPP or you can
follow these instructions.

jQuery getJson no response when searching solr

I am trying to search a local Solr core and am getting no response using getJSON. I know the URL works and returns a response but the getJson function seems to return null.
<!DOCTYPE html>
<html>
<head>
<title>Ray Search</title>
</head>
<body>
Document ID:<br>
<input id="query" type="text" name="document_ID"><br>
<button onclick="searchSolr();">Search</button>
<div id="results">
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type='text/javascript'>
function searchSolr() {
var searchStr = $('#query').val();
if (searchStr.length == 0) {
return;
}
var searchURL = "http://localhost:8983/solr/Ray-Docs/select?q=*&wt=json&json.wrf=on_data";
$.getJSON(searchURL, function (result) {
var docs = result.response.docs;
var total = 'Found ' + result.response.numFound + ' results';
$('#results').prepend('<div>' + total + '</div>');
});
}
</script>
</html>
Did you try invoking getJSON like below?
jQuery.getJSON(sourceURL).done(function(returnData){
//Data Processing
});

jQuery, ajax, and php web scraper acting strangely

I'm trying to scrape a web page, but getting some weird results in my browser's console (as seen below). Here's my code:
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Icefilms Searcher</title>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
</head>
<body>
<script type="text/javascript" src="script.js"></script>
<div id="container" style="width:1100px;position:relative;"></div>
</body>
</html>
script.js
$(document).ready(function(){
var currNum = 168000;
var maxNum = 168005;
function generateNextUrl(){
currNum++;
return currNum-1;
}
scrapeThis(generateNextUrl());
function scrapeThis(theUrl){
$.ajax({
url:
"php.php",
data:
"icefilmsURL=" + theUrl,
success:
function(response){
var movieTitle = $(response).find("#videotitle").find("span:first").text();
$("#container").append("<a href='http://www.icefilms.info/ip.php?v="+theUrl+"' target='blank'>"+movieTitle+"</a><br>");
},
complete:
function(){
if(currNum < maxNum+1){
scrapeThis(generateNextUrl());
}
},
error:
function(xhr,err){
$("#container").append("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
$("#container").append("responseText: "+xhr.responseText);
}
});
};
});
php.php
<?php
echo file_get_contents("http://www.icefilms.info/ip.php?v=".$_GET["icefilmsURL"]);
?>
The code works fine, but this is what I see in my console:
Any ideas?
You are seeing those in the console because the page you are scraping contains references to relative paths.
That is to say rather than
<img src="http://www.icefilms.info/someimage.jpg">
The code is
<img src="someimage.jpg">
Therefore, when you grab and display their HTML on your own domain the browser is trying to load the image from your domain, localhost in this case. But you do not have the image on your server.
You can use a base href in the HTML to resolve this, or you could find and replace relative path images to include the domain.
<base href="http://www.icefilms.info/">

Yelp reviews dont display

I am looking at Trying to use jQuery to display JSON text data as an example, but I cannot get any information to display.
When I put the url (http://api.yelp.com/business_review_search?name=pantibar&term=gay&location=Dublin&limit=1&ywsid=XXXXXXXXXXXXXXXXXX) in chrome postman, it does return the information, but I cannot get it to display on my web page.
Any ideas?
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function showData(data) {
$.each(data.businesses, function(i,business){
// extra loop
$.each(business.reviews, function(i,review){
var content = '<p>' + review.text_excerpt + '</p>';
content += '<p>' +review.date + '</p>';
$(content).appendTo('#review');
});
});
}
$(document).ready(function(){
writeScriptTag( "http://api.yelp.com/business_review_search?name=pantibar&term=gay&location=Dublin&limit=1&ywsid=XXXXXXXXXXXXXXXXXX");
});
function writeScriptTag(path) {
var fileref = document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", path);
document.body.appendChild(fileref);
}
</script>
</head>
<body>
</body>
I added the following to the body and everything worked fine.
<div id="review"></div>

Categories