$ is not defined in JQuery [duplicate] - javascript

This question already has answers here:
JQuery - $ is not defined
(36 answers)
Closed 7 years ago.
Let me show you all, i put this code in a file called consultas.php
CONSULTAS.PHP
This file shows the table with data, at the end of column called folio id="'.$row["folio"].'" when i clicked there this shows me and towards to VISTAPREVIA.PHP for more data about this folio but in paging #1 it works very well and now when i'm going to paging #2 i clicked again and doesn't work because doesn't show me anything, the error says me: Uncaught ReferenceError: $ is not defined
<script type="text/javascript">
$(document).ready(function() {
var table = $('#registros').DataTable({
"paging": true
});
//new $.fn.dataTable.AutoFill( table );
$('.back').on("click", function(event)
{
event.preventDefault();
location.reload();
});
$('.modificar').on("click", function(event)
{
event.preventDefault();
//Cargamos el contenido del enlace
var f = $(this).attr('id');
$('#mainContainer').load(this.href, {folio: f}, function(){
});
});
$('.vistaprevia').on("click", function(event)
{
event.preventDefault();
//Cargamos el contenido del enlace
var f = $(this).attr('id');
$('#mainContainer').load(this.href, {folio: f}, function(){
});
});
$('.detalle').on("click", function(event)
{
event.preventDefault();
var f = $(this).attr('id');
$('<div></div>').load(this.href, {folio: f}).modal();
});
});
</script>
REGRESAR ATRÁS
<h1 class="titPer">CONSULTA DE LA TABLA</h1>
<div class="tabla">
<table id="registros" class="display" cellspacing="0">
<thead>
<tr>
<th>Folio</th>
<th>Estatus</th>
<th>Punto de Venta</th>
<th>Usuario</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysql_fetch_array($consulta)) {
?>
<tr>
<td><?=$row['folio']?></td>
<td><?=$row['estatus']?></td>
<td><?=$row['punto_venta']?></td>
<td><?=$row['usuario']?></td>
<td>
<?php
if($_SESSION['permisos'] == 'VENDEDOR' || $_SESSION['permisos'] == 'JEFESUC' || $_SESSION['permisos'] == 'EMBARQUES'){
echo '
<center>
<a class="modificar icon-pencil" href="includes/vistaPrevia.php" id="'.$row["folio"].'"></a>
|
<a class="detalle icon-eye-plus" href="includes/lightbox.php" id="'.$row["folio"].'"></a>
</center>
';
}else{
echo'
<center>
<a class="vistaprevia icon-eye-plus" href="includes/vistaPrevia.php" id="'.$row["folio"].'"></a>
</center>
';
}
?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
VISTAPREVIA.PHP
<?php session_start(); ?>
<head>
<link href='http://fonts.googleapis.com/css?family=PT+Sans+Narrow' rel='stylesheet' type='text/css'>
</head>
REGRESAR ATRÁS
<h1 class="titPer">ACTUALIZACIÓN DE DATOS</h1>
<!-- <form action="includes/"></form> -->
<?php
if($_SESSION['permisos'] == 'CALIDAD'){
include('upRegCal.php');
}
?>
<form action="includes/edit.php" enctype="multipart/form-data" id="formAct" method="POST" name="enviarForm">
<?php
if($_SESSION['permisos'] == 'VENDEDOR' || $_SESSION['permisos'] == 'JEFESUC' || $_SESSION['permisos'] == 'EMBARQUES'){
include('upRegUser.php');
}
if($_SESSION['permisos'] == 'ADMINISTRADOR'){
//include('upRegCal.php');
echo "Hola Administrador";
}
?>
</form>
last
INDEX.PHP
i have to assure this part because i put the correct Jquery scripts but i don't know why and i couldn't find the problem and yes i use the Datables Scripts
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8"/>
<title>Bienvenido</title>
<script src="js/jquery-1.11.2.js"></script>
<script src="js/funciones.js"></script>
<script src="libs/datatables/media/js/jquery.dataTables.js"></script>
<script src="libs/datatables/extensions/AutoFill/js/dataTables.autoFill.js"></script>
<script type='text/javascript' src='js/jquery.simplemodal.js'></script>
<script type='text/javascript' src='js/basic.js'></script>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,300,400,600,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/normalize.css" type="text/css"/>
<link rel="stylesheet" href="css/estilos.css" type="text/css"/>
<link rel="stylesheet" href="css/estilosForm.css" type="text/css"/>
<link type='text/css' href='css/basic.css' rel='stylesheet' media='screen' />
<link rel="stylesheet" href="libs/datatables/media/css/jquery.dataTables.css" type="text/css"/>
<link rel="stylesheet" href="libs/datatables/extensions/AutoFill/css/dataTables.autoFill.css" type="text/css"/>
</head>
<body>
<div class="fondoHeader"></div>
<header class="shadow">
<nav>
<?php
if(isset($_SESSION['usuario']))
include('includes/btnSiSession.php');
else
include('includes/btnNoSession.php');
?>
</nav>
</header>
<div id='mainContainer'>
<?php
include('includes/bienvenido.php');
if(isset($_SESSION['usuario'])){
echo "<script language='JavaScript'>";
// echo "document.getElementById('login').style.display='none'";
echo "document.getElementById('login').style.visibility='hidden'";
echo "</script>";
}
else{
echo "<script language='JavaScript'>";
// echo "document.getElementById('login').style.display='block'";
echo "document.getElementById('login').style.visibility='visible'";
echo "</script>";
}
?>
</div>
<div class="clear"></div>
<footer>
<?php
include('includes/footer.php');
?>
</footer>
</body>
</html>
UPDATE
i put this code jQuery CDN script
<script src="ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var table = $('#registros').DataTable({
"paging": true
});
//new $.fn.dataTable.AutoFill( table );
$('.back').on("click", function(event)
{
event.preventDefault();
location.reload();
});
$('.modificar').on("click", function(event)
{
event.preventDefault();
//Cargamos el contenido del enlace
var f = $(this).attr('id');
$('#mainContainer').load(this.href, {folio: f}, function(){
});
});
$('.vistaprevia').on("click", function(event)
{
event.preventDefault();
//Cargamos el contenido del enlace
var f = $(this).attr('id');
$('#mainContainer').load(this.href, {folio: f}, function(){
});
});
$('.detalle').on("click", function(event)
{
event.preventDefault();
var f = $(this).attr('id');
$('<div></div>').load(this.href, {folio: f}).modal();
});
});
</script>

In consultas.php, you must include JQuery (<script src="js/jquery-1.11.2.js"></script>) before using it, before your <script>.
In web, each page is different, then you must add jQuery in each one.
example
<script src="js/jquery-1.11.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
/* ... */
});
</script>

In some cases you have to use jQuery instead of $.
2nd option: jQuery(document).ready(function($) {
After this you can use $ as synonym for jquery.

This error is because you're missing the JQuery library. If you are including your Javascript libraries(including JQuery) at the bottom of your page(footer), you can either
Include the JQuery library at the top of the page
OR
make your Javascripts functions into a common js file and include it at the footer just below the Jquery include.
Here is the link to Jquery CDN

Related

jquery add 1 to variable on click then insert to database

I want to have 2 buttons on a page. If u click button "addMe", then I want to add 1 to a variable? (theCount). The other button (InsertDB) I want to add "theCount" into my db.
Im able to add data to my db, but not "theCount", probly because its a "div id" and I dont know how to do it. I have 3 files: index.php, addscript.js and insert.php
Here is my script:
index.php:
<?php
include "insert.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add 1 on click, then add sum to db</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button id="addMe">Add 1</button>
<div id="theCount"></div>
<form method="post">
<button id="InsertDB">Add to DB</button>
</form>
</body>
</html>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
<script src="addscript.js"></script>
addscript.js:
var counter = 0;
$(document).ready(function() {
$("#InsertDB").click(function(){
var theCount= $("#theCount").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "theCount=" + theCount,
success: function(data) {
alert("Added to DB");
}
});
});
$("#addMe").click(function(){
counter++;
$("#theCount").text(counter);
});
});
insert.php:
<?php
include "db.php";
$theCount=$_POST['theCount'];
$sql = "INSERT INTO `mat`( `polse`)
VALUES ('$theCount')";
if (mysqli_query($conn, $sql)) {
echo "Craig is Satoshi";
}
else {
echo "Error";
}
mysqli_close($conn);
?>
#theCount is a <div>:
<div id="theCount"></div>
And a <div> doesn't have a value, so this won't work:
var theCount= $("#theCount").val();
Instead, get the text of the element:
var theCount= $("#theCount").text();
Much in the same way that you already set the text of the element:
$("#theCount").text(counter);

Cannot implement autocomplete from mysql

I am struggling to implement autocomplete on my page as no results are showing from the database.
Below is the code on the index.php page
<head> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script>
$(function() {
$("#tags").autocomplete({
source: "autocomplete.php"
});
});
</script> </head> <body> <label for="tags">Select Student</label> <div><input id="tags" type="text" name="tags" /> </div></body>
The autocomplete.php file looks like this...
<?php include("session.php");
session_start();
$description_arr = array();
$stmt = "select case
When (login.name is null or login.name='') and (login.surname is null or login.surname='')
then login.username
Else login.name + ' ' + login.surname
End as user_profile
from my_students
inner join login
on stud_id = login.id
where my_students.id = '$login_id'";
$ses_stmt = mysqli_query($conn, $stmt);
while($row = mysqli_fetch_array($ses_stmt)){
array_push($description_arr,$row['user_profile']);}
echo json_encode($description_arr);
?>

How to connect HTML page to MySQL Workbench Server using JavaScript,Ajax and PHP?

I have an HTML page where we enter the name of a movie and if that movie is present in the database,then the name is displayed. I am trying to connect to the database using JavaScript, Ajax and PHP. The database is in the MySQL Workbench Server.
This is what I have done:
pc.html
<html>
<head>
<script type="text/javascript">
function Search_Data()
{
var httpr = new XMLHttpRequest();
var movie_name=document.getElementById("moviename").value;
console.log(movie_name);
httpr.open("GET","get_data.php",true);
httpr.send();
httpr.onreadystatechange = function()
{
if(this.readyState==4 && this.status==200)
{
alert(this.responseText);
}
}
}
</script>
<body>
<input type="text" name="moviename" id="moviename" placeholder="Enter a movie...">
<br/>
<input type="button" name="search" value="Search" onclick="Search_Data()">
<br/>
<span id="response"></span>
</body>
</head>
</html>
get_data.php
(Below code is a trial code to see if its working)
<?php
echo "Hello World"
?>
In the browser,the result I am getting is:
The files are in the following location:
C:\Users\Admin\AppData\Roaming\MySQL\Workbench\scripts
The entire code is getting displayed instead of just "Hello World".I am new to web development and PHP and I am not sure what seems to be the problem.
what are you using is ajax with normal java-script i suggest to use jquery ajax and this is a full example how to connect it to php and how to get the value or list
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<button type="button" name="search" id="search" class="btn btn-info">Search</button>
<td width="90%"><span id="employee_name"></span></td>
second
<input type="input" id="inputs" value="submit">
<p id="email"></p>
<p id="pass"></p>
<p id="permission"></p>
<script>
$(document).ready(function(){
$('#search').click(function(){
var val = document.getElementById("inputs").value;
var id= $('#employee_list').val();
setInterval(function(){
$.ajax({
url:"db.php",
method:"POST",
data: {val : val},
dataType:"JSON",
success:function(data)
{
$('#email').text(data[val].email);
$('#pass').text(data[val].pass);
$('#permission').text(data[val].perm);
}
})
}, 1000);
});
});
</script>
</body>
</html>
the php file
<?php
$items = array();
$url="localhost";
$user= "root";
$pass="";
$dbname="test";
$value= 0;
if(isset( $_POST['val'])){
$value= $_POST['val'];
}
$num=0;
$connect=mysqli_connect($url,$user,$pass,$dbname);
$result="SELECT email,pass,permission FROM test where id=$value";
$sql=mysqli_query($connect,$result);
while($row=mysqli_fetch_assoc($sql) ){
/* add a new item */
$num++;
$items[$value] = array(
'email' => $row['email'],
'pass' => $row['pass'],
'perm' => $row['permission']
);
}
$json_response = json_encode($items);
echo $json_response;
?>

using ajax call to empty the div

Making a ajax, so when i click on this Link1 Button, i need to empty the contents in the products_list div
<button type="w3-button">Link1</button>
Please help me on how to make a ajax call when clicking link1 button it empty the products in product_list
The below code contains a javascript to clear the contents of products_list but it do not work
PHP File
<?php
session_start(); //start session
include("config.inc.php"); //include config file
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Stores</title>
<link href="style/style1.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
</head>
<body>
<div align="center">
<h3>Products</h3>
</div>
<script>
$(document).on("click", ".w3-button", function() {
$('.products-wrp').html('')
// $("#products_list").html();
});</script>
<?php
//List products from database
$results = $mysqli_conn->query("SELECT product_name, product_desc, product_code, product_image, product_price FROM products_list");
//Display fetched records as you please
$products_list = '<ul id ="products_list" class="products-wrp">';
while($row = $results->fetch_assoc()) {
$products_list .= <<<EOT
<li>
<form class="form-item">
<h4>{$row["product_name"]}</h4>
<div>
<img src="images/{$row["product_image"]}" height="62" width="62">
</div>
<div>Price : {$currency} {$row["product_price"]}<div>
</form>
</li>
EOT;
}
$products_list .= '</ul></div>';
echo $products_list;
?>
</body>
</html>
Check Code below that will empty the div On Failure on Ajax Request -
function getFailOutput() {
$.ajax({
url:'myAjax.php',
success: function (response) {
console.log(data, response);
$('#output').html(response);
},
error: function () {
//Empty Output Div ON Error Returned From Ajax Request
$('#output').html('');
},
});
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
test success | test failure
<div id="output">waiting for action</div>

validating answer submitted to database

<?php
include ("dbFunctions.php");
$query = "SELECT * FROM two_three";
$result = mysqli_query($link, $query);
mysqli_close($link);
?>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" href="CSS/main.css" type="text/css"/>
<link rel="stylesheet" href="CSS/easy.css" type="text/css"/>
<title> Easy Game 1 </title>
<center>
<h1> Easy Game 1 </h1>
<h2> Click the image the number of times to get the answer! </h2>
<div class="border_solid">
<div id="timer"></div>
</div>
<hr>
</center>
</head>
<body>
<center>
<form method="post" id="validate">
<div id="display"><script type="text/javascript">document.write(count);</script></div>
<img src="image/ufo.png" class="ufo" onclick="add()"><br>
<input type="button" class="submit" value="submit" name="submit"/>
</form>
</center>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$questID = $row['two_three_id'];
$factor1 = $row['factor1'];
$factor2 = $row['factor2'];
$answer = $row['answer'];
?>
<div class="image-questionid"><u>Question <?php echo $questID; ?></u></div>
<div class="image-questionfactor1"><?php echo $factor1; ?></div>
<div class="image-betweenfactor">X</div>
<div class="image-questionfactor2"><?php echo $factor2; ?></div>
<div class="image-questionequals">= ?</div>
<?php
break;
}
}
?>
</body>
<script type="text/javascript">
var count = 0;
function add() {
count++;
document.getElementById('display').innerHTML = count;
}
var myVar = setInterval(function () {
myTimer()
}, 1000);
var d = 0;
function myTimer() {
document.getElementById("timer").innerHTML = d++;
}
</script>
</html>
So basically this is the code I've done so far, I'd like to do a validation to check the count after the user clicks on submit, and check the count with the database answer. Is there anyone out there who can help me out?
in the form use the method in tag form onsubmit ="validation". after you need to implement the validation method in javascript and make a ajax request (in validation) to another php form, in that php form u make the query to db and returning the number of click you need to do. o you need to implement jquery library.
function validation(){
$.ajax({
url: "your_php_requesting_to_db.php",
success: function(data){
if(data == numberofclicks){
return true;
}else{
return false;
}
}
});
}
Here is the new code, im new in this foro so i don't know how to put in a comment the code, im assumng you got the total clicks you need to do, answering your question of timmer here is a little bit of doc
http://www.w3schools.com/js/js_timing.asp
<?php
include ("dbFunctions.php");
$query = "SELECT * FROM two_three";
$result = mysqli_query($link, $query);
mysqli_close($link);
?>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" href="CSS/main.css" type="text/css"/>
<link rel="stylesheet" href="CSS/easy.css" type="text/css"/>
<title> Easy Game 1 </title>
<center>
<h1> Easy Game 1 </h1>
<h2> Click the image the number of times to get the answer! </h2>
<div class="border_solid">
<div id="timer"></div>
</div>
<hr>
</center>
</head>
<body>
<center>
<form method="post" id="validate" onsubmit="validate()">
<div id="display">
<script type="text/javascript">document.write(count);</script>
</div>
<img src="image/ufo.png" class="ufo" onclick="add()"><br>
<input type="hidden" id="totalClicks" value="<?php /*IF U GOT THE NUMBER OF CLIC FROM BD PUT IN THERE LIKE ECHO $NUMCLICKS */ ?>"/>
<input type="hidden" id="countClic" value="0" />
<input type="button" class="submit" value="submit" name="submit"/>
</form>
</center>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$questID = $row['two_three_id'];
$factor1 = $row['factor1'];
$factor2 = $row['factor2'];
$answer = $row['answer'];
?>
<div class="image-questionid"><u>Question <?php echo $questID; ?></u></div>
<div class="image-questionfactor1"><?php echo $factor1; ?></div>
<div class="image-betweenfactor">X</div>
<div class="image-questionfactor2"><?php echo $factor2; ?></div>
<div class="image-questionequals">= ?</div>
<?php
break;
}
}
?>
</body>
<script type="text/javascript">
var count = 0;
function add() {
count++;
document.getElementById('display').innerHTML = count;
document.getElementById('countClic').value=count;
}
var myVar = setInterval(function () {
myTimer()
}, 1000);
var d = 0;
function myTimer() {
document.getElementById("timer").innerHTML = d++;
}
function validate(){
var totalClics = document.getElementById('totalClicks').value=count;
var clicksCount = document.getElementById('countClic').value=count;
if(totalClics == clicksCount){
return true;
}else{
return false;
}
}
</script>
</html>

Categories

Resources