Not fetch data using below code - javascript

I need to get data from mysql database without refreshing the page using jquery ajax. I have a php script which is working fine. However, my JS seems to be having some problem. Here is the jquery script.
index.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.post demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<form action="/" id="searchForm">
<input type="text" name="s" class="s" placeholder="Search...">
<input type="submit" value="Search">
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="item"></div>
<script>
// Attach a submit handler to the form
$( "#searchForm" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
url = $form.attr( "action" );
// Send the data using post
var posting = $.post( 'test.php', { s: $(".s").val() } ).done(function( data ) {
alert( "hiiiiiiiiii" + $(".s").val() );
});
// Put the results in a div
});
$.getJSON(
'fetch_data.php',
's='+$('.s').val(),
function(result){
$('#item').empty();
$.each(result.result, function(){
$('#item').append('<p>'+this['s']+'</p>');
});
});
</script>
</body>
</html>
This code is not working. pleas give me solution how it work?
fetch_data.php
<?php
if(!mysql_connect("localhost","root",""))
{
echo "db connection error : ".mysql_error();
exit;
}
else
{
if(!mysql_select_db("test"))
{
header('Content-type: application/json');
echo "db selection error : ".mysql_error();
exit;
}
}
$sql = "select s from test ";
$res = mysql_query($sql);
$result = array();
while($row = mysql_fetch_array($res)){
echo $row[0];
array_push($result,
array('s'=>$row[0]));
}
echo json_encode(array('result'=>$result));
?>

Related

Use AJAX to prevent refresh when adding to a database

I'm a computer science student, in my sophomore year. For independent learning I decided to create a website in technologies like: SQL, PHP, JS, AJAX, BOOTSTRAP. I'm trying to add content to the database, I use AJAX - I do not want to refresh the page, so I use AJAX. I manage to add the content to a database - but the page refreshes.
I tried to use jquery - when I add content - to prevent refresh. The code works - but there is still a refresh.
The code that accesses the database:
<?php
$DBConInfo = [
'server' => '127.0.0.1',
'username' => 'root',
'password' => '',
'name' => 'test',
];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($DBConInfo['server'],$DBConInfo['username'], $DBConInfo['password'],$DBConInfo['name']);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// php code to Insert data into mysql database from input text
if(isset($_POST['insert']))
{
$hostname = "127.0.0.1";
$username = "root";
$password = "";
$databaseName = "test";
// get values form input text and number
$name = $_POST['name'];
$description = $_POST['description'];
$price = $_POST['price'];
$picture = $_POST['picture'];
// mysql query to insert data
$query = "INSERT INTO `product`(`name`,`description`, `price`, `picture`) VALUES ('$name','$description','$price','$picture')";
$result = mysqli_query($conn,$query);
// check if mysql query successful
if($result) {
echo 'Data Inserted';
}
else{
echo 'Data Not Inserted';
var_dump($conn->error);
}
//mysqli_free_result($result);
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html>
<head>
<title> PHP INSERT DATA </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form id="form-insert" action="" method="post">
<!--<input type="text" name="id" required placeholder="id"><br><br>-->
<input type="text" name="name" required placeholder="Name"><br><br>
<input type="text" name="description" required placeholder="description" min="10" max="100"><br><br>
<input type="text" name="price" required placeholder="price"><br><br>
<input type="text" name="picture" required placeholder="picture" min="10" max="100"><br><br>
<input id="submit-insert" type="submit" name="insert" value="Add Data To Database">
</form>
<span id="result"></span>
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src ="js/DBscript.js" type="text/javascript"></script>
</body>
</html>
Using ajax - to prevent refresh:
$("#submit-insert").click( function() {
$.post( $("#form-insert").attr("action"),
$("#form-insert :input").serializeArray(),
function(info){ $("#result").html(info);
});
//clearInput();
});
$("#form-insert").submit( function() {
return false;
});
function clearInput() {
$("#form-insert :input").each( function() {
$(this).val('');
});
}
After submitting the form you have to use event.preventDefault()
$("#submit-insert").click( function(event) {
event.preventDefault();
});
$('#form-insert').on('submit', function (event) {
event.preventDefault();
$.ajax({
type : 'post',
url : 'NameOfPHPFile.php',
data : $('#form-insert').serialize(),
success : function () {
alert('form was submitted');
}
});
});

How to solve this "Uncaught ReferenceError: $ is not defined"

I have some code where I need to update a column of a table (MySQL) calling another php file without leaving the page where some tables might allow inline editing.
I have a point in the php echoing of the page, where an icon can be clicked to save input. The code at that point is:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?php
$sql = "SELECT * FROM table WHERE a_column='certain_value'";
if (mysqli_query($conn, $sql)) {
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$note = $row["note"];
$code = $row["code"];
}
}
}
// some tabled elements not relevant for the issue
echo "<input type='text' id='note_1' name='note_1' value=$note readonly>";
echo "<input type='text' id='new_note' name='new_note'>";
echo "<img src='icon_to_click.png' id='icon_to_click' name='icon_to_click' >";
?>
<script type="text/javascript">
$(document).ready(function() {
$('#icon_to_click').click(function() {
var note_orig = document.getElementById('note_1').value;
var code_val = '<?php echo "$code" ?>';
var note_new = document.getElementById('new_note').value;
if (note_new != note_orig) {
$.ajax({
type: 'POST',
url: 'update_notes.php',
data: {'code': code_val, 'note': note_new},
success: function(response){
document.getElementById('note_1').value = note_new;
}
});
}
});
});
The relevant code of update_notes.php is:
<?php
// connection
$unsafe_note = $_POST["note"];
$code = $_POST["code"];
require "safetize.php"; // the user input is made safe
$note = $safetized_note; // get the output of safetize.php
$sqlupdate = "UPDATE table SET note='$note' WHERE code='$code'";
if (mysqli_query($conn, $sqlupdate)) {
echo "Note updated";
} else {
echo "Problem in updating";
}
// close connection
?>
Now when I run the code and look at the tool, it gives me the error: Uncaught ReferenceError: $ is not defined, linking the error to this line of the previous js code:
$(document).ready(function() {
So, how can I fix that?
It means that you tried to use Jquery in your Javascript Code without calling Jquery Library or the code is called without the library was fully loaded.
I notice :
That you haven't closed your script tag
You use Jquery so you can use $('#id_name') to select element by Id instead of document.getElementById('note_1')
Get element value by using Element.val() instead of Element.value
Try to edit your code like this
<?php
$sql = "SELECT * FROM table WHERE a_column='certain_value'";
if (mysqli_query($conn, $sql)) {
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$note = $row["note"];
$code = $row["code"];
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Some title</title>
</head>
<body>
<form method="post" accept-charset="UTF-8">
<input type='text' id='note_1' name='note_1' value=<?= $code ?> readonly>";
<input type='text' id='new_note' name='new_note'>";
<img src='icon_to_click.png' id='icon_to_click' name='icon_to_click' >";
</form>
<script>
$(document).ready(function() {
$('#icon_to_click').click(function() {
var note_orig = $('#note_1').val();
var code_val = '<?= $code ?>';
var note_new = $('#new_note').val();
if (note_new != note_orig) {
$.ajax({
type: 'POST',
url: 'update_notes.php',
data: {'code': code_val, 'note': note_new},
success: function(response){
$('#note_1').val() = note_new;
}
});
}
});
});
</script>
</body>
</html>
Hey I have faced same error a day before,this is because you have missed using a jquery library script that is needed. please try using some Updated Jquery CDN . :) It will definitely help
OR
include the jquery.js file before any jquery plugin files.

PHP ajax search results in mucking up my page

Hi guys its my first time trying out a live ajax search for my site. I am new to php so any help on this matter would be great. I was following some tutorials here and there and trying to make it work, but every time i press search no results come up at all. Any help on this matter would be great.
Code:
<?php
mysql_connect("localhost","root","") or die ("could not connect");
mysql_select_db("reg") or die ("could not find db");
if (isset($_POST['search_term']) == true && empty($_POST['search_term']) == false) {
$search_term = mysql_real_escape_string($_POST['search_term']);
$query = mysql_query("SELECT `ingName` FROM `ing` WHERE `ingName` LIKE '$search_term%'");
while(($row = mysql_fetch_assoc($query)) !== false) {
echo '<li>',$row['ingName'],'</li>';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="container">
<input type="text" class="searchFunction"> <input type = "submit" value ="Search">
<div class = "dropdown">
<ul class = "result">
</ul>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.searchFunction').keyup(function() {
var search_term = $(this) .attr('value');
$.post('build.php', {search_term:search_term}, function(data) {
$('.result').html(data);
$('.result li').click(function() {
var result_value = $(this).text();
$('.searchFunction').attr('value', result_value);
$('.result').html('');
});
});
});
});
</script>
</body>
</html>
Again i am so new to this, so i am just trying to build my knowledge around this area. Any help in solving this big problem out would be great
P.S i know about the sql injections :) but one step at a time for now x
As has been pointed out - the method used so far is at risk of sql injection so before getting committed to using the now deprecated mysql suite of functions you would be wise to read up on and implement mysqli which, when you employ prepared statements will offer significant protection from malevolent sql injection attacks.
As your ajax query is being sent to the same page ( by the looks of code posted ) one important thing to do is exit from the phpafter sending the response - otherwise you end up sending the entire page ( which would also be badly formed as there would be content outside the html tags ) and I suspect this is not your desired goal.
The ajax function looks, to my untrained eye, ok but as I don't use jQuery I might well be wrong and have missed something important.
<?php
/*
as the rest of the page doesn't use a db connection,
only load the db conn if the page is requested via post
*/
if( $_SERVER['REQUEST_METHOD']=='POST' ){
/* assign db connection to a variable */
$conn=mysql_connect("localhost","root","") or die ("could not connect");
mysql_select_db("reg") or die ("could not find db");
/* empty() does an implied `isset` */
if ( !empty( $_POST['search_term'] ) ) {
$search_term = mysql_real_escape_string( $_POST['search_term'] );
/*
You ought to look at using mysqli ( prepared statements )
rather than the now deprecated `mysql_*` functions
*/
$query = mysql_query( "SELECT `ingName` FROM `ing` WHERE `ingName` LIKE '$search_term%'", $conn );
if( $query ){/* only send response if the query succeeds */
while( $row = mysql_fetch_assoc( $query ) ) {
echo '<li>',$row['ingName'],'</li>';
}
}
}
mysql_close( $conn );
/* make sure that the rest of the page is not sent back with the response data */
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Gotta have a title!</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready( function() {
$('.searchFunction').keyup( function( event ) {
/* I could not get this to work - I don't know what this is doing as I don't use jQuery */
/*var search_term = $(this).attr('value');*/
/* this however does work */
var el=event.target || event.srcElement;
var search_term=el.value;
/* maybe better to search after a few letters have been added? */
if( search_term.length < 2 )return;
/* it appears you are posting to the same page */
$.post( document.location.href, { search_term:search_term }, function( data ) {
$('.result').html( data );
$('.result li').click( function( event ) {
var result_value = $(this).text();
$('.searchFunction').attr('value', result_value );
$('.result').html('');
});
});
});
});
</script>
</head>
<body>
<div class="container">
<input type="text" name='search_term' class="searchFunction">
<input type="submit" value="Search">
<div class="dropdown">
<ul class="result"></ul>
</div>
</div>
</body>
</html>
Full, working example
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
if ( !empty( $_POST['search_term'] ) ) {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
/* using lower() helped account for vagueries in spelling */
$sql='select * from `maps` where
lower( `location_name` ) like lower( "%'.$_POST['search_term'].'%" );';
$res=$db->query( $sql );
if( $res ){
while( $rs=$res->fetch_object() ){
echo "<li>".$rs->location_name."</li>";
}
}
}
exit();
}
?>
<!doctype html>
<html lang='en'>
<head>
<title>Gotta have a title!</title>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script>
<script type='text/javascript'>
$( document ).ready( function() {
$('.searchFunction').keyup( function( event ) {
var search_term=this.value;
/* maybe better to search after a few letters have been added? */
if( search_term.length < 5 )return;
/* it appears you are posting to the same page */
$.post( document.location.href, { search_term:search_term }, function( data ) {
$('.result').html( data );
$('.result li').click( function( event ) {
var result_value = $(this).text();
$('.searchFunction').attr( 'value', result_value );
$('.result').html('');
});
});
});
});
</script>
</head>
<body>
<div class='container'>
<input type='text' name='search_term' class='searchFunction'>
<input type='submit' value='Search'>
<div class='dropdown'>
<ul class='result'></ul>
</div>
</div>
</body>
</html>
You can try writing your query without the quotations ie:
$query = mysql_query("SELECT ingName FROM ing WHERE ingName LIKE '$search_term%'");
and you can also loosen your search by using '%$search_term%' instead of '$search_term'.
Another possible issue is the mysql_connect(). I was using that function and it did not work for me so I resolved to the mysqli_connect() function which worked for me.
Some more advise, you do not need the ==true and you can also you can use
!empty($_POST['search_term']).
Once you are through learning that you can also try the PDO function which is far much better than initiating your own connection.
You initiate a PDO connection like this.
$dbh1 = new PDO('mysql:dbname=dbname;host=127.0.0.1', 'username', 'dbpass');
Then you can search like this. - using the initialized connection.
$query = "SELECT ingName from ing WHERE ingName LIKE %$search_term%";
$stmt = $dbh1->prepare($query);
$stmt->execute();
$allRows = count($stmt);
$row = $stmt->fetch(PDO::fetch_assoc);
foreach($row as $one){
echo "<li>".$one['ingName']."</li><br>";
}
Cheers!

jQuery ajax response not displaying when returning to current page

I'm attempting to post some data back to the same page through ajax. In the example below the $name variable is not being updated in my page once the button is clicked. However, if I look at the console log of the response from ajax (using firebug) it shows the correct html, with the name inserted (i.e. <div>Matthew</div>) - the page just isn't being updated with this response. Any ideas for how to fix this would be greatly appreciated.
The code I have is:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<?php
$name = "A name";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name = "No name!";
}
else{
$name = $_POST["name"];
}
}
?>
<script>
$(document).ready(function(){
$("button").click(function(){
var mydata = {name: "Matthew"};
$.ajax({
type: 'POST',
data: mydata,
success: function(data){
console.log(data);
}
});
});
});
</script>
<button>Send an HTTP POST request to a page and get the result back</button>
<div id="name">
<?php echo $name;?>
</div>
</body>
</html>
It is because <?php echo $name;?> does not run again when doing the ajax call. You have to replace the content of the div in the success function like this:
success: function(data){
$("div").html(data);
}

.load page with form variables

I want to load a page with variables from a form and it seems it doesn't get my select value. I'm new to JavaScript and I need this instead doing a serialize to get values and then use .load().
Here is my code:
<?php
include('dbconfig.php');
$id=$_GET['id'];
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function filtreaza_tip () {
var tip = document.getElementById("tip").value;
var id_local= document.getElementById("id_local").value;
$( "#tipuri_rezervare" ).load("select_tip_rezervare.php?id="+id_local+"&tip="+tip);
}
</script>
</head>
<body>
<form id="tip" method="post">
<input type="hidden" name="id_local" id="id_local" value="<?php echo $id;?>">
<select name="tip" id="tip" onchange="filtreaza_tip();">
<option value="0">Selectati Tipul</option>
<?php
$stmt = $dbh->prepare("SELECT *
FROM Tip_Rezervare
INNER JOIN Local ON Local.ID_Local=:id_local
INNER JOIN Leg_Tip_Local ON Tip_Rezervare.ID_Tip=Leg_Tip_Local.ID_Tip and Leg_Tip_Local.ID_Local=:id_local");
$stmt->bindParam(':id_local', $id, PDO::PARAM_INT);
$stmt->execute() ;
while ($row = $stmt->fetch()) {
$local=$row['Denumire_Local'];
echo '<option value="'.$row['ID_Tip'].'">'.$row['Nume'].'</option>';
}
echo'</select>';
?>
<div id="tipuri_rezervare">
</div>
</body>
</html>
I have a working one with serialize but I don't want that. Here is the working code:
function filtreaza_tip ()
{
var datastring = $("#tip").serialize();
$.ajax({
type: "POST",
url: "tip_rezervare.php",
data: datastring,
success: function(data) {
$( "#tipuri_rezervare" ).load('select_tip_rezervare.php?',data);
}
});
}
Your form id and dropdown id are same.
Thats the reason you are getting the issue.
Change the ids it will work fine.
Load uses POST method so you can just do this:
var tip = document.getElementById("tip").value;
var id_local= document.getElementById("id_local").value;
$( "#tipuri_rezervare" ).load("select_tip_rezervare.php, {tip: tip, id: id_local});
Then you can get your values on your select_tip_rezervare.php page with $_POST['tip'] and $_POST['id'].
Use the jquery method $.val() like that :
$("#tip").val(); // Return the input / select value of the selector
Check the jQuery Api : http://api.jquery.com/val/

Categories