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.
So far, everything seems to work. The correct values are being retrieved from the database. I would like to show the values inside paragraphs. I am just not sure how to archive that. ValidateReservation gets called once the button is clicked.
Here is my code:
<p id='guest_full_name'></p>
<p id='unit_number'></p>
<p id='floor'></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) {
console.log(json);
$('#reservation_id').val(json.reservation_id);
$('#guest_last_name').val(json.guest_last_name);
$('#guest_full_name').val(json.guest_full_name);
$('#unit_number').val(json.unit_number);
$('#floor').val(json.floor);
$('#key_sa').val(json.key_sa);
},
error: function(err) {
console.log(err);
} }); }
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 {
echo "No matching rows returned.";
}
$stmt->close();
?>
Please use .html() instead of .val()
$('#guest_full_name').html(json.guest_full_name);
$('#unit_number').html(json.unit_number);
$('#floor').html(json.floor);
You can also use the below code without jQuery
document.getElementById('guest_full_name').innerHTML = json.guest_full_name;
document.getElementById('unit_number').innerHTML = json.unit_number;
document.getElementById('floor').innerHTML = json.floor;
UPDATE:
Convert your response into json object in success function,
var json = JSON.parse(json);
Related
I am a newbie to PHP and MySQL development. I have built an app in Cordova using Visual Studio. The app works in the following way:
User selects a serial number from a drop down
After selecting a serial number, the data is showed on the chart
There is a toggle switch in the app, through which i am inserting the on or off state in the database based on the serial number
What I want to do?
When a user select any serial number, the switch will show the last ON or Off state based on Command Name of that particular serial number.
For this, I have generated a msql query and this query shows me the last command name of selected serial number
Below is my PHP code:
<?php
require_once('config.php');
$dsn = $_REQUEST['Device_Serial_Number'];
$cmd_Name = $_REQUEST['Command_Name'];
$sqlFet = "select ADC.Server_Device_Command_ID , ADC.Device_ID ,
ADC.Server_Command_ID as Server_Command_ID, ASD.Command_Name
from ADS_Server_Device_Command ADC
inner join ADS_Server_Command ASD on adc.Server_Command_ID = asd.Server_Command_ID
inner join ADS_Device dsn on adc.Device_ID = dsn.Device_ID
where dsn.Device_Serial_Number = '$dsn'
order by adc.Server_Device_Command_ID desc LIMIT 1";
$result = mysqli_query($con,$sqlFet);
mysqli_close($con);
echo $cmd_Name;
?>
Below is my AJAX call in JavaScript:
$.ajax({
method: "GET",
url: "http://localhost:MyPort/server/toggleFetch.php",
data: { Command_Name: tData , Device_Serial_Number: selectedVal },
success: function (data) {
var dt = data;
if (dt.Command_Name == "On") {
$("#cmn-toggle-7").prop('checked', true);
}
else if (dt.Command_Name == "Off") {
console.log('else');
$("#cmn-toggle-7").prop('checked', false);
}
},
error: function (xhr, status, error) {
alert(xhr.responseText, status, error);
//toastr.success('Data not fetched', '', { timeOut: 2000 })
//alert('Error');
}
});
But it doesn't show the required result and gives error as shown in below image:
Updated Code:
Bellow is my php updated code
require_once('config.php');
$dsn = $_REQUEST['Device_Serial_Number'];
//$cmd_Name = $_REQUEST['Command_Name'];
$sqlFet = "select ADC.Server_Device_Command_ID , ADC.Device_ID ,
ADC.Server_Command_ID as Server_Command_ID, ASD.Command_Name
from ADS_Server_Device_Command ADC
inner join ADS_Server_Command ASD on adc.Server_Command_ID = asd.Server_Command_ID
inner join ADS_Device dsn on adc.Device_ID = dsn.Device_ID
where dsn.Device_Serial_Number = '$dsn'
order by adc.Server_Device_Command_ID desc LIMIT 1";
$result = mysqli_query($con,$sqlFet);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
mysqli_close($con);
echo $row["Command_Name"];
Bellow is the ajax
$.ajax({
method: "GET",
url: "http://localhost:MyPort/server/toggleFetch.php",
//dataType: "json",
data: { Command_Name: tData , Device_Serial_Number: selectedVal },
success: function (data) {
var dt = data;
if (dt == "On") {
$("#cmn-toggle-7").prop('checked', true);
}
else if (dt == "Off") {
console.log('else');
$("#cmn-toggle-7").prop('checked', false);
}
},
error: function (xhr, status, error) {
alert(xhr.responseText, status, error);
//toastr.success('Data not fetched', '', { timeOut: 2000 })
//alert('Error');
}
});
Now when running the code i am not getting any error but still i am not getting my required result i.e. the toggle doesn't change it's state
For more information please see the image bellow
I don't know what's the problem, any help would be highly appreciated.
This error means, that AJAX didnt send Command_Name via GET. You will have to check variable tData if it contains some value.
First step: dont send command_name with AJAX to PHP script (This causes Error on Line 5!!), it is not needed. Second step: in Php script you will have to change echo $command_name, to echo result from DB based on $dsn. So echo result from DB.
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
echo $row["Command_name"]; //This should show ON/OFF state from DB to AJAX.
I am using select2 and ajax to query my database for terms under a certain taxonomy, but when I search the search boxes just hangs on "searching" without retrieving any results.
This is my html
<select multiple="" name="regions1[]" id="regions1" class="job-manager-multiselect select2-hidden-accessible" required="" tabindex="-1" aria-hidden="true"></select>
My jquery:
<script>
jQuery(function($) {
$(document).ready(function() {
$( "#regions1" ).select2({
ajax: {
url: "/ajax/connect.php",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return {
results: data
};
},
cache: true
},
minimumInputLength: 2
});
});
});
</script>
and my php code to query the database, I am looking to get all the term names under the taxonomy "job_listing_region"
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
try {
$conn = new PDO("mysql:host=$servername;dbname=mydatabase", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
// strip tags may not be the best method for your project to apply extra
layer of security but fits needs for this tutorial
$search = strip_tags(trim($_GET['q']));
// Do Prepared Query
$query = $conn->prepare("
SELECT * FROM (
SELECT wp_terms.name
FROM wp_terms
JOIN wp_term_taxonomy
ON wp_term_taxonomy.term_id = wp_terms.term_id
WHERE taxonomy = 'job_listing_region'
AND count = 0
) as T"
);
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);
// Make sure we have a result
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['name'], 'text' => $value['name']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
// return the result in json
echo json_encode($data);
And as you can see, I am retrieving my data, but the search just hangs.
Thanks in advance.
Found the solution here How to load JSON data to use it with select2 plugin
Needed to recreate my results like this
processResults: function (data) {
return {
results: $.map(data, function(obj) {
return { id: obj.id, text: obj.text };
})
};
}
So you need to change processResults to success and put the following into that function:
for(i=0;1<data.length;++i){
var currentObject = data[i];
var id = currentObject.id;
var text = currentObject.text;
//do what you need to here (Put things in a div, etc)
}
And from there, you can do something like this:
document.getElementById("search").innerHTML = document.getElementById("search").innerHTML+"<br />"+id+text;
I'm creating my project using OOP. I need to pass all the values inserted in the database in the form of array. And it's a multidimensional array. SO when I pass now via ajax as a 'text' datatype it displays array in console.log(). But I'm unsure if this is the correct way and how to display the value in a table form in jquery.
Below are the functions where the values returned to the object in another page.
public function selectType()
{
$sql="SELECT * FROM car_type";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$carType=array();
while($row = $stmt->fetch())
{
array_push($carType,$row['car_type']);
}
return $carType;
}
public function selectMaker()
{
$sql="SELECT * FROM car_maker";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$carMaker=array();
while($row = $stmt->fetch())
{
array_push($carMaker,$row['car_maker']);
}
return $carMaker;
}
ANd this is how I'm fetching the values to be passed to another page to be displayed to the user.
$setting = new setting($car_type,$car_maker,$rental_type,$rental);
//$setting->connection;
$setting->addCarType();
$setting->addCarMaker();
$setting->addRentalBy();
$carType=$setting->selectType();
$carMaker=$setting->selectMaker();
$json=array();
array_push($json,array("type"=>$carType,"maker"=>$carMaker));
echo $json;
Finally ajax to fetch and display data
$("#submit").on("click",function()
{
$("#set_setting").submit(function(){
data = $(this).serialize()
$.ajax({
type: "POST",
dataType: "html",
url: "submit_setting.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
//hide the form
$("#set_setting").slideUp("slow");
//show the result
for (i = 0; i < data.length; i++) {
console.log(data);//outputs array
$(".the-return").html(data);
}
}
});
return false;
});
});
You need to pass array as JSON and post it using name value pairs.
var data = {a:{'foo':'bar'},b:{'this':'that'}};
$.ajax({ url : '/',
type : 'POST',
data : {'data':JSON.stringify(data)},
success : function(){ }
});
And in backend (PHP):
$data = json_decode($_POST['data']);
print_r($data);
// Result:
// Array( "a" => Array("foo"=> "bar"), "b" => Array("that" => "this"))
I'm more of a designer but I need to grab some data from a database. I would be able to get what I need without problem using PHP but I'm creating a mobile app in Phonegap so can't use anything other than HTML, CSS or JS.
I've read that this can be done in a PHP file on the server, encoded to JSON and then grabbed in the HTML with Ajax.
Can anyone show me how do I do this, as simply as possible please?
Javascript file
$.ajax({
type: "GET",
dataType: "JSON",
url: "php/phpDb.model.php",
data: {
sataVariable: "here is some data send with GET method"
},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
php file (phpDb.model.php)
// Connect to database
$con = mysqli_connect("host", "userName", "password", "database")
or die('{ "error" : true, "errorMessage" : "Cannot connect to database '.mysqli_error($con).'"}');
// Query
$sqlCalling = "SELECT * FROM table WHERE ";
$result = mysqli_query($con,$sqlCalling);
$rowCalling = mysqli_fetch_array($resultCalling);
mysqli_close($con);
//getting column_1 and column_2
$column_1 = $rowCalling['column_1'];
$column_2 = $rowCalling['column_2'];
// Return a JSON parseable array
return array(
"column_1" => $column_1 ,
"column_2" => $column_2 ,
);
This solution is very generic, you will most likely just replace the name of the tables and the name of column with what they actually are in your database.
This is a very basic example using jQuery:
//hello_world.js
$.ajax({
url:'hello_world.php',
type: 'POST'
data: { 'var' : 'Hello World' }
}).done(function(response){
alert(response); //Well now alert an json string based on your query..
});
//hello_world.php
$STH = $DBH->prepare("SELECT blabla FROM table WHERE column = ?");
$STH->execute(array($_POST['var']));
$STH->setFetchMode(PDO::FETCH_ASSOC);
$resultQuery = $STH->fetchAll();
echo json_encode($resultQuery); //
I've been all over stackoverflow trying to figure this out. I'm using jQuery's ajax method to send in some form data, and PDO to prepare and return data based on the form input. I have one parameter in the prepared statement, which is taken from the form data, and set using the PDO bindParam method.
Using the form data, the json data I get back is undefined. If I hardcode the string parameter rather than use the form data, I get back the data I'm looking for. I've echoed out the exact value and type of the variable I'm passing in, and it's the same as the hardcoded string. I've tried explicitly setting the encoding to ensure it's utf8 as well.
This is what my php looks like (EDIT: includes execute method, which is included in my code, but got left out initially in the post):
$endorsers = array();
// Takes in the values from checkbox form data
foreach($_POST as $k => $v) {
if($v == 'on') {
$endorsers[] = $k;
}
}
// Set variable to first checkbox value
$endorser = $endorsers[0];
try {
$connection = new PDO('mysql:host=localhost;dbname=*****;charset=utf8', $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $connection->prepare('SELECT DISTINCT c.name AS cand_name, e.name AS end_name FROM candidates c JOIN end_cand ec ON (ec.end_id = c.id) JOIN endorsements e ON (e.abbrev = :endorser)');
$statement->bindParam(':endorser', $endorser, PDO::PARAM_STR);
$statement->execute();
$results = $statement->fetchAll();
if (isset($results)) {
echo json_encode($results);
} else {
$error = array('error_message' => 'Sorry, Charlie');
echo json_encode($error);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
And the ajax:
$("document").ready(function() {
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "get-endorsements.php",
success: function(data) {
console.log(data[0]);
console.log(data[1]);
}
})
})
});
If I do a regular form submission just to view the echoed json encoded results, I get the same thing whether using a hardcoded string or the form data - it's in this form:
[{"key1":"value1","key2":"value2"},{"key1":"value3","key2":"value4"}].
The data returned via ajax is undefined when using the form data variable though, and I can't figure out why this is making a difference.
SOLUTION:
$("form").submit(function(e) {
e.preventDefault();
var data = $(this).serialize();
console.log(data);
$.ajax({
type: "POST",
//contentType: "application/json; charset=utf-8",
dataType: "json",
data: data,
url: "get-endorsements.php",
success: function(data) {
console.log(data[0]);
console.log(data[1]);
}
})
})
Had to pass in data via $.ajax (thanks #David-SkyMesh), and NOT set the contentType (since this is the contentType for data passed to the server, not data received). Got myself very confused thinking that the data was available simply via the $_POST variable b/c it was, of course, when I tested the PHP return values with a standard post method on the form instead of via Ajax.
I think you lost:
$results->execute();
before
$results = $statement->fetchAll();
$endorsers = array();
// Takes in the values from checkbox form data
foreach($_POST as $k => $v) {
if($v == 'on') {
$endorsers[] = $k;
}
}
// Set variable to first checkbox value
$endorser = $endorsers[0];
try {
$connection = new PDO('mysql:host=localhost;dbname=*****;charset=utf8', $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $connection->prepare('SELECT DISTINCT c.name AS cand_name, e.name AS end_name FROM candidates c JOIN end_cand ec ON (ec.end_id = c.id) JOIN endorsements e ON (e.abbrev = :endorser)');
$statement->bindParam(':endorser', $endorser, PDO::PARAM_STR);
$results->execute();
$results = $statement->fetchAll();
if (isset($results)) {
echo json_encode($results);
} else {
$error = array('error_message' => 'Sorry, Charlie');
echo json_encode($error);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}