This is my HTML Code
<input type="text" class="form-control" id="stfmail" name="staffmail" placeholder="E-Mail" required="required"><span id="result"></span>
In jQuery Ajax
<script type="text/javascript">
$(document).ready(function(){
$("#stfmail").keyup(function() {
var name = $(this).val();
if(name.length > 1)
{
$("#result").html('checking...');
$.ajax({
type : 'POST',
url : '../include/check_availability.php',
data : $(this).serialize(),
success : function(data)
{
$("#result").html(data);
}
});
return false;
}
else
{
$("#result").html('');
}
});
});
</script>
PHP
if($_POST)
{
$username = $_POST['name'];
$ob->useravailable($username);
}
public function useravailable($username)
{
$stmt=$this->conn->prepare("select user_name from users where user_name=:uname and delet='0'");
$stmt->execute(array(':uname'=>$username));
if($stmt->rowCount()>0)
{
echo "<span style='color:brown;'>Sorry username already taken !!!</span>";
}
else
{
echo "<span style='color:green;'>available</span>";
}
}
Here i type a username..but in useravailable function only else part is working.. I type Existing username it works the else part available message is shown..
Please help me
thanks
<script type="text/javascript">
$(document).ready(function(){
$("#stfmail").keyup(function() {
var name = $(this).val();
if(name.length > 1)
{
$("#result").html('checking...');
$.ajax({
type : 'POST',
url : '../include/check_availability.php',
data : $(this).serialize(),
success : function(data)
{
$("#result").html(data);
if(data) {
$(".redbold").html('already this username is there ').show();
$("#username").focus();
}
}
});
return false;
}
else
{
$("#result").html('');
}
});
});
</script>
if($_POST)
{
$username = $_POST['name'];
$query = mysql_query("SELECT user_name from users where user_name ='".$username ."' ", $con);
while ($row = mysql_fetch_assoc($query)) {
echo $row['user_name '];
}
}
Related
I'm having trouble implementing if statement in ajax success function.
<?php
include('../Config/config.php');
$myquery = "SELECT * FROM voters WHERE Precinct = '".$_POST['precinct']."'";
$execute = mysqli_query($mysqli, $myquery);
if (mysqli_num_rows($execute) >= 1)
{
echo "Precinct is full.\n Recheck precinct number.";
}
?>
function checkerprecinct() {
var precinct = $("#precinct").val();
$.ajax({
type: "POST",
url: "precinctchecker.php",
data: "precinct=" + precinct,
success: function(data) {
console.log(data);
if (data === "") {
alert("Data is empty!");
} else {
alert(data);
}
}
});
}
I would like to use this as a validation.
I want to alert the user if the sent data contains similar data from the database.
try this code
change with your code
PHP Code:
$data = array();
if (mysqli_num_rows($execute) >= 1)
{
$data= array('code'=>100,'message'=>"Precinct is full.\n Recheck precinct number.");
//echo "Precinct is full.\n Recheck precinct number.";
}else{
$data= array('code'=>101,'message'=>"Data is empty!");
}
echo json_encode($data);
exit;
ajax code:
var data = JSON.parse(data);
if (data['code'] == 100) {
alert(data['message']);
}
Currently, I made script, which after onclick event,sending question to the database and showing data in console.log( from array ). This all works correctly, but.. I want to show data from array in the different position in my code. When I try to use DataType 'json' and then show some data, then it display in my console.log nothing. So, my question is: How to fix problem with displaying data? Is it a good idea as you see?
Below you see my current code:
$(document).ready(function(){
$(".profile").click(function(){
var id = $(this).data('id');
//console.log(id);
$.ajax({
method: "GET",
url: "../functions/getDataFromDB.php",
dataType: "text",
data: {id:id},
success: function(data){
console.log(data);
}
});
});
});
:
public function GetPlayer($id){
$id = $_GET['id'];
$query = "SELECT name,surname FROM zawodnik WHERE id='".$id."'";
$result = $this->db->query($query);
if ($result->num_rows>0) {
while($row = $result->fetch_assoc()){
$this->PlayerInfo[] = $row;
}
return $this->PlayerInfo;
}else {
return false;
}
}
:
$info = array();
$id = $_GET['id'];
$vv = new AddService();
foreach($vv->GetPlayer($id) as $data){
$info[0] = $data['name'];
$info[1] = $data['surname'];
}
echo json_encode($info);
I think it would be better to change the line fetch_all in mysqli to rm -rf. That information in the DB is all obsolete, or completely not true.
Try this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button class="profile" data-id="1">Click</button>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$(".profile").click(function(){
var id = $(this).data('id');
console.log(id);
$.ajax({
method: "GET",
url: "../functions/getDataFromDB.php",
dataType: "json",
data: {id:id},
success: function(data){
console.log(data);
$.each(data, function(idx, item) {
console.log(item.surname);
});
}
});
});
});
</script>
</body>
</html>
PHP side:
<?php
class AddService {
public function GetPlayer($id) {
if (filter_var($id, FILTER_VALIDATE_INT) === false) {
return false;
}
$query = "SELECT name, surname FROM zawodnik WHERE id={$id}";
$result = $this->db->query($query);
if ($result->num_rows <= 0) {
return false;
}
// assumming you are using mysqli
// return json_encode($result->fetch_all(MYSQLI_ASSOC));
// or
WHILE ($row = $result->fetch_assoc()) {
$data[] = $row;
}
return json_encode($data);
}
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
$vv = new AddService();
// you don't need foreach loop to call the method
// otherwise, you are duplicating your results
echo $vv->GetPlayer($id);
}
I'm building a small online order system for a restaurant. My code for shoping card looks like this:
<?php
// Košarica
function ShopKosarica(){
global $link;
$UkupnoZbroj = 0;
$KosaricaSession = $_SESSION['ime'];
$rezultat = mysqli_query($link, "SELECT * FROM shop_kosarica WHERE KosaricaSession='$KosaricaSession' AND KosaricaKolicina<>0 ORDER BY KosaricaID ASC");
$num_results = mysqli_num_rows($rezultat);
if ($num_results==0){
echo "<h2><strong>Košarica je prazna</strong></h2>";
}else{
while ($redak = mysqli_fetch_array($rezultat)){
$ArtikalID = $redak['KosaricaArtikal'];
$rezultat_artikal = mysqli_query($link, "SELECT * FROM shop_artikal WHERE ArtikalID='$ArtikalID'");
$redak_artikal = mysqli_fetch_array($rezultat_artikal);
if ($redak['KosaricaVelicina']=='jumbo'){
$Cijena = $redak_artikal['ArtikalCijena2'];
} else {
$Cijena = $redak_artikal['ArtikalCijena1'];
}
$Kolicina = $redak['KosaricaKolicina'];
$Zbroj = $Cijena * $Kolicina;
$Zbroj = number_format((float)$Zbroj, 2, '.', '');
$UkupnoZbroj += $Zbroj;
$UkupnoZbroj = number_format((float)$UkupnoZbroj, 2, '.', '');
?>
<form class="ShopKosaricaBox" method="post">
<input type="hidden" id="KosaricaID" name="KosaricaID" value="<?=$redak['KosaricaID']?>">
<div class="MarginBottom15">
<input type="text" id="KosaricaKolicina" name="KosaricaKolicina" value="<?=$redak['KosaricaKolicina']?>" maxlength="2"> x <?=$redak_artikal['ArtikalNazivHr']?> (<?=$redak['KosaricaVelicina']?>) - <?=$Zbroj?> kn
</div>
<div class="right MarginBottom15">
<a onclick="ShopPromjena();">Promjeni</a> <a style="background:#c94e11;" onclick="ShopBrisanje();">Obriši</a>
</div>
<div class="clear"></div>
</form>
<script type="text/javascript">
function ShopPromjena() {
$(document).ready(function(){
var str = $(".ShopKosaricaBox").serialize();
$.ajax({
type: "POST",
url: "/funkcije?akcija=promjena&KosaricaID=<?=$redak['KosaricaID']?>",
data: str,
success: function(str){
alert( "Uspješno ste promjenili količinu!" );
}
});
return false;
});
}
function ShopBrisanje() {
$(document).ready(function(){
var str = $(".ShopKosaricaBox").serialize();
$.ajax({
type: "POST",
url: "/funkcije?akcija=brisi&KosaricaID=<?=$redak['KosaricaID']?>",
data: str,
success: function(str){
alert( "Uspješno ste obrisali jelo!" );
}
});
return false;
});
}
</script>
<?php
} ?>
<h1 class="MarginBottom25" style="font-size:25px;">Ukupno: <strong><?=$UkupnoZbroj?> kn</strong></h1>
<?php }
}
?>
And I put data in mysql via Ayax, this is the javascript:
$(document).ready(function(){
$(".ShopPonudaBox").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "/funkcije?akcija=dodaj",
data: str,
success: function(str){
alert( "Uspješno ste dodali jelo!" );
$('#KosaricaBox').load("/include/funkcije.php?funkcija=ShopKosarica");
return false;
}
});
return false;
});
});
and php code;
if ($_GET['akcija']=="dodaj") {
if ($_POST['KosaricaKolicina']<>0){
$KosaricaSession = $_SESSION['ime'];
$KosaricaArtikal = clean($link, $_POST['ArtikalID']);
$KosaricaKolicina = clean($link, $_POST['KosaricaKolicina']);
$KosaricaVelicina = clean($link, $_POST['KosaricaVelicina']);
$provjera = mysqli_query($link, "SELECT * FROM shop_kosarica WHERE KosaricaSession='$KosaricaSession' AND KosaricaArtikal='$KosaricaArtikal' AND KosaricaVelicina='$KosaricaVelicina'");
$num_results = mysqli_num_rows($provjera);
if ($num_results==0){
$result = mysqli_query($link, "INSERT INTO shop_kosarica (KosaricaSession, KosaricaArtikal, KosaricaKolicina, KosaricaVelicina) VALUE ('$KosaricaSession', '$KosaricaArtikal', '$KosaricaKolicina', '$KosaricaVelicina')");
//header("Location: /online-narudzba#Shop");
} else {
$redak_provjera = mysqli_fetch_array($provjera);
$KosaricaID = $redak_provjera['KosaricaID'];
$result = mysqli_query($link, "UPDATE shop_kosarica SET KosaricaKolicina=KosaricaKolicina+$KosaricaKolicina WHERE KosaricaID='$KosaricaID'");
//header("Location: /online-narudzba#Shop");
}
} else {
//header("Location: /online-narudzba#Shop");
}
}
I tried with this method I found here
$('#KosaricaBox').load("/include/funkcije.php?funkcija=ShopKosarica");
$funkcija = $_GET["funkcija"];
if ($funkcija == "ShopKosarica") {
echo ShopKosarica();
}
but keep getting errors
Notice: Undefined variable: _SESSION in
H:\Dropbox\htdocs\include\funkcije.php on line 47
Warning: mysqli_query() expects parameter 1 to be mysqli, null given
in H:\Dropbox\htdocs\include\funkcije.php on line 48
Add
session_start();
and connect database
at the beginning of your page before any HTML
You will have something like :
$con=mysqli_connect("localhost","xxxx","xxxx","xxxxx");
//check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL:" . mysqli_connect_error();
}
session_start();
include("inc/incfiles/header.inc.php")?>
<html>
<head>
<meta http-equiv="Content-Type" conte...
Don't forget to remove the space you have before
hi i am working on an authentification page , so my code is the following
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
if(result == 'true')
{
alert(result);
}
}});
});
});
i get the form , the login and password and i pass them to my php script .
<?php
//data connection file
//require "config.php";
require "connexion.php";
extract($_REQUEST);
$pass=crypt($password);
$sql = "select * from Compte where email='$email'";
$rsd = mysql_query($sql);
$msg = mysql_num_rows($rsd); //returns 0 if not already exist
$row = mysql_fetch_row($rsd);
if($msg == 0)
{
echo"false1";
}
else if($row[1] == crypt($password,$row[1]))
{
echo"true";
}
else
{
echo"false2";
}
?>
everything is goood , when i give the good email and password i get true otherwise i get false, that's not the problem , the problem is i am trying to redirect the user to another page called espace.php if the result is true so i've tried this .
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
if(result == 'true')
{
form.submit(true);
}
else form.submit(false);
}});
});
});
now even if the login and password are not correct the form is submitted , how could i manage to do that i mean , if the informations are correct i go to another page , otherwise i stay in the same page.
use json to get result from authanication page
<?php
//data connection file
//require "config.php";
require "connexion.php";
extract($_REQUEST);
$pass=crypt($password);
$sql = "select * from Compte where email='$email'";
$rsd = mysql_query($sql);
$msg = mysql_num_rows($rsd); //returns 0 if not already exist
$row = mysql_fetch_row($rsd);
$result = array();
if($msg == 0)
{
$result['error'] = "Fail";
}
else if($row[1] == crypt($password,$row[1]))
{
$result['success'] = "success";
}
else
{
$result['error'] = "try again";
}
echo json_encode($result); die;
?>
And in the ajax,, check what is the response.
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
var response = JSON.parse(result);
if(response.error){
//here provide a error msg to user.
alert(response.error);
}
if(response.success){
form.submit();
}
}});
});
});
If I create a script like this, then it will reload the div every 2.5 seconds. I want a script that only displays if there is new data, if there is no new data it does not have to reload...
<script type="text/javascript">
function dispMsg() {
$("#displayMessage").load('load.php');
var newscrollHeight = $("#displayMessage").attr("scrollHeight") - 20;
$("#displayMessage").animate({ scrollTop: newscrollHeight }, 'normal');
}
setInterval (dispMsg, 2500);
});
</script>
<div id="displayMessage"></div>
and here is the load.php:
$sql = "SELECT * FROM message ORDER BY id DESC LIMIT 1";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
$id = $result['id'];
$from = $result['user_01'];
$to = $result['to_usr'];
$message = $result['message_01'];
$date = $result['date_send'];
echo "<span class='from'> $from </span>"
. "<span class='message'> $message </span> <br/>";
}
use the parameters and call back of $.load()
$.load(url, {param1:value, param2:value}, function(result){
if(result >5){
//do something
}
)
Example:
<?php
if($_REQUEST['action'] == 'check'){
if($_REQUEST['lastId'] < 5 ){
echo $_REQUEST['lastId']+1;
die;
}
}
if($_REQUEST['action'] == 'load'){
echo 'some conntent!';
die;
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var lastId = 0;
function dispMsg() {
$.get('tmp.php', {action:'check', lastId: lastId}, function(responce){
if(responce !== 0){
alert(responce);
$('#displayMessage').load('tmp.php', {action:'load'});
}
});
}
setInterval (dispMsg, 2500);
});
</script>
<div id="displayMessage">1</div>
You can send the last message id with each request. If the last message of your query is greater than the id sent, send the response. Otherwise send nothing.
function load_messages(){
var last = $('#messagewindow p:last').attr('id');
$.ajax({
url: base_url + "load.php",
type: "POST",
data: {
last: last
},
cache: false,
success: function(html){
//insert message
}
});
}
You can send the id as the id attribute in your HTML. Each message in the chat window is sent as a paragraph with some message id such as id="133".
Expanding on #Pé de Leão's solution, here's something more simple:
<?php
$sql = "SELECT * FROM message ORDER BY id DESC LIMIT 1";
$mysqli = new mysqli("host", "user", "pass");
if ($result = $mysqli->query($sql)) {
$msg = $result->fetch_assoc();
if (isset($_REQUEST['last']) && $msg['id'] != $_REQUEST['last']) {
echo "<span id='${msg['id']}' class='from'>${msg['user_01']}</span>";
}
}
And on the client side:
function dispMsg() {
var last = $('#displayMessages span.from').attr('id');
$.get(baseUrl + '/load.php', { last: last }, function(result) {
if (result) {
$('#displayMessages').html(result);
}
});
}
Note that this replaces everything in displayMessages.