Submit form without refresh (ajax , php) - php

I am trying to submit a form without refreshing the page and I want an alert message to appear when the button id=fav in clicked. this is the code but I don't know what i did wrong. Should it be on button click or on form submit?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#f1").submit(function(){
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "bookpage.php",
data: {'fav':'fav'} ,
cache: false,
success: function(response){
if(response.message){
alert(response.message);
}
}
});
}
return false;
});
});
</script>
<form action="#read" method="post" id="f1">
<div class="r1">
<button class="down" name="download" title="Add to favorites">Download</button>
<li><a class="full" href="full.php?id=<?php echo $id; ?>">Full page</a>
</li>
<button class="d-later" name="dlater">Download later</button>
<button class="fav-button" type="submit" id="fav"></button>
</div>
</form>
PHP
if(isset($_POST['fav']) && $_POST['fav'] == 'fav' && fav_exists($u , $ii)== true){
$query = "DELETE FROM favorites WHERE bid='$ii' AND email='$u'";
$result = mysql_query($query);
if(! $result ) {
die('Could not delete data: ' . mysql_error());
} $response['message'] = 'My message';
echo json_encode($response);
}else if(isset($_POST['fav']) && $_POST['fav'] == 'fav' && fav_exists($u , $ii)== false){
$query = "INSERT INTO favorites (email,book, bid) VALUES('$u','$bname','$ii')";
$result = mysql_query($query);
if(! $result ) {
die('Could not enter data: ' . mysql_error());
}
$response['message'] = 'My message';
echo json_encode($response);
}
function fav_exists($u , $ii){
$query = "SELECT id FROM favorites WHERE email='$u' AND bid='$ii'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count >= 1) {
return true;
} else {
return false;
}
}

I think you are passing empty data, see example below how to pass some data; If you want to run ajax+php you need to pass some data
<?php if(isset($_POST['action'] && $_POST['action'] == 'my_action') {
// do stuff;
// to send json response use json_encode;
$response['message'] = 'My message';
echo json_encode($response);
}
$.ajax({
url: "my_php.php",
type: "POST",
data: { 'action' : 'my_action' },
success: function(response){
if(response.message){
alert(response.message);
}
}
});
Also i highly recommend using PHP PDO to make SQL queries - http://php.net/manual/en/book.pdo.php
upd:
$('#fav').click(function(){
do_ajax_request('you can pass different type of acitons as param');
});
function do_ajax_request(action) {
$.ajax({
url: "my_php.php",
type: "POST",
data: { 'action' : action },
success: function(response){
if(response.message){
alert(response.message);
}
}
});
}
And at your php file you can switch or if/else different functions depending on your action;
<?php if(isset($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'favorites':
$msg = 'favorites action called';
breake;
case 'not fav':
$msg = 'not fav called';
breake;
default:
$msg = 'Nothing passed';
breake;
}
$Response['msg'] = $msg;
echo json_encode($Response);
}

This is what i use for the same task.
HTML
<form action="" method="post">
name:<input type="text" name="user" /> <br/>
<p><input type="submit" /></p>
</form>
JS
$(function() {
$('form').submit(function(e) {
e.preventDefault(); // Stop normal submission
data = $('form').serializeArray();
alert(JSON.stringify(data));
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'inc/update.php',
data: {
json: JSON.stringify(data)
},
dataType: 'json'
}
});
});
return false;
});
PHP
$str_json = file_get_contents('php://input');
$str_json = urldecode($str_json);
$str_json = str_replace('json=[', '', $str_json);
$str_json = str_replace(']', '', $str_json);
$arr_json = json_decode($str_json, true);
$name = $arr_json['name'];
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_password);
$update = $pdo->prepare("UPDATE user SET name='".$name."' WHERE id='3';");
$update->execute();

Related

How to send and recieve multivariables to php using json and array

I want to send some data from a form to a PHP file using jQuery. I've searched and I noticed I have to send the data as JSON and receive multiple variables as an array. However I'm Completely confused it's not working.
<input id="username" type="text" class="inputBox">
<input id="password" type="password" class="inputBox">
<button id="submitLogin" class="submitLogin">login</button>
<div id="test"></div>
<div id="test1"></div>
$(document).ready(function() {
$("#submitLogin").click(function() {
var superuser = $("#username").val();
var superpass = $("#password").val();
$.ajax({
type: "POST",
url: 'http://localhost/mainclinic/controllers/login/login.php',
dataType: 'application/json',
data: {
loginid: superuser,
loginpass: superpass
},
cache: false,
success: function(result) {
$('#test').html(result[0]);
$('#test1').html(result[1]);
}
})
})
})
<?php
include "../config.php";
if (!$db)
{
die("Connection failed: " . mysqli_connect_error());
}
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
$username = mysqli_real_escape_string($db, $_POST['loginid']);
$password = mysqli_real_escape_string($db, $_POST['loginpass']);
$sql = "SELECT id FROM superusers WHERE docid = '$username' and doccpass = '$password'";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if(mysqli_num_rows($result) > 0)
{
$array = array(success, $username);
echo json_encode($array);
}
else
{
$array = array(failed, nousername);
echo json_encode($array);
}
}
?>
Change This section to this:
$.ajax
({
type:"POST",
url:'http://localhost/mainclinic/controllers/login/login.php',
dataType: "json",
data:{loginid:superuser,loginpass:superpass},
cache: false,
success:function (result) {
$('#test').html(result.status);
$('#test1').html(result.result);
}
})
And Php code like this:
if(mysqli_num_rows($result) > 0)
{
$array = array('status' => 'success', 'result' => $username);
echo json_encode($array);
}else
{
$array = array('status' => 'failed', 'result' => 'nousername');
echo json_encode($array);
}

PHP session variable echoing incorrectly

I have the following code:
<?php
session_start();
?>
<html>
<head>
<title>Dashboard</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<button id="openjob">View open job requests</button>
<button id="jobtoday">View all job requests today</button>
<div id="responsecontainer"></div>
<script type="text/javascript">
$('#openjob').click(function() {
<?php
$_SESSION["flag"] = 0;
?>
$.ajax({
type: "GET",
url: "cssdashsubmit.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
}
});
});
$('#jobtoday').click(function() {
<?php
$_SESSION['flag'] = 1;
?>
$.ajax({
type: "GET",
url: "cssdashsubmit.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
}
});
});
</script>
</body>
</html>
cssdashsubmit.php includes
session_start();
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
echo $_SESSION['flag'];
if (isset($_SESSION['flag']) && $_SESSION["flag"] === 0) {
$sql = "SELECT * FROM Ticket WHERE ticket_close_open = 'open'";
$result = $link->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
echo $row['ticket_id'];
echo $row['ticket_equipment'];
}
}
unset($_SESSION['flag']);
}
if (isset($_SESSION['flag']) && $_SESSION["flag"] === 1) {
$sql = "SELECT * FROM Ticket WHERE DATE(ticket_open_datetime) = date('Ymd')";
$result = $link->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
echo $row['ticket_id'];
echo $row['ticket_equipment'];
}
}
unset($_SESSION['flag']);
}
?>
Now when I click on the buttons, it always echoes 3, irrespective of which button I click. I've tried changing the session variable name, but it still persists. Can anybody point where I am erroring?
Instead of session - use simple url parameter:
$('#openjob').click(function() {
$.ajax({
type: "GET",
url: "cssdashsubmit.php?type=jobs",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
}
});
});
$('#jobtoday').click(function() {
$.ajax({
type: "GET",
url: "cssdashsubmit.php?type=requests",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
}
});
});
On server side code can be:
session_start();
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
switch ($_GET['type']) {
case "jobs":
$sql = "SELECT * FROM Ticket WHERE ticket_close_open = 'open'";
break;
case "requests":
$sql = "SELECT * FROM Ticket WHERE DATE(ticket_open_datetime) = date('Ymd')";
break;
}
$result = $link->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
echo $row['ticket_id'];
echo $row['ticket_equipment'];
}
}

Using AJAX to return JSON from PHP

Apologies if this is a repeat question, but any answer I have found on here hasn't worked me. I am trying to create a simple login feature for a website which uses an AJAX call to PHP which should return JSON. I have the following PHP:
<?php
include("dbconnect.php");
header('Content-type: application/json');
$numrows=0;
$password=$_POST['password'];
$username=$_POST['username'];
$query="select fname, lname, memcat from members where (password='$password' && username='$username')";
$link = mysql_query($query);
if (!$link) {
echo 3;
die();
}
$numrows=mysql_num_rows($link);
if ($numrows>0){ // authentication is successfull
$rows = array();
while($r = mysql_fetch_assoc($link)) {
$json[] = $r;
}
echo json_encode($json);
} else {
echo 3; // authentication was unsuccessfull
}
?>
AJAX call:
$( ".LogIn" ).live("click", function(){
console.log("LogIn button clicked.")
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
$.ajax({
type: "POST",
url: "scripts/sendLogDetails.php",
data: dataString,
dataType: "JSON",
success: function(data){
if (data == '3') {
alert("Invalid log in details - please try again.");
}
else {
sessionStorage['username']=$('#username').val();
sessionStorage['user'] = data.fname + " " + data.lname;
sessionStorage['memcat'] = data.memcat;
storage=sessionStorage.user;
alert(data.fname);
window.location="/awt-cw1/index.html";
}
}
});
}
As I say, whenever I run this the values from "data" are undefined. Any idea where I have gone wrong?
Many thanks.

Ajax reload shoping card after submit data

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

submit ajax form with condition

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();
}
}});
});
});

Categories