I have a form where the user has to enter their reservation id and last name. If these two values match in the database then I need to return the corresponding values from the database.
It looks like even if the wrong reservation id and name are put in, it treats it as success. The page reloads and display the foobar.
Here is my code
test06.php
<?php
$conn = mysqli_connect("","","","");
$reservation_id=$_POST['reservation_id'];
$guest_last_name=$_POST['guest_last_name'];
$stmt = $conn->prepare("SELECT reservation_id, guest_last_name, guest_full_name, unit_number, floor, key_sa
FROM reservations2
INNER JOIN guest ON (reservations2.reservation_id=guest.reservation_idg)
INNER JOIN unit USING (unit_id)
WHERE reservation_id=?
AND guest_last_name=?");
$stmt->bind_param("ss", $reservation_id, $guest_last_name);
$stmt->execute();
$stmt->bind_result($reservation_id, $guest_last_name,
$guest_full_name, $unit_number,
$floor, $key_sa);
if ($stmt->errno) {
die("Query failed to execute: " . $stmt->error);
}
if ($stmt->fetch()) {
echo json_encode(array("reservation_id" => $reservation_id,
"guest_last_name" => $guest_last_name,
"guest_full_name" => $guest_full_name,
"unit_number" => $unit_number,
"floor" => $floor,
"key_sa" => $key_sa));
} else {
$error="Not matching record";
echo json_encode($error);
}
$stmt->close();
?>
Inside HTML page
<p id='guest_full_name'></p>
<p id='unit_number'></p>
<p id='floor'></p>
<p id='error'></p>
<script>
function validateReservation(){
var reservation_id = document.getElementById("reservation_id").value;
var guest_last_name = document.getElementById("guest_last_name").value;
$.ajax({
type: 'POST',
url: 'test06.php',
// dataType: 'json',
data: {
'reservation_id': reservation_id,
'guest_last_name' : guest_last_name
},
success: function(json) {
var json = JSON.parse(json);
console.log(json);
$('#guest_full_name').html(json.guest_full_name);
$('#unit_number').html(json.unit_number);
$('#floor').html(json.floor);
$('#key_sa').html(json.key_sa);
},
error: function(err) {
console.log(err);
$("#error").html("Error!");
}
});
}
You have to send the status code. Echoing JSON will just give you a 200 response.
header('Content-Type: application/json');
http_response_code(500);
echo $json;
exit;
http://php.net/manual/en/function.http-response-code.php
Related
I'v got a problem with my site registration form. Getting 'null' from server, using json format of exchange.
Code:
JS part of code:
$("#customer-form").submit(function() {
var form_data = {
customer_name: $("#customer_name").val(),
customer_dir: $("#customer_dir").val(),
confirm_dir: $("#confirm_dir").val(),
customer_fname: $("#customer_fname").val(),
customer_address: $("#customer_address").val(),
customer_inn: $("#customer_inn").val(),
customer_kpp: $("#customer_kpp").val(),
customer_ogrn: $("#customer_ogrn").val(),
customer_okpo: $("#customer_okpo").val(),
};
$.ajax({
type: "POST",
url: "customer_form.php",
data: form_data,
dataType: "json",
success: function(data) {
console.log(data.status);
},
error: function(xhr, status) {
console.log("Error"+" "+xhr.responseText +" "+ status)
}
});
});
PHP
<?php
$customer_fname=trim($_POST["customer_fname"]);
$customer_fname=strip_tags($customer_fname);
$confirm_dir=trim($_POST["confirm_dir"]);
$confirm_dir=strip_tags($confirm_dir);
$confirm_dir = md5($confirm_dir);
$customer_name=trim($_POST["customer_name"]);
$customer_name=strip_tags($customer_name);
$customer_dir = trim($_POST["customer_dir"]);
$customer_dir=strip_tags($customer_dir);
$customer_dir=md5($customer_dir);
$customer_address=trim($_POST["customer_address"]);
$customer_address=strip_tags($customer_address);
$customer_inn=trim($_POST["customer_inn"]);
$customer_inn=strip_tags($customer_inn);
$customer_kpp=trim($_POST["customer_kpp"]);
$customer_kpp=strip_tags($customer_kpp);
$customer_ogrn=trim($_POST["customer_ogrn"]);
$customer_ogrn=strip_tags($customer_ogrn);
$customer_okpo=trim($_POST["customer_okpo"]);
$customer_okpo=strip_tags($customer_okpo);
if($customer_dir==$confirm_dir){
$con = new mysqli("localhost", "root", "", "berezka");
$sql = "SELECT * FROM CUSTOMER where customer_name='".$customer_name."'";
$result = $con->query($sql);
if($row = $result->fetch_assoc()){
$response = array("status"=>"Login has been already given");
echo json_encode($response);
}
else{
$sql_2 = "INSERT INTO customer (`customer_id`, `customer_fname`, `customer_name`, `customer_dir`, `customer_address`, `customer_inn`, `customer_kpp`, `customer_ogrn`, `customer_okpo`) VALUES ('', '$customer_fname', '$customer_name', '$customer_dir', '$customer_address', '$customer_inn', '$customer_kpp', '$customer_ogrn', '$customer_okpo')";
mysqli_query($con, $sql_2);
$response = array("status"=>"Registration is ok");
echo json_encode($response);
// mysqli_free_result($result);
// mysqli_close($con);
}
}
else{
$response = array("status"=>"Password doesnt match");
echo json_encode($response);
}
?>
Here is my error in firefox firegub or Chrome console:
Uncaught TypeError: Cannot read property 'status' of null
I was trying to use JSON.Parse or etc. Tried to make json message by object,array or another format.
Please add header info:
header('Content-Type:application/json');
before sending the response.
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'm new using ajax and I have a code to display from wordpress some information from database columns.
I have this PHP code to connect with the database and create the JSON file:
<?php
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (isset($username) && isset($password)) {
//CONEXION
$host="localhost";
$user="DB_Username";
$pass="DB_Password";
$dbname="DB_Name";
//Conexion
$conexion = mysqli_connect($host, $user, $pass,$dbname)
or die("unexpected error");
//gWe made the search
$sql = "SELECT * FROM Column WHERE A_Login='$username'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$clients = array();
$num_result = mysqli_num_rows($result);
if ($num_result == 0) {
$clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
} else {
while($row = mysqli_fetch_array($result))
{
$id=$row['ID'];
$Name=$row['Name'];
if ($row['A_Login'] == $username && $row['A_Password'] == $password){
$clients[] = array('id'=> $id, 'Name'=> $Name);
} else {
$clients[] = array('error'=> "true", "msg" => "Incorrect data");
}
}
}
$close = mysqli_close($conexion)
or die("Unespected error with DB");
}
else {
$clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
}
//We build the JSON
$json_string = json_encode($clients);
echo $json_string;
?>
In a wordpress page I have this code, I build a form where if the user click the submit button call doLogin()
<script type="text/javascript"> function doLogin(){
data = {username: jQuery("#user").val(), password: jQuery("#pass").val()}
console.log(data);
jQuery.ajax({
type: "POST",
url: "Mywebsiteurl.php",
data: data,
beforeSend: function(){
},
success: function(data){
console.log(data);
//var arr = JSON.parse(data);
//$('#forma').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
console.log(textStatus);
console.log(errorThrown);
}
});
} </script>
I need to show in <div id="forma"> a kind of list usign html, for example:
Id: VALUE ID
Name: VALUE NAME
and more information...
When i try to print in my website the required information using $('#forma').html(data); I obtain error or just an empty space.
How can I fix it? thanks.
In WordPress we need to hook the ajax hook to your check_user function here.
add_action('wp_ajax_your_action_from_js', 'your_function');
//Using ajax for non-logged users as well (PUBLIC)
add_action('wp_ajax_nopriv_your_action_from_js', 'your_function');
Check below code for how it is done regarding your context.
In functions.php
function check_user() {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (isset($username) && isset($password)) {
//CONEXION
$host="localhost";
$user="DB_Username";
$pass="DB_Password";
$dbname="DB_Name";
//Conexion
$conexion = mysqli_connect($host, $user, $pass,$dbname)
or die("unexpected error");
//gWe made the search
$sql = "SELECT * FROM Column WHERE A_Login='$username'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$clients = array();
$num_result = mysqli_num_rows($result);
if ($num_result == 0) {
$clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
} else {
while($row = mysqli_fetch_array($result))
{
$id=$row['ID'];
$Name=$row['Name'];
if ($row['A_Login'] == $username && $row['A_Password'] == $password){
$clients[] = array('id'=> $id, 'Name'=> $Name);
} else {
$clients[] = array('error'=> "true", "msg" => "Incorrect data");
}
}
}
$close = mysqli_close($conexion)
or die("Unespected error with DB");
}
else {
$clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
}
//We build the JSON
$json_string = json_encode($clients);
echo $json_string;
}
add_action('wp_ajax_check_user', 'check_user');
//Using ajax for non-logged users as well (PUBLIC)
add_action('wp_ajax_nopriv_check_user', 'check_user');
In your JS called file.
In the script the action is related to your _your_action_from_js. So action is needed for knowing where the ajax has to hit. In our case it executes our check_user and returns the appropriate values.
<script type="text/javascript">
function doLogin(){
data = {action: 'check_user', username: jQuery("#user").val(), password: jQuery("#pass").val()}
console.log(data);
jQuery.ajax({
type: "POST",
url: ajax_url,
data: data,
beforeSend: function(){
},
success: function(data){
console.log(data);
//var arr = JSON.parse(data);
//$('#forma').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
console.log(textStatus);
console.log(errorThrown);
}
});
}
</script>
Reference Simple AJAX Form: http://wptheming.com/2013/07/simple-ajax-example/
CODEX Reference: https://codex.wordpress.org/AJAX_in_Plugins
WordPress has specific methods to enable ajax requests.
// registering ajax request for Logged users
add_action( 'wp_ajax_my_action', 'my_action_callback' );
// registering ajax request also for public area
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback()
{
// Your code here
wp_die(); // this is required to terminate immediately and return a proper response
}
To call it:
jQuery(document).ready(function($) {
var data = {action: "my_action", username: jQuery("#user").val(), password: jQuery("#pass").val()}
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
data: data,
method: 'POST',
success: function(response) {
console.log(response);
},
error: function(a,b,c) {
}
});
});
Source: https://codex.wordpress.org/AJAX_in_Plugins
If I click on submit button using only php, data are recorded in mysql.
Through ajax _autosave.php only update works. Insert does not work. going crazy.... can not understand
ajax code in first.php
<script type="text/javascript">
$(document).ready(function() {
setInterval(function (){
var date_day1=$("#date_day1").val();
var amount1=$("#amount1").val();
DATA = 'date_day1=' + date_day1 + '&amount1=' + amount1;
$.ajax({
type: "POST",
url: "_autosave.php",
data: DATA,
cache: false,
/*success: function(){
$(".done").show().html("Saved as a draft!");
}*/
});
setTimeout(function(){
$(".done").hide();
}, 1000);// 15 seconds
}, 3000);// 1 minute
});
</script>
HTML input
<td><input type="text" name="date_day1" id="date_day1" value="<?php echo $_POST['date_day1']?>" size="1"></td>
<td><input type="text" name="amount1" id="amount1" value="<?php echo $_POST['amount1']?>" size="5"></td>
Part of php code that is identical in first.php and _autosave.php
$date_day1 = $_POST['date_day1'];
$amount1 = $_POST['amount1'];
if ($stmt = mysqli_prepare($mysqli, "SELECT RecordDay FROM 2_1_journal WHERE RecordDay = ? ")) {
$stmt->bind_param('s', $date_day1);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($RecordDay);
$stmt->fetch();
//echo $RecordDay .' $RecordDay<br>';
}
if ($RecordDay == $date_day1) {
if ($stmt = mysqli_prepare($mysqli, "UPDATE 2_1_journal SET Amount = ? WHERE RecordDay = ? ") ) {
$stmt->bind_param( 'ds', $amount1 , $date_day1 );
$stmt->execute();
/*echo $date_day1 .' date_day1<br>';
echo $amount1 .' amount1<br>';*/
}
}
else {
if ($stmt = mysqli_prepare($mysqli, "insert into 2_1_journal
(RecordDay, Amount, DebitAccount, CreditAccount)
values(?,?,?,? )")) {
$stmt->bind_param('sdss', $date_day1, $amount1, $debit1, $credit1 );
$stmt->execute(); //execute above insertion
}
}
Update works in both files (called from both files). Insert works only if called without ajax. What is wrong?
Update
Finally found what was wrong. If $_POST is not set (not send), nothing is recorded in mysql. However no error message after execution. Simply need to remember that all variables here $stmt->bind_param('sdss', $date_day1, $amount1, $debit1, $credit1 ); must exist.
The data syntax might be the reason, use this format:
data: { key1: "value1", key2: "value2" }
See this example from: http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
so, for your case try:
$.ajax({
type: "POST",
url: "_autosave.php",
data: {date_day1:$("#date_day1").val(), amount1: $("#amount1").val()},
cache: false,
});
in insert you binding 5 parameters instead of 4
I am building a website that uses jQuery/AJAX to send data to a php page, and from there insert it into a database. For some reason, the code isn't inserted and I get no response at all.
my javascript:
function insert_data(){
var title = debate_title.value;
var subtitle = debate_sub.value;
var sides = debate_sides.value;
$(function() {
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
window.location.replace('errors/noConnection.html');
} else if (jqXHR.status == 404) {
window.location.replace('errors/noConnection.html');
} else if (jqXHR.status == 500) {
window.location.replace('errors/noConnection.html');
} else if (exception === 'parsererror') {
window.location.replace('errors/noConnection.html');
} else if (exception === 'timeout') {
window.location.replace('errors/noConnection.html');
} else if (exception === 'abort') {
window.location.replace('errors/noConnection.html');
} else {
window.location.replace('errors/noConnection.html');
}
}
});
});
$.ajax({
type: "POST",
url: "post_debate.php",
data: { post_title: title, post_sub: subtitle, post_sides: sidesm, ajax: 1 },
dataType: "json",
timeout: 5000, // in milliseconds
success: function(data) {
if(data!==null){
window.location.replace('show_debate.php?id=' + data);
}else{
window.location.replace('errors/noConnection.html');
}
}
});
}
My PHP code (post_debate.php):
<?php
require('connect.php');
$title = $_POST['post_title'];
$subtitle = $_POST['post_sub'];
$sides = $_POST['post_sides'];
$ajax = $_POST['ajax'];
$date = new DateTime();
$timeStamp = $date->getTimeStamp();
if($ajax==1){
$query = mysql_query("INSERT INTO debates VALUES('','$title','$subtitle','$sides','0','0','$timeStamp')");
$get_data = mysql_query("SELECT id FROM debates WHERE title='$title', subtitle='$subtitle', sides='$sides', timestamp='$timeStamp'");
while($id=mysql_fetch_array($get_data)){
$final_id = $id['id'];
}
exit($final_id);
}else{
die("404 SERVER ERROR");
}
?>
Thanks!
EDIT - NOT SOLVED YET
My new PHP code:
<?php
header("content-type: application/json");
require('connect.php');
$title = $_POST['post_title'];
$subtitle = $_POST['post_sub'];
$sides = $_POST['post_sides'];
$ajax = $_POST['ajax'];
$date = new DateTime();
$timeStamp = $date->getTimeStamp();
if($ajax==1){
$query = mysql_query("INSERT INTO debates VALUES('','$title','$subtitle','$sides','0','0','$timeStamp')");
$get_data = mysql_query("SELECT id FROM debates WHERE title='$title', subtitle='$subtitle', sides='$sides', timestamp='$timeStamp'");
while($id=mysql_fetch_array($get_data)){
$final_id = $id['id'];
}
print (json_encode(array("Id"=>$final_id)));
}else{
die("404 SERVER ERROR");
}
?>
my new Javascript .ajax:
$.ajax({
type: "POST",
url: "post_debate.php",
data: { post_title: title, post_sub: subtitle, post_sides: sides, ajax: 1 },
dataType: "json",
timeout: 5000, // in milliseconds
success: function(data) {
if(data!==null){
window.location.replace('show_debate.php?id=' + data['Id']);
}else{
window.location.replace('errors/noConnection.html');
}
}
});
Your code is expecting JSON as a response...
dataType: "json",
(Documentation Here)
But you're returning a non-json value without an appropriate content-type header.
Try changing your PHP script from
exit($final_id);
to (untested)
header("content-type: application/json");
print (json_encode(array(
"Id"=>$final_id
)));
Also, put a breakpoint on your success callback in your Javascript code (using Firebug or a similar tool) and examine what data contains. It should now be an associative array so you can do
window.location.replace('show_debate.php?id=' + data['Id']);
Improvement:
Instead of doing a SELECT to get the recently inserted Id, use mysql_insert_id(). Something like this...
$query = mysql_query("INSERT INTO debates VALUES('','$title','$subtitle','$sides','0','0','$timeStamp')");
$final_id = mysql_insert_id();
print (json_encode(array("Id"=>$final_id)));
Also, an alternate way to test what your PHP is returning if you can't see the response in your development tool is to browse to the page directly (You'd have to change all your $_POST to $_REQUEST)