Simple web example showing unresolved "ReferenceError: $ is not defined" [duplicate] - javascript

This question already has answers here:
JQuery - $ is not defined
(36 answers)
Closed 5 months ago.
I am trying to call a php from a javascript.
My code is longer, but I'm trying this simple example to see if the call works.
The example consists of three files and when opening in the browser
localhost/myweb/mytest/example01/index.html
the alerts that appear in index.js should be displayed and it calls index.php, which should write a message to a log file.
The files I use in my test example are:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF'8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello world</title>
</head>
<body>
<script src="index.js"></script>
</body>
</html>
index.js
alert("Hello world from javascript!");
debugger;
var myip = "192.168.1.20";
var myfile = "My_file_name";
$.get( 'index.php',{ paramIp: myip, fileSource: myfile },
function( response ) {
if ( response.status == 'success' ) {
alert("PHP returns OK");
}
else {
alert("PHP returns ERROR");
}
}
)
index.php
<?php
$paramIp = (isset( $_GET['paramIp'] ))? $_GET['paramIp']: false;
$fileSource= ( isset($_GET['fileSource'] ))?$_GET['fileSource']: "";
$fp = fopen("log_messages.txt", "a");
$date = (new DateTime("NOW"))->format("y-m-d H:i:s");
fwrite($fp, $date."index.php paramIp = " . $paramIp . ", fileSource = ". $fileSource . PHP_EOL);
fclose($fp);
echo $fileSource;
?>
When I open the page in the browser with the URL
localhost/myweb/mytest/example01/index.html
The javascript alert is displayed, appearing the message
Hello world from javascript!
But when continuing the execution of the script, I see that the php does not get executed and in FireBug the error is shown:
ReferenceError: $ is not defined
After consulting some posts in several forums that talk about this error, I have modified the original files, leaving them like this:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="index.js"></script>
<meta charset="UTF'8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello world</title>
</head>
<body>
<script src="index.js"></script>
</body>
</html>
index.js
$(document).ready(function(){
alert('Hi from jQuery!');
console.log('Hi from jQuery!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
alert("Hello world from javascript!");
debugger;
var myip = "192.168.1.20";
var myfile = "My_file_name";
$.get( 'index.php',{ paramIp: myip, fileSource: myfile },
function( response ) {
if ( response.status == 'success' ) {
alert("PHP returns OK");
}
else {
alert("PHP returns ERROR");
}
}
)
index.php
<script type="text/javascript" src="index.js"></script>
<?php
$paramIp = (isset( $_GET['paramIp'] ))? $_GET['paramIp']: false;
$fileSource= ( isset($_GET['fileSource'] ))?$_GET['fileSource']: "";
$fp = fopen("log_messages.txt", "a");
$date = (new DateTime("NOW"))->format("y-m-d H:i:s");
fwrite($fp, $date."index.php paramIp = " . $paramIp . ", fileSource = ". $fileSource . PHP_EOL);
fclose($fp);
echo $fileSource;
?>
As before, the javascript alert is displayed, with the message
Hello world from javascript!
But the php does not get executed and in FireBug the error is still shown:
ReferenceError: $ is not defined

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
alert("Hello world from javascript!");
debugger;
var myip = "192.168.1.20";
var myfile = "My_file_name";
$.get( 'index.php',{ paramIp: myip, fileSource: myfile },
function( response ) {
if ( response.status == 'success' ) {
alert("PHP returns OK");
}
else {
alert("PHP returns ERROR");
}
}
)
});
</script>
And if you do that....?

Related

How should I access a variable from javascript in PHP to perform some actions?

I have a file named sample.php, in which I have some JS code, and some PHP code. This is some sort of sample snippet of the code I have :
<!DOCTYPE html>
<html lang="en">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<head>
<script type="text/javascript">
var ThunkableWebviewerExtension = {
receiveMessage: function(fxn) {
var callbackFunction = function(event) {
if (typeof fxn === 'function') {
fxn(event.data)
}
};
document.addEventListener('message', callbackFunction, false);
window.addEventListener('message', callbackFunction, false);
}
}
</script>
</head>
<body>
<script type="text/javascript">
var value;
ThunkableWebviewerExtension.receiveMessage(function(message) {
value = message;
});
//sending the value with ajax
$.ajax({
url : "./sample.php", //same file
method : "GET",
data: {"name": value},
success : (res) => {
console.log(value);
},
error : (res) => {
console.log(res);
}
})
</script>
<?php
echo $_GET['name'];
?>
</body>
</html>
The problem is the PHP code doesn't print anything - Are there any error/bug I need to fix? Or is there a better method for accessing a JS variable in PHP?
Thanks! :)
Here's how you can access PHP code within in a <script> (without using AJAX):
<?php
echo"<script>";
include ('javascriptStuff.js');
echo'let x = '.json_encode($phpVariable).';';
echo"</script>";
?>

got error when using javascript ajax json to retrieve php array

My html page is suppose to retrieve the array from the php page and alert the first element in the array. But when I run the html, got the following error, "Uncaught TypeError: Object function (E,F){return new o.fn.init(E,F)} has no method 'parseJSON' " in the console window. I tried to use jQuery.parseJSON(json_data) instead of $.parseJSON(json_data) but still got the same error. How can I fix this?
script.js:
function getArr(){
alert('return sent');
$.ajax({
url: "n1.php",
type: "GET",
success: function(json_data){
var data_array =jQuery.parseJSON(json_data);
var rec = data_array[0];
alert(rec);
alert("GOOD");
},
error: function() {
alert("BAD");
} });
}
newcal.html:
<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8">
<link rel="stylesheet" media="screen" href="demo.css">
<body onload="getArr();">
<div id="rounded"><div id="main" class="container">
<div id="pageContent">
Hello, this is the default content
</div>
</div>
</div>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
</html>
n1.php:
<?php
$output = array("cat","dog");
echo json_encode($output);
?>
parseJSON was added in jQuery 1.4.1 (in 2010)
You are using jQuery 1.3.2 (from 2009), which is too old.
The current version of jQuery 1.x is 1.11 (released this year).
Use a more recent version of jQuery.
You should also tell the browser that you are sending it JSON instead of claiming that your JSON is HTML. (PHP defaults to claiming that anything it outputs through a web server is HTML)
<?php
header("Content-type: application/json");
$output = array("cat","dog");
echo json_encode($output);
?>
Then let jQuery parse it automatically:
success: function(data_array){
// Remove the following line. It will be parsed automatically.
// var data_array =jQuery.parseJSON(json_data);
var rec = data_array[0];

What is wrong with this HTML, JavaScript and JSON code?

I have the following HTML code in a file called test.html. Both the HTML file and the JSON file below are stored on a server within the same directory.
<!DOCTYPE html>
<html>
<head>
<title>Shape Up</title>
<meta name="robots" content="noindex,follow">
<meta name="description" content="">
<meta name="keywords" content="">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script language="JavaScript" type="text/javascript">
function ajax_get_json()
{
var hr = new XMLHttpRequest();
hr.open("GET", "game.json", true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function()
{
if(hr.readyState == 4 && hr.status == 200)
{
var data = JSON.parse(hr.responseText);
var results = document.getElementById("results");
results.innerHTML = "";
for(var obj in data)
{
results.innerHTML += data[obj].title;
}
}
}
hr.send(null);
results.innerHTML = "requesting...";
}
</script>
</head>
<body>
<div id="results"></div>
<script language="JavaScript" type="text/javascript">
ajax_get_json();
</script>
</body>
</html>
It pulls data from a file called game.json which is stored in the same directory.
{
"level_001":
{
"id":001,
"title":"Level 1",
"difficulty":0,
"comments":"this is how you complete level 1"
},
"level_002":
{
"id":002,
"title":"Level 2",
"difficulty":0,
"comments":"this is how you complete level 2"
}
}
The problem is that the results.innerHTML = ""; line is never reached. Why?
There are no errors in the browser, I've checked this on Firefox and on Safari.
According to jsonlint.com your JSON is invalid because of these properties:
"id":001
...
"id":002
You need to either remove the leading zeros:
"id":1
or make the numbers strings:
"id":"001"
For further details see the format rules spelled out at json.org
Presumably the line you mentioned is never reached because JSON.parse() gives an error about the above. (Do you not see an error in the browser's console?)

Uncaught Error: Error calling method on NPObject.

am a newbie to JSON and i just cant's access to the object data.
this is the code :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>ajax </title>
</head>
<body>
<p id="p"></p>
<script type="text/javascript" >
var r = new XMLHttpRequest()
r.open("GET", "d.json");
if(r.readyState ===4 && r.status ===200){
var data = JSON.parse(r.responseText);
var p = document.getElementById("p");
p.innerHTML = data.user;
}
r.send();
</script>
</body>
</html>
and this is the d.json file
{"user":"khaled","age":"20"};
i got that error : "Uncaught Error: Error calling method on NPObject. "
thanks.
if its a flash url ur dealing with then this link will help
npe flash
else
a general discussion in google comm
npe google

JavaScript isn't working on my server

This code is working on other test environment but not on mine.
Do you know why?
I am using Amazon EC2 and Cotendo CDN.
The result I am getting is a blank page.
Thanks in advance!
<html>
<head>
<title>Geo Test</title>
<script type='text/javascript' src='http://www.101greatgoals.com/wp-includes/js/jquery/jquery.js?ver=1.7.1'></script>
<script>
$(document).ready( function() {
$.getJSON( "http://smart-ip.net/geoip-json?callback=?",
function(data){
console.log(data);
var c = data.countryCode;
if(c=="US" || c=="US" ){
document.getElementById('ddd').innerHTML = 'US'; } else {
document.getElementById('ddd').innerHTML = 'Not US';}
/*
this service needs ip
var ip = data.host;
alert(ip);
$.getJSON( "http://freegeoip.net/json/"+ip,
function(data){
console.log(data);
}
);*/
}
);
});?
</script>
</head>
<body>
<div id="ddd"></div>
</body>
</html>
Change this line:
$(document).ready( function() {
to that:
jQuery(document).ready( function($) {
It's necessary, because inside http://www.101greatgoals.com/wp-includes/js/jquery/jquery.js?ver=1.7.1 you've already got a call of jQuery.noConflict(); , so jQuery is not accessible by using the $
...and also remove the ? (see Pointy's comment above)

Categories

Resources