So i already asked some questions here and fixed my problems,but i think they are growing instead of going down,lol.My problem now is i get "Undefined index" error.I will leave picture with the error here.I tried to add variables to define my fsearch.Tried things like
$fsearch = mysqli_escape_string($connect, $_POST['fsearch']);
And more simple like.
$fsearch = $_POST['fsearch'];
But it doesn't work.Here is code.
jQuery(document).ready(function ($) {
$("#food_search").keyup(function(event){
var search_term =$(this).val();
$.ajax({
type:"POST",
url:"/Food-Search",
data:{fsearch:search_term},
success:function(res){
$("#food_search_result").html(res);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!----------------------------------------------------------------
HTML
----------------------------------------------------------------->
<form method="POST">
<p>Търсене на храни: <input type="text" name="fsearch" id="food_search"></p>
</form>
<!----------------------------------------------------------------
PHP
-----------------------------------------------------------------><?php
$hostname = "localhost";
$username = "name";
$password = "password";
$databaseName = "dbName";
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
if (!empty($_POST['fsearch'])) {
$fsearch = mysqli_escape_string($connect, $_POST['fsearch']);
$req = $connect->prepare('SELECT * FROM food_data_bg WHERE title LIKE "%".$fsearch."%"');
$req->execute(array(
'fsearch'=>'%'.$_POST['fsearch'].'%'
));
if($req->rowCount()==0){
echo 'Не бяха намерени резултати!';
}
else{
while($foodsearch=$req->fetch()){
?>
<div class="search-result">
<img src="<?php echo $data['fimage']; ?>" class="fimage"/>
<span class="result-title"><?php echo $data['title'];?></span><br>
<span class="calories-total"><?php echo $data['calories total'];?></span><br>
</div>
<?php
}
}
}
?>
The code is used for searching,it must get the value of #food-search (input field) on every keyup and send it to PHP,which must check for matches in database and print it.(I think i got 1 more mistake by printing result in PHP page and returning it to java to print it in #food_search_result div)
Hope this helps.
PHP Code
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "stackoverflow";
if (!empty($_POST['fsearch'])) {
$fsearch = $_POST['fsearch'];
$mysqli = new mysqli($hostname , $username, $password, $databaseName);
if($mysqli->connect_error)
{
die("$mysqli->connect_errno: $mysqli->connect_error");
}
$query = "SELECT * FROM food_data_bg where title LIKE ?";
$stmt = $mysqli->stmt_init();
if(!$stmt->prepare($query))
{
print "Failed to prepare statement\n";
}
else
{
$searchVar = "%" . $fsearch . "%";
$stmt->bind_param("s", $searchVar);
$stmt->execute();
$result = $stmt->get_result();
if(!$result->num_rows){
echo 'Не бяха намерени резултати!';
}
while ($row = $result->fetch_array())
{
?>
<div class="search-result" style='clear:both; border:1px solid red;'>
<img src="<?php //echo $row['fimage']; ?>" class="fimage"/>
<span class="result-title"><?php echo $row['title'];?></span><br>
<span class="calories-total"><?php echo $row['calories total'];?></span><br>
</div>
<?php
}
}
$stmt->close();
$mysqli->close();
}
HTML Code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function ($) {
$("#food_search").keyup(function(event){
var search_term =$(this).val();
console.log(search_term);
$.ajax({
type:"POST",
url:"Food-Search.php",
data:{fsearch:search_term},
success:function(res){
$("#food_search_result").html(res);
console.log(res);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
});
});
</script>
<!----------------------------------------------------------------
HTML
----------------------------------------------------------------->
<form method="POST">
<p>Търсене на храни: <input type="text" name="fsearch" id="food_search"></p>
</form>
<!----------------------------------------------------------------
PHP
----------------------------------------------------------------->
<div style="border:#FF0000;clear:both; padding:10px;min-height:300px;" id="food_search_result"></div>
Related
Previously I could not know about ajax. therefore I want to ask.
I want to display my wordlist from mysql into a text field but in array. this is the index.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="container" >
<h2>View data</h2>
<h4>Word List : </h4>
<div class="form-group">
<input id="wordlist" type="text" class="form-control" name="wordlist">
</div><br>
<button id="display" title="Generate Word">Generate</button>
<div class="input-single">
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({
type: "GET",
url: "view_ajax.php",
dataType: "html",
success: function(){
$('').html();
}
});
});
});
</script>
And then this is the process.php
<?php
$host = "localhost";
$user = "root";
$password = "";
$dbname = "posts";
$con = mysqli_connect($host, $user, $password, $dbname);
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "select wordlist from word";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('wordlist'=>$row[0]));
}
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
I will be very helpful if you can give an answer. Thank you
Change your PHP loop to something like this:
$result = array();
while($row = mysqli_fetch_array($res)){
$result[]= $row[0];
}
echo json_encode(array('wordlist'=>$result));
Then, in your JS, see below
$(document).ready(function() {
$("#display").click(function() {
/*$.ajax({
type: "GET",
url: "view_ajax.php",
dataType: "json",
success: function(response){
// use the code below in this area
}
});*/
let response = {
"wordlist": ["This", "is", "the", "return", "from", "your", "server"]
} // this is what the response object will look like in your success function above
let output
// normal comma delimited response
output = response.wordlist.join(",");
// or if you want to keep the quotes
output = JSON.stringify(response.wordlist);
output = output.substr(1, output.length - 2);
// use .val() to set the value of an input
$('#wordlist').val(output);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<h2>View data</h2>
<h4>Word List : </h4>
<div class="form-group">
<input id="wordlist" type="text" class="form-control" name="wordlist">
</div><br>
<button id="display" title="Generate Word">Generate</button>
<div class="input-single">
</div>
How I can have image with each result? I search many websites and many tutorials but I can't understand those tutorials.
here is my index
<nav>
<div class="nav-wrapper">
<form>
<div class="input-field">
<input id="vyhledat" class="form-control input-lg" type="search" placeholder="Vyhledat film..." />
<label class="label-icon" for="search"><i class="material-icons">search</i></label>
<i class="material-icons">close</i>
</div>
</form>
</div>
</nav>
here my script
<!-- js -->
<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>
$(document).ready(function(){
$('#vyhledat').autocomplete({
source: "php/vyhledat.php",
minLength: 3,
select: function(event, ui) {
var url = ui.item.id;
if (url != '#') {
location.href = url
}
},
open: function(event, ui) {
$(".ui-autocomplete").css("z-index", 1000)
}
})
});
</script>
And here is my php code
$keyword = trim($_REQUEST['term']); // input
$sugg_json = array();
$json_row = array();
$keyword = preg_replace('/\s+/', ' ', $keyword);
$query = 'SELECT id, nazev, href, obrazek FROM filmy WHERE nazev LIKE :term'; // query
$stmt = $DBcon->prepare( $query );
$stmt->execute(array(':term'=>"%$keyword%"));
if ( $stmt->rowCount()>0 ) {
while($recResult = $stmt->fetch(PDO::FETCH_ASSOC)) {
$json_row["id"] = $recResult['href'];
$json_row["value"] = $recResult['nazev'];
$json_row["label"] = $recResult['nazev'];
array_push($sugg_json, $json_row);
}
} else {
$json_row["id"] = "#";
$json_row["value"] = "";
$json_row["label"] = "Žádný výsledek";
array_push($sugg_json, $json_row);
}
$jsonOutput = json_encode($sugg_json, JSON_UNESCAPED_SLASHES);
print $jsonOutput;
and of course connection to my database.
$DBhost = "localhost";
$DBuser = "jirkua";
$DBpass = "koralek1";
$DBname = "jirkua";
try {
$DBcon = new PDO("mysql:host=$DBhost;dbname=$DBname",$DBuser,$DBpass);
$DBcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $ex){
die($ex->getMessage());
}`
I want to link my json result to the google map. I have a imei_number in the database which is the password of the user. Once the user enter the right password(imei_number in the database), the system will select the longitude and latitude of the imei_number selected and later link it to the google map's longitude and latitude.
The HTML code is:
<form method="post" action="loginServer.php">
<label> Username: </label>
<input type = "text" maxlength = "20" name = "user" id= "user" />
<br />
<label> Password: </label>
<input type = "password" maxlength= "20" name="pass" id= "pass" />
<br />
<input type ="Button" onclick="" value="Clear" />
<input type = "Submit" value = "Login"id= "btn"/>
</p>
</form>
The Google map page is
<script type = "text/javascript">
function LoadMap(){
var mapEdit = {
zoom: 8,
center: new google.maps.LatLng($.getJSON('connect.php', function(data) {
$.each(data, function(key, val) {
$("ul").append(val.latitude);
});
});
,
$.getJSON('connect.php', function(data) {
$.each(data, function(key, val) {
$("ul").append(val.longitude);
});
});
),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), mapEdit);
var marker = new google.maps.Marker({
position: new google.maps.LatLng( $.getJSON('connect.php', function(data) {
$.each(data, function(key, val) {
$("ul").append(val.latitude);
});
});
,
$.getJSON('connect.php', function(data) {
$.each(data, function(key, val) {
$("ul").append(val.longitude);
});
});
),
map: map,
});
marker.addListener('click', function(){
infowindow.open(map, marker);
});
}
</script>
</head>
<body onload = "LoadMap()">
<div id="map" style="width: 400px; height: 500px;"></div>
The connect.php is
<?php
include 'linker.php';
$sql = "SELECT * FROM android_data WHERE $pass = 'imei_number'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
$data[] = $row;
$row["longitude"]);
$row["longitude"]. " - latitude: " . $row["latitude"]. "<br>";
}
} else {
echo "0 results";
}
echo json_encode($data);
mysqli_close($conn);
?>
The linker.php is
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "project_gps";
$user = $_POST['user'];
$pass = $_POST['pass'];
$user = stripcslashes($user);
$pass = stripcslashes($pass);
$conn = mysqli_connect($servername, $username, $password, $dbname);
$user = mysqli_real_escape_string($conn, $user);
$pass = mysqli_real_escape_string($conn, $pass);
if($conn){
echo "connected";
}
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
But they are not all working. Please, what can I do?
I'm trying to insert data without refreshing the page using ajax and php, but the data is not getting inserted into the database.
Here is my code
<?php
require 'validation_class.php';
$obj_menufacture = new Validation_Class();
if (isset($_POST['btn'])) {
$menufacture = $obj_menufacture->menufacture_add($_POST);
}
?>
<!DOCTYPE html>
<html>
<head>
<script src='js/jquery-3.0.0.js'></script>
</head>
<body>
<div id='form_id'>
<form action='' method='post'>
<input type='text' class='m_name' name='m_name' id='m_name' onchange="names('m_name')" onkeyup="names('m_name')"/>
<span style='color:red;' id='m_name_error'></span>
<input type="submit" name='btn' value="submit" id='save'/>
</form>
</div>
<div id='cool'></div>
<style>
.border_input{
border-color:red;
}
.border_input1{
border-color:green;
}
</style>
<script>
$(document).ready(function () {
$('#save').on('click', function (e) {
e.preventDefault();
var m_name = $.trim($('#m_name').val());
var dataString = 'name='+ m_name;
if (m_name === '') {
if (m_name == '') {
$('#m_name_error').html('Please enter your name');
$('#m_name').addClass('border_input');
}
} else {
$.ajax({
url: 'validation.php',
method: 'post',
data:dataString,
success: function () {
$("#form_id").slideUp("slow");
}
});
}
});
});
function names(id) {
var val = $.trim($('#' + id).val());
if (val === '') {
$('#' + id + '_error').html('');
$('#' + id).addClass('border_input');
} else {
$('#' + id + '_error').html('');
$('#' + id).addClass('border_input1');
}
}
</script>
</body>
</html>
Here is my insert code
<?php
class Validation_Class{
public $link;
public function __construct() {
$HOST = "localhost";
$USER = "root";
$PASS = "";
$DATABASE = "store";
$this->link = mysqli_connect($HOST, $USER, $PASS, $DATABASE);
if (!$this->link) {
die('database query problem' . mysqli_error($this->link));
}
}
public function menufacture_add($data) {
$sql = "INSERT INTO menufacture(m_name)VALUES('$data[m_name]')";
if (mysqli_query($this->link, $sql)) {
$menufacture = "Menufacture insert successfully";
return $menufacture;
} else {
die('menufacruere query problem' . mysqli_error($this->link));
}
}
}
please help me what can i do to solve this
<form name="signup" id="reg" action="" method="post"enctype="multipart/form-data">
<input type='text' class='m_name' name='m_name' id='m_name' onchange="names('m_name')" onkeyup="names('m_name')"/>
<span style='color:red;' id='m_name_error'></span>
<input type="submit" name='btn' value="submit" id='save'/>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$("#save").submit(function () {
var form_data = $('#reg').serialize();
$.ajax({
type: "POST",
url: 'setting.php',
data: $('#reg').serialize(),
success: function (data) {
alert('Data save Successfully');
}, error: function () {
alert('Some Internal Error.');
}
});
});`
</script>
settting.php
<?php
include("db_connection.php"); // include connection file
if(isset($_POST)) {
$fname = $_POST['m_name'];
$insert = "INSERT INTO `table_name`(`column_name`)VALUES('".$fname."')";
$insertion = mysqli_query($conn, $insert);
}
?>
$("#save").on("click", function () {
var form_data = $('#reg').serialize();
$.ajax({
type:"POST",
url:'setting.php',
data: $('#reg').serialize(),
success: function(data){
alert("Data save Successfully");
},error: function () {
alert('Some Internal Error.');
}
});
});
I am working on a form which has two fields. One is code and the other is name. I have a validation of checking the existing code in a database. The query for code seems to work fine but the same does not work for name, especially in lower case. Can anyone help me?
Here is my code:
<?php
session_start();
if (!isset($_SESSION["username"])) {
header("Location: unauthorize_access.php");
}
require("includes/dbconnect.php");
if (isset($_POST['save'])) {
$code = $_POST["code"];
$name = $_POST["name"];
{
mysql_query("INSERT INTO `country`(code, `name`)
Values
('$code', '$name')") or die(mysql_error());
print '<script type="text/javascript">';
print 'alert("RECORDS ADDED SUCCESSFULLY")';
header('refresh: 1; country.php');
PRINT '</script>';
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Country</title>
<link rel="stylesheet" type="text/css" href="form2/view.css" media="all">
<script type="text/javascript" src="form2/view.js"></script>
<script type="text/javascript" src="form2/calendar.js"></script>
<script type="text/javascript">
function checkForm()
{
if(country.code.value == "") {
alert("Error: Code cannot be Empty!");
country.code.focus();
return false;
}
if(country.name.value == "") {
alert("Error: Name cannot be Empty!");
country.name.focus();
return false;
}
}
</script>
<script type="text/javascript" src="chk/jquery-1.2.6.min.js"></script>
<SCRIPT type="text/javascript">
<!--
pic1 = new Image(16, 16);
pic1.src = "loader.gif";
$(document).ready(function(){
$("#code").change(function() {
var code = $("#code").val();
if(code.length >= 2)
{
$("#status").html('<img src="loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "check_con.php",
data: "code="+ code,
success: function(msg){
$("#status").ajaxComplete(function(event, request, settings){
if(msg == 'OK')
{
$("#code").removeClass('object_error'); // if necessary
$("#code").addClass("object_ok");
$(this).html(' <img src="tick.gif" align="absmiddle">');
}
else
{
$("#code").removeClass('object_ok'); // if necessary
$("#code").addClass("object_error");
$(this).html(msg);
}
});
}
});
}
else
{
$("#status").html('<font color="red">The code should have at least <strong>2</strong> characters.</font>');
$("#code").removeClass('object_ok'); // if necessary
$("#code").addClass("object_error");
}
});
});
//-->
</SCRIPT>
<SCRIPT type="text/javascript">
<!--
pic1 = new Image(16, 16);
pic1.src = "loader.gif";
$(document).ready(function(){
$("#code").change(function() {
var code = $("#code").val();
if(code.length >= 2)
{
$("#status").html('<img src="loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "check_con.php",
data: "code="+ code,
success: function(msg){
$("#status").ajaxComplete(function(event, request, settings){
if(msg == 'OK')
{
$("#code").removeClass('object_error'); // if necessary
$("#code").addClass("object_ok");
$(this).html(' <img src="tick.gif" align="absmiddle">');
}
else
{
$("#code").removeClass('object_ok'); // if necessary
$("#code").addClass("object_error");
$(this).html(msg);
}
});
}
});
}
else
{
$("#status").html('<font color="red">The code should have at least <strong>2</strong> characters.</font>');
$("#code").removeClass('object_ok'); // if necessary
$("#code").addClass("object_error");
}
});
});
//-->
</SCRIPT><SCRIPT type="text/javascript">
<!--
pic1 = new Image(16, 16);
pic1.src = "loader.gif";
$(document).ready(function(){
$("#name").change(function() {
var code = $("#name").val();
if(code.length >= 0)
{
$("#stat_2").html('<img src="loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "check_con.php",
data: "name="+ name,
success: function(msg){
$("#stat_2").ajaxComplete(function(event, request, settings){
if(msg == 'OK')
{
$("#name").removeClass('object_error'); // if necessary
$("#name").addClass("object_ok");
$(this).html(' <img src="tick.gif" align="absmiddle">');
}
else
{
$("#name").removeClass('object_ok'); // if necessary
$("#name").addClass("object_error");
$(this).html(msg);
}
});
}
});
}
else
{
$("#stat_2").html('<font color="red"><strong>The name cannot be empty</strong></font>');
$("#name").removeClass('object_ok'); // if necessary
$("#name").addClass("object_error");
}
});
});
//-->
</SCRIPT>
</head>
<body id="main_body" >
<img id="top" src="form2/top.png" alt="">
<div id="form_container">
<h1><a>Country</a></h1>
<form id="country" class="appnitro" enctype="multipart/form-data" method="post" onsubmit="return checkForm()">
<div class="form_description">
<h2>Country</h2>
</div>
<table border ="0px" width="100%">
<tr>
<td><label class="description" for="element_1">Code</label></td><td><input id="code" name="code" type="text" maxlength="6" Placeholder="Please enter a code" value=""/></td><td width="400" align="left"><div id="status"></div></td>
</tr>
<tr>
<td><label class="description" for="element_1">Name</label></td><td><input id="name" name="name" size="40" type="text" maxlength="40" Placeholder="Please enter a name" value=""/></td><td width="400" align="left"><div id="stat_2"></div></td>
</tr>
<tr>
<td></td><td ><input type="submit" name="save" value="Save"></td>
</tr>
</table>
</form>
Here is my php code. It works fine for the code field but doesn't work for name.
<?php
$dbHost = 'localhost'; // usually localhost
$dbUsername = 'root';
$dbPassword = '';
$dbDatabase = 'pts_root';
$db = mysql_connect($dbHost, $dbUsername, $dbPassword) or die ("Unable to connect to Database Server.");
mysql_select_db ($dbDatabase, $db) or die ("Could not select database.");
if(isSet($_POST['code']))
{
$code = $_POST['code'];
$sql_check = mysql_query("SELECT * FROM country WHERE code='".$code."'") or die(mysql_error());
if(mysql_num_rows($sql_check))
{
echo '<font color="red">The code <STRONG>'.$code.'</STRONG> is already exist.</font>';
}
else
{
echo 'OK';
}
}
?>
<?php
$dbHost = 'localhost'; // usually localhost
$dbUsername = 'root';
$dbPassword = '';
$dbDatabase = 'pts_root';
$db = mysql_connect($dbHost, $dbUsername, $dbPassword) or die ("Unable to connect to Database Server.");
mysql_select_db ($dbDatabase, $db) or die ("Could not select database.");
if(isSet($_POST['name']))
{
$name = $_POST['name'];
$sql_check = mysql_query("SELECT * FROM country WHERE UPPER(`name`)='".$name."'") or die(mysql_error());
if(mysql_num_rows($sql_check))
{
echo '<font color="red">The name <STRONG>'.$name.'</STRONG> is already exist.</font>';
}
else
{
echo 'OK';
}
}
?>
I'm looking at this particular section:
$sql_check = mysql_query("SELECT * FROM country WHERE UPPER(`name`)='".$name."'") or die(mysql_error());
if(mysql_num_rows($sql_check))
Without reading through all of the rest of your code, and trying to figure out your test case, it might be helpful for you to know that MySQL can use a "case insensitive" collation.
The UPPER function will convert the value stored to uppercase, but that doesn't really affect the comparison if the collation is case insensitive.
You may want to consider using the BINARY operator.
SELECT * FROM country WHERE BINARY UPPER(`name`)= 'FOO'
http://dev.mysql.com/doc/refman/5.5/en/charset-binary-op.html
One quick way to check the collation in MySQL is:
SHOW VARIABLES LIKE 'collation%'
You may see values like this:
utf8_general_ci
latin1_swedish_ci
That _ci at the end of the collation name identify this as a "case insensitive" collation, which basically means 'ABC' = 'abc' evaluates as TRUE.
Collation can be specified at the individual table and column level as well.
For more information, see the MySQL Reference http://dev.mysql.com/doc/refman/5.5/en/charset.html
NOTE: With php 5 and mysqli, do not use a SET names query, rather use the mysqli_set_charset.
http://php.net/manual/en/mysqli.set-charset.php
Change
$name = $_POST['name'];
to
$name = strtoupper($_POST['name']);
so you are comparing the capitalised input with the capitalised field.
You can also do it using like
SELECT * FROM country WHERE `name` like '$name'
Hope this helps