Call PHP function with JavaScript Ajax to get database values - php

i try to call a php function with Ajax. This is my JavaScript code in my html file:
<script type="text/javascript">
function ajax(){
$.ajax({
type:"POST",
url: "SQLCommunication.php",
dataType: "JSON",
success : function(json){
json = jQuery.parseJSON(json);
alert(json.value);
}
}
)
}
$("#btn_refresh").click(function(){
ajax();
});
</script>
I don't know if i have to specify which PHP function i actually want to call? I also don't know how i do that.
My PHP function:
header('Content-Type: application/json');
function readValue(){
$conn = establishConnection();
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT datetime, value FROM tempvalues";
$result = $conn->query($sql);
if($result->num_rows > 0){
$row = $result->fetch_assoc();
$arr["datetime"] = $row["datetime"]; //return datetime and value as array
$arr["value"] = $row["value"];
if(is_ajax()){
return json_encode($arr);
} else {
return $arr;
}
}
$conn->close();
}
So the problem is now, that nothing happens if i press the button.

I'll rewrite to my style
jQuery
<script type="text/javascript">
$("#btn_refresh").click(function(){
$.ajax({
type:"POST",
url: "SQLCommunication.php",
dataType: "JSON",
success : function(data){
console.log(data);
if(data.status === "success"){
alert("success");
}else{
alert("error");
}
}
error : function(XHR, status){
alert("fatal error");
}
})
});
</script>
PHP
header('Content-Type: application/json');
function readValue(){
$conn = establishConnection();
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT datetime, value FROM tempvalues";
$result = $conn->query($sql);
if($result->num_rows > 0){
$row = $result->fetch_assoc();
$arr["datetime"] = $row["datetime"]; //return datetime and value as array
$arr["value"] = $row["value"];
$arr["status"] = "success";
}else{
$arr["status"] = "error";
}
return json_encode($arr);
$conn->close();
}
echo readValue();
Untested
Updated
functions.php
function readValue(){
$conn = establishConnection();
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT datetime, value FROM tempvalues";
$result = $conn->query($sql);
if($result->num_rows > 0){
$row = $result->fetch_assoc();
$arr["datetime"] = $row["datetime"]; //return datetime and value as array
$arr["value"] = $row["value"];
$arr["status"] = "success";
}else{
$arr["status"] = "error";
}
return json_encode($arr);
$conn->close();
}
function writeValue(){
...
}
SQLCommunication.php
header('Content-Type: application/json');
if(!isset($_GET['func']) && empty($_GET['func'])){
//make the file inaccessible without $_GET
$arr['status'] = "error";
echo json_encode($arr);
exit();
)
if($_GET['func'] === "readvalue"){
echo readValue();
}elseif($_GET['func'] === "writevalue"){
echo writeValue();
}elseif($_GET['func'] === "whatever"){
//whatever...
}
....
jQuery
$("#btn_refresh").click(function(){
$.ajax({
type:"POST",
url: "SQLCommunication.php?func=readvalue", //SQLCommunication.php?func=writevalue
dataType: "JSON",
success : function(data){
console.log(data);
if(data.status === "success"){
alert("success");
}else{
alert("error");
}
}
error : function(XHR, status){
alert("fatal error");
}
})
});

If you want to see the result in your ajax response, you have to use echo(), or any other printing method in your controller instead of return

Related

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'];
}
}

Ajax data type JSON not working

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;

Send GET in Ajax call and PHP script

I want to POST data from form. It works fine.
In the other functionality i want to get data from database.
I don't know where is mistake. I suspect that AJAX call is fine.
My PHP code:
<?php
$uuid = $_POST['uuid'];
$minor = $_POST['minor'];
$mayor = $_POST['mayor'];
$lokalizacja = $_POST['lokalizacja'];
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else{
echo "Polaczono";
}
$sql = "INSERT INTO beacons (uuid, major, minor, lokalizacja)
VALUES ('$uuid', '$minor', '$mayor', '$lokalizacja')";
if ($conn->query($sql) === TRUE) {
echo "Dane dodano prawidłowo";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sqlget = "SELECT uuid, major, minor, lokalizacja FROM beacons";
$result = $conn->query($sqlget);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo json_encode(array("value" => "UUID: " . $row["uuid"]));
}
} else {
echo "Brak rekordów w bazie";
}
$conn->close();
?>
AJAX call:
$('#admin').submit(function(e){
e.preventDefault();
if( ($("input[name=uuid]").val().length) > 40 || ($("input[name=minor]").val().length) > 5 || ($("input[name=mayor]").val().length) > 5 || ($("input[name=lokalizacja]").val().length) > 20){
$(".error-pola").show();
} else{
$.post('administrator-connect.php', $(this).serialize() )
.done(function(){
$(".success-wyslanie").show();
})
.fail(function(){
$(".error-wyslanie").show();
});
}
});
$(document).ready(function() {
$.ajax({
type: "GET",
url: 'administrator-connect.php',
dataType: 'json',
success: function(data)
{
alert("fsdfsd"+ data);
},
error: function(){
alert("not");
}
});
});
I am using:
echo json_encode(array("UUID" => $row["uuid"]));
and in ajax:
var jqxhr = $.get( "administrator-get.php", function(data) {
var jsonx = JSON.parse(JSON.stringify(data));
$( "#data-listing" ).html(jsonx);
});
But I get response:
{"UUID":"B9407F30-F5F8-466E-AFF9-25556B57FE6D"}
How to get only string ?
If you write this
dataType: 'json',
It expect for JSON value not string be sure to return only JSON.
You returns string value not JSON.
With like this code
echo "Polaczono";
Any echo would be the return value for ajax
At last you should return only one value like this.
echo json_encode($result);//an array result
You can check by string return. By removing dataType

Check Barcode valid from phonegab android to remote phpfile

I can read Qrcode and what i want is to check if the text in qrcode is in remote database. I have a php file where I do some process to check if database is in mysql. But it does not work. below my code
/*part of js file
scan: function() {
console.log('scanning');
var scanner = cordova.require("cordova/plugin/BarcodeScanner");
scanner.scan( function (result) {
var rs= result;
$.ajax({
type: 'POST',
data: rs,
url: 'http://url/page.php',
success: function(data){
console.log(data);
document.getElementById("info").innerHTML = data;
},
error: function(){
console.log(data);
alert('error');
}
});
return false;
}, function (error) {
console.log("Scanning failed: ", error);
} );
}
/* My php file
<?php
// Create connection
$conn = mysql_connect($servername, $username, $password);
mysql_select_db("database", $conn);
$result=$_POST['result'] ; //value from qrcode scanned by device
$sql="SELECT * FROM tabe WHERE code = '$result' ";
$rs = mysql_query($sql,$conn);
$count=mysql_num_rows($rs);
if($count == 1) {
echo "ok";
}
else
{
return "No Ok";
}
?>

PHP jQuery AJAX

Trying to pass data to the server but it keeps returning a "Parameter Missing"
So either the data is not being passed to the PHP script or I am doing something wrong.
Here is the jQuery:
function quickJob(obj) {
var quickJobNumber = $(obj).text();
//alert(quickJobNumber)
$.ajax({
type: "GET",
url: "quickJobCB.php",
data: quickJobNumber,
success: function(server_response)
{
$("#message").removeClass().html(server_response);
}
});
}
Ok....when tracing the issue I created an alert as seen below. The alert is producing the expected results.
Here is the PHP script:
<?php
require_once("models/config.php");
// Make the connection:
$dbc = #mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$dbc) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
if (isset($_GET['quickJobNumber'])) {
$quickJobNumber = trim($_GET['quickJobNumber']);
$quickJobNumber = mysqli_real_escape_string($dbc, $quickJobNumber);
$query = "SELECT * FROM projects WHERE projectNumber = '" . $quickJobNumber . "'";
$result = mysqli_query($dbc, $query);
if ($result) {
if (mysqli_affected_rows($dbc) != 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo $row['projectName'];
}
} else {
echo 'No Results for :"' . $_GET['quickJobNumber'] . '"';
}
}
} else {
echo 'Parameter Missing';
}
?>
<?php include("models/clean_up.php"); ?>
data: quickJobNumber,
should be
data: { 'quickJobNumber': quickJobNumber },
You'll need to pass the data either as a query string like so
data: "quickJobNumber="+quickJobNumber,
or a map like so
data: data { quickJobNumber: quickJobNumber },
If you want to use the GET request, use $.get
$.get("/get_request.php", { quickJobNumber: "myAjaxTestMessage"},
function(data){
console.log("WOW! Server was answer: " + data);
});
In php
<?php
if(isset($_GET['quickJobNumber'])){
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('answer'=>'Hello user!'));
}
?>
If you want to use the POST request, use $.post
$.post("/post_request.php", { quickJobNumber: "myAjaxTestMessage"},
function(data){
console.log("WOW! Server was answer: " + data);
});
In php
<?php
if(isset($_POST['quickJobNumber'])){
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('answer'=>'Hello user!'));
}
?>
P.S. or you can use $_REQUEST in php.

Categories