error in json function saving data into database - php

I have tried a lot but I have not been able to find out what is wrong with this function to save two values into database. It has been working fine for another function to save one value. It behaves very strange here. Sometimes send 'parent' value & sometimes stop sending it but never send msg value. Here is function. It works fine for one input i.e. parent but problems start with the addition of 2nd input.
<script>
function ADDLISITEM(form)
{
var parent = form.txtInput.value;
var msg = form.msgInput.value;
form.txtInput.value = "";
form.msgInput.value = "";
var url = "send_mysql.php"
var request = null;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
request=new XMLHttpRequest();
}
else
{// code for IE6, IE5
request=new ActiveXObject("Microsoft.XMLHTTP");
}
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader("Connection", "close");
request.onreadystatechange = function(){
if (request.readyState == 4) {
if (request.status == 200) {
//alert('POST');
} else {
alert(request.status); // fails here
}
}
}
request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"&msg=" +
encodeURIComponent(msg).replace(/%20/g, '+'));
}
</script>
This is send.php
$username = "babar";
$password = "k4541616";
$hostname = "localhost";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect
to MySQL");
$selected = mysql_select_db("spec",$dbh) or die("Could not select first_test");
//die(var_export($_POST,TRUE));
$parent = $_POST['parent'];
$msg = $_POST['msg'];
$name = 'Akhtar Nutt';
//$parent2 = json_decode($parent);
$msg_ID = '2q7b2sfwwe';
//$msg2 = json_decode($msg);
$query = "INSERT INTO msg2_Qualities(id,name,msg,msg_id,parent) VALUES
('','$name','$msg','$msg_ID','$parent')";
if(!mysql_query($query, $dbh))
{die('error:' .mysql_error())
;}
?>

Alter
request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"msg=" + encodeURIComponent(msg).replace(/%20/g, '+'));
to:
request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"&msg=" + encodeURIComponent(msg).replace(/%20/g, '+'));
You're missing the argument separator & in your query string...
You also might want to refrain from using values in $_REQUEST as they aren't reliable. If your script expects data from a POST then retrieve these values from $_POST.

Related

Check if two column match on SQL PHP

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.
I have two files, one that is html where I use ajax and one php file. When clicking on the button, nothing is being returned, I am not seeing any specific errors and I am sure that the value I put in are correct.
<script>
var ajax = getHTTPObject();
function getHTTPObject()
{
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} else {
//alert("Your browser does not support XMLHTTP!");
}
return xmlhttp;
}
function updateCityState()
{
if (ajax)
{
var reservation_id = document.getElementById("reservation_id").value;
var guest_last_name = document.getElementById("guest_last_name").value;
if(reservation_id)
{
var param = "?reservation_id=" + reservation_id + "&guest_last_name=" + guest_last_name;
var url = "test04.php";
ajax.open("GET", url + param, true);
ajax.onreadystatechange = handleAjax;
ajax.send(null);
}
}
}
function handleAjax()
{
if (ajax.readyState == 4)
{
var guest_full_name = document.getElementById('guest_full_name');
var unit_number = document.getElementById('unit_number');
var floor = document.getElementById('floor');
var key_sa = document.getElementById('key_sa');
if(!!ajax.responseText) {
var result = JSON.parse(ajax.responseText);
if(!!result){
guest_full_name.innerHTML = (!!result.guest_full_name) ? result.guest_full_name : '';
unit_number.innerHTML = (!!result.unit_number) ? result.unit_number : '';
floor.innerHTML = (!!result.floor) ? result.floor : '';
key_sa.innerHTML = (!!result.key_sa) ? result.key_sa : '';
}
}
}
}
</script>
<p id='employee_name'></p>
<p id='employee_age'></p>
<p id='safe_code'></p>
My test04.php
<?php
$conn = mysqli_connect("","","","");
$reservation_id = mysqli_real_escape_string($conn, $_GET['reservation_id']);
$guest_last_name = mysqli_real_escape_string($conn, $_GET['guest_last_name']);
$query = "SELECT reservation_id, guest_full_name, guest_last_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 ='".$reservation_id."'AND guest_last_name ='".$guest_last_name."";
$result = mysqli_query($conn, $query) or die(mysql_error());
$response = array();
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$response['guest_full_name'] = ($row['guest_full_name'] != '') ? $row['guest_full_name'] : '';
$response['unit_number'] = ($row['unit_number'] != '') ? $row['unit_number'] : '';
$response['floor'] = ($row['floor'] != '') ? $row['floor'] : '';
$response['key_sa'] = ($row['key_sa'] != '') ? $row['key_sa'] : '';
}
}
echo json_encode($response, true);
?>
I am not seeing any specific errors
Where are you looking?
Did you check the raw response from the PHP script or just look at what was rendered in your browser?
Did you verify that error logging is working and did you check your logs?
The logic of your PHP is unclear - your JSON data and the PHP array can't handle multiple records yet you process multiple records. It would be nice to implement REST properly. This should also apply authentication and use CSRF for security - but I'll assume you left those out for illustrative purposes.
Your code is not written to handle failures or missing data. Consider (noting all the differences with what you posted):
<?php
$conn = mysqli_connect("","","","");
$response = array();
$reservation_id = mysqli_real_escape_string($conn, $_GET['reservation_id']);
$guest_last_name = mysqli_real_escape_string($conn, $_GET['guest_last_name']);
$query = "SELECT reservation_id, guest_full_name
, guest_last_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 ='".$reservation_id."'
AND guest_last_name ='".$guest_last_name."";
$result = mysqli_query($conn, $query);
if (!$result) {
$response['status']=503
$response['msg']="Error";
trigger_error(mysql_error());
finish($response);
exit;
}
$response['status']=200;
$response['msg']='OK';
$response['guest_full_name'] = htmlentities($_GET['guest_last_name']);
$response['reservations']=array();
while($row = mysqli_fetch_assoc($result)) {
$response['reservations'][]=array(
'unit_number'=>$row['unit_number'],
'floor'=>$row['floor'],
'key_sa'=>$row['floor_sa']);
}
}
finish($response);
exit;
function finish($response)
{
header("HTTP/1.1 $response[status] $response[msg]");
header("Content-type: application/json");
echo json_encode($response, true);
}

Perform Server Side & Client Side Operations In One Project

I found an example that does exactly what I am after. My only issue is that this syntax calls a secondary file of book-suggestion.php If possible, I would like a way of performing all of this function in one page.
Here is step 1 - the client side
function book_suggestion()
{
var book = document.getElementById("book").value;
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "book_name=" + book;
xhr.open("POST", "book-suggestion.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//alert(xhr.responseText);
document.getElementById("suggestion").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
And here is part 2 - the server side
<?php
//provide your hostname, username and dbname
$host="";
$username="";
$password="";
$db_name="";
//$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
$con=mysql_connect("$host", "$username", "$password");
mysql_select_db("$db_name");
$book_name = $_POST['book_name'];
$sql = "select book_name from book_mast where book_name LIKE '$book_name%'";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))
{
echo "<p>".$row['book_name']."</p>";
}
?>
What do I need to do to combine these parts so that they are all in one file?
You could do it all one page, I use a .htaccess rewrite where everything is funneled through just one index page, so essentially doing the same thing. You just do the php above the output of your html and exit when done:
/index.php
<?php
# Create some defines
define('DB_HOST','localhost');
define('DB_NAME','database');
define('DB_USER','root');
define('DB_PASS','');
# Create a PDO connection, mysql_* is out of date and unsafe
# Review PDO, there are some presets to the connection that should be explored
# like emulated prepares and other such niceties
$con = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USER,DB_PASS);
# If there is a value posted, do action
if(!empty($_POST['book_name'])) {
# Bind parameters
$sql = "select book_name from book_mast where book_name LIKE ?";
$query = $con->prepare($sql);
$query->execute(array($book_name.'%'));
# Fetch normally
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo "<p>".$row['book_name']."</p>";
}
##*****THE IMPORTANT PART ******##
# Stop so you don't process the rest of the page in the ajax
exit;
}
?>
<!-- THE REST OF YOUR HTML HERE -->
<script>
function book_suggestion()
{
var book = document.getElementById("book").value;
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "book_name=" + book;
xhr.open("POST", "index.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//alert(xhr.responseText);
document.getElementById("suggestion").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
</script>

How to prevent saving data when ajax response is false?

I created a text filed for customer name. Already registered customer will show while clicking that text field. Only that registered customer can entry the data. I used ajax for prevent the new user addition.
this is the ajax:
function validateForm()
{
var customerName = document.getElementById('customerName').value;
var customerId = document.getElementById('customerId').value;
var getResponse=0;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
getResponse= xmlhttp.responseText;alert(getResponse);
if(getResponse=="0")
{
return false;
}
}
};
xmlhttp.open("GET", "customer_check_ajax.php?name="+customerName+"&id="+customerId, true);
xmlhttp.send();
}
and here is the ajax page customer_check_ajax.php :
<?php
require("../../config/config.inc.php");
require("../../config/Database.class.php");
require("../../config/Application.class.php");
if($_SESSION['travelType']=='Admin')
{
$check = 1;
}
else
{
$check = '';
$logId = $_SESSION['travelId'];
$proId = $_SESSION['proId'];
$check = "proId='$proId'";
}
$cusName = $_REQUEST['name'];
$cusId = $_REQUEST['id'];
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$qry="select * FROM ".TABLE_ACCOUNTS." WHERE ID='$cusId' and accountName='$cusName' and proId='$proId'";
$res = mysqli_query($connection, $qry);//echo $qry;
$num = mysqli_num_rows($res);
if($num>0)
echo '1';
else
echo '0';
?>
here i would get the responses as 0 for new user and 1 for already registered user. But i want to stop saving data when new user addition. Please help me.
You are making Asynchronous request and the answer of the ajax will come after the function is over ..
To do what you want you must do synchronous ajax request
xmlhttp.open("GET", "customer_check_ajax.php?name="+customerName+"&id="+customerId, false); // `false` makes the request synchronous

AJAX PHP Database NOT WORKING no errors

I am new to AJAX and am trying to insert form data into a database using ajax and php. It is simply not working, I had errors to start off but now there are no more errors and the database doesn't update and there is no response text. Please Help!
AJAX
function submit(){
var vid = <?php echo $user['vid'] ?>;
var type = document.getElementById("type").value;
var rules = document.getElementById("rules").value;
var comments = document.getElementById("comments").value;
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("page").innerHTML = xhttp.responseText;
}
}
xhttp.open("POST", "/content/training/request/submit.php", false);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("vid="+vid+"&type="+type+"&rules="+rules+"&comments="+comments);
}
</script>
PHP FILE AJAX IS CALLING:
<?php
require("http://".$_SERVER["HTTP_HOST"]."/config/db.php");
$stmt = $db->prepare("INSERT INTO trainingRequests (vid, type, rules, comments, timeSubmitted) VALUES (:vid,:type,:rules,:comments,:timeSubmitted)");
$stmt->bindParam(':vid', $vid);
$stmt->bindParam(':type', $type);
$stmt->bindParam(':rules', $rules);
$stmt->bindParam(':comments', $comments);
$stmt->bindParam(':timeSubmitted', $time);
$vid = $_POST["vid"];
$type = $_POST["type"];
$rules = $_POST["rules"];
$comments = $_POST["comments"];
$time = time();
$stmt->execute();
echo "Submitted!";
Don't use an HTTP URL in require. When you access the PHP script through the webserver, it runs the script (in another server instance, so it doesn't affect the current script), it doesn't return the script contents. Change it to:
require("../../config/db.php");

Trouble trying to populate a dropdown menu with a json array returned by php

When I am trying to populate my dropdown menu with ajax I am not able to get the desired values into the dropdown menu.
Could you tell me where the mistake is? The accno returned from php is json array to be filled in the drop down menu.
function showACC(str)
{
if (str == "")
{
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var doc = window.document.createElement("doc");
var myarray = JSON.parse($source);
var dropdown = document.getElementById("DropdownList");
for (var i = 0; i < myArray.length; ++i) {
dropdown[dropdown.length] = new Option(myArray[i], myArray[i]);
}
}
}
xmlhttp.open("GET","data.php?q="+str,true);
xmlhttp.send();
}
}}
<?php
/*
Connecting to the database
*/
$dbuser = 'root';
$dbpass = 'neel';
$host = 'localhost';
$db = 'library';
mysql_connect($host, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
/*
Executing SQL query
*/
$queryResult = mysql_query('SELECT acc_no FROM lib_iss_ret where stu_id="07751a1035"') or die(mysql_error());
$source = array();
/*
Building the source string
*/
while ($row = mysql_fetch_array($queryResult)) {
array_push($source, $row['acc_no']);
}
/*
Printing the source string
*/
echo json_encode($source);
?>
Problem is that, I suppose, you think that php variable $source is available in your javascript with the same name. This is a mistake. PHP knows nothing about javascript.
Response from server comes as a responseText property of xmlhttp object. So you should parse xmlhttp.responseText instead of $source:
var myarray = JSON.parse(xmlhttp.responseText);
To check what you get you could use alert or console.log with developers console.

Categories