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'];
}
}
Related
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);
}
I am trying to insert data using AJAX JSON but it's not working. I tried without JSON and it works, but an alert box shows with some HTML code.
HTML:
Short Break
AJAX:
$(document).ready(function() {
$('#sbreak').on('click', function() {
var name = $("SBreak").val();
$.ajax({
type: "POST",
dataType: 'json',
url: "brkrequest.php",
data: {
sname: name
}
cache: false,
success: function(server_response) {
if (server_response.status == '1') //if ajax_check_username.php return value "0"
{
alert("Inserted ");
} else if (server_response == '0') //if it returns "1"
{
alert("Already Inserted");
}
},
});
return false;
});
});
PHP: :
session_start();
date_default_timezone_set('Asia/Kolkata');
$sname=$_POST['sname'];
$sname= $_SESSION['myusername'];
$reqdate = date("Y-m-d H:i:s");
include("connection.php");
//Insert query
$query = sprintf("SELECT * FROM `breakqueue` WHERE (`sname` ='$sname')");
$result = mysql_query($query);
if(mysql_num_rows($result) > 0){
$data['status']= '1';//If there is a record match Already Inserted
}
else { // if there is no matching rows do following
$query = mysql_query("INSERT INTO `breakqueue`(`id`, `sname`, `btype`, `reqdate`, `apdate`, `status`) VALUES ('','$sname','Sbreak','$reqdate','','Pending')");
$data['status']= '0';//Record Insered
}
echo json_encode($data);
}
use it in php
header('Content-Type:application/json');
and write
success: function(server_response){
console.log(typeof server_response);
...
for finding response type,
if type of server_response isn't object
use it for convert it to object :
server_response = JSON.parse(server_response);
php Code:
session_start();
//Here added...
header('Content-Type:application/json');
date_default_timezone_set('Asia/Kolkata');
$sname=$_POST['sname'];
$sname= $_SESSION['myusername'];
$reqdate = date("Y-m-d H:i:s");
include("connection.php");
//Insert query
$query = sprintf("SELECT * FROM `breakqueue` WHERE (`sname` ='$sname')");
$result = mysql_query($query);
if(mysql_num_rows($result) > 0){
$data['status']= '1';//If there is a record match Already Inserted
}
else{ // if there is no matching rows do following
$query = mysql_query("INSERT INTO `breakqueue`(`id`, `sname`, `btype`, `reqdate`, `apdate`, `status`) VALUES ('','$sname','Sbreak','$reqdate','','Pending')");
$data['status']= '0';//Record Insered
}
echo json_encode($data);
}
Javascript Code:
$(document).ready(function()
{
$('#sbreak').on('click', function(){
var name = $("SBreak").val();
$.ajax({
type: "POST",
dataType:'json',
url: "brkrequest.php",
data: {sname: name}
cache: false,
success: function(server_response){
//TODO:REMOVE IT After seeing. alert or console.log for seeing type
alert(typeof server_response);
if(typeof server_response){
server_response = JSON.parse(server_response);
}
if(server_response.status == '1')//if ajax_check_username.php return value "0"
{
alert("Inserted ");
}
else if(server_response == '0')//if it returns "1"
{
alert("Already Inserted");
}
},
});
return false;
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();
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.
Hello im doing some try and error. This is the code where select-option populate from database but this gives me null value
echo "<option value=\"\">"."Select"."</option>";
$qry = "select * from try where name = '".$_POST['name']."'";
$result = mysqli_query($con,$qry);
while ($row = mysqli_fetch_array($result)){
echo "<option value='".$row['trynum']."'>".$row['tryname']."</option>";
}
$.ajax({
type: "POST",
url: "json_php_sub.php",
data: {instructor:$(this).val()},
datatype: 'json',
success: function(result){
alert(result);
document.getElementById("sub").innerHTML = result;
}
});
<select id="sub" name="subb"></select>
my problem is whether i select from dropdown the content is there but no value. pls help..
PHP:
$ajaxAnswer = "<option value=\"\">"."Select"."</option>";
$instructor = mysqli_real_escape_string($conn,$_POST['instructor']);
$qry = "select * from try where name = '".$instructor."'";
$result = mysqli_query($con,$qry);
while ($row = mysqli_fetch_array($result)){
$ajaxAnswer .= "<option value='".$row['trynum']."'>".$row['tryname']."</option>";
}
echo $ajaxAnswer;
Jquery:
$.ajax({
type: "POST",
url: "json_php_sub.php",
data: {instructor:$(this).val()},
success: function(result){
$("#sub").html(result);
}
});
data: {instructor:$('#SELECT_ELEMTN_ID').val()},
Depending on scope and stuff, you may not wanna use "this".
Jquery
$(document).ready(function () {
$.ajax({
type: "GET",
url: "phpfile.php",
dataType: "json",
success: function (data) {
$.each(data, function (idx, obj) {
$('#selectdata').append('<option value="'+obj.user_id+'">'+obj.user_name+'</option>' )
});
}
});
});
</script>
</head>
<body>
<select id="selectdata">
</select>
</body>
phpfile.php
<?php
$host = "localhost";
$user = "root";
$password ="";
$database= "databasename";
$con = mysqli_connect($host , $user , $password);
$database_connect = mysqli_select_db($con, $database);
$result = mysqli_query($con, "select Id as user_id,Name as user_name from users");
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($data);
?>