Issue with ODBC PDO and Ajax - javascript

I'm working on a project for work, and I've run into some issues.
I'm creating dynamic elements based on PDO queries and ajax, and I've searched and searched to resolve my specific issue. Basically, I have two select boxes that are dynamically added from a database response, and regardless of which option is selected, all of the dynamically created buttons are made exactly the same. Selected Rack_G
I've also created timers for each Rack/Tray, and the same issue arises for the timers. There is only a record for Rack H Tray 8.Rack H Tray 8
My db_connect.php
$first = "odbc:TIMERODBC";
$user = "exampleuser";
$pass = "examplepass";
$pdo = new PDO($first,$user,$pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Below is my class.db.php file that queries my database
public function selectOven()
{
try{
$stmt = $this->conn->query("SELECT sub.equipName FROM STR_EquipSubCategory sub LEFT JOIN STR_EquipCategory category ON category.categoryID = sub.categoryID GROUP BY sub.equipName");
$data = $stmt->fetchAll();
foreach($data as $row)
{
echo "<option value=" . $row['equipName'] . "><strong>" . $row["equipName"] . "</strong></option>";
}
}
catch(PDOException $e) {
return $e->getMessage();
}
}
public function selectRack($oven) {
try{
$sth = $this->conn->prepare('SELECT storageBayName FROM STR_EquipSubCategory WHERE equipName =:oven');
$sth->bindParam(':oven',$oven,PDO::PARAM_STR);
$sth->execute();
$data = $sth->fetchAll();
echo "<select id='rack' class='custom-select mb-2'>Rack";
echo "<option value ='Select Rack'></option>";
foreach($data as $row)
{
echo "<option id=".$row['storageBayName']." value=". $row["storageBayName"] . ">". $row["storageBayName"] . "</option>";
}
echo "<select>";
}
catch(PDOException $e) {
return $e->getMessage();
}
}
public function selectRackTray($oven,$rack) {
try{
$sth = $this->conn->prepare("EXECUTE STR_GetTimerOpenTraysSp ?, ?");
$sth->bindParam(1,$oven,PDO::PARAM_STR);
$sth->bindParam(2,$rack,PDO::PARAM_STR);
$sth->execute();
$data = $sth->fetchAll();
foreach($data as $row)
{
if(($row['material'] != 0) ) {
echo "<div class='row'>";
echo "<button type='button' id='tray".$row['storageBayName']." ". $row['sublevelID'] ."' class='btn btn-danger' data-toggle='popover'>Tray " .$row['sublevelID'] . "</button>";
echo "</div>";
}
else {
echo "<div class='row'>";
echo "<button type='button' id='emptyTray".$row['storageBayName']. " ".$row['sublevelID'] ."' class='btn btn-success'>Tray " .$row['sublevelID'] . "</button>";
echo "</div>";
}
}
}
catch(PDOException $e) {
return $e->getMessage();
}
}
And now my ajax jQuery & Ajax
$(document).ready(function(){
$("select#oven").change(function(){
var selectedOven = $("#oven option:selected").val();
$.ajax({
type: "POST",
url: "process-request.php",
data: { oven : selectedOven }
}).done(function(data){
$("#rackResponse").html(data);
});
});
});
$(document).on('change', "select#rack", function() {
var selectedRack = ($(this).val());
var selectedOven = ($("#oven option:selected").text());
$.ajax({
type: "POST",
url: "process-a-request.php",
data:
{
rack: selectedRack,
oven: selectedOven
},
}).done(function(data){
$("#tResponse").html(data);
});
});
If anyone can help me out, I would greatly appreciate it. Note, I'm not super experienced with PHP, but everything else seems to be working correctly.

My problem wasn't with ajax, php, or the PDO statements. I ran some tests on my stored procedure that I was calling, and found the problem there. Thanks for attempting to help me out.

Related

How to display values in JS from a PHP array that was posted from jQuery

I have a button called rename that when pushed, executes in jQuery a rename.php file. Inside that php file the program selects data from a mysql, creates an array with that data, and processes an array in to json_encode($array);. How can I then get that json encoded array and echo it out into javascript?
I'm trying to echo the array out so that javascript displays my images src's.
This is my second line of ajax so I just wrote the javascript out as if it were php because I'm not sure of the commands or structure in js.
$.ajax
(
{
url:"test4.php",
type: "GET",
data: $('form').serialize(),
success:function(result)
{
/*alert(result);*/
document.getElementById("images_to_rename").innerHTML = foreach(jArray as array_values)
{
"<img src=\""array_values['original_path']"/"array_values['media']"/>";
}
}
}
);
and my jQuery php file:
<?php
include 'db/mysqli_connect.php';
$username = "slick";
if(empty($_GET['image_name']))
{
echo '<div class="refto" id="refto">image_name is empty</div>';
}
else
{
echo '<div class="refto" id="refto">image_name is not empty</div>';
foreach($_GET['image_name'] as $rowid_rename)
{
//echo '<br><p class="colourful">rowid_refto: '.$rowid_refto.'</p><br>';
$active = 1;
$command = "Rename";
$stmt = $mysqli->prepare("UPDATE ".$username." SET active=?, command=? WHERE rowid=?");
$stmt->bind_param("isi", $active, $command, $rowid_rename);
$stmt->execute();
$stmt->close();
}
//go to database, get parameters of sort
$command = "Rename";
$active = 1;
$stmt = $mysqli->prepare("SELECT original_path, media FROM " . $username . " WHERE active=? and command=?");
$stmt->bind_param("is", $active, $command);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$arri[] = $row;
}
foreach($arri as $rows) //put them into workable variables
{
$rowt = $rows['original_path'];
$rowy = $rows['media'];
//echo 'rows[\'original_path\'] = '.$rows['original_path'].''.$rows['media'].'';
}
$stmt->close();
echo json_encode($arri);
?>
<script type="text/javascript">
var jArray= <?php echo json_encode($arri); ?>;
</script>
<?php
}
echo "something2";
?>
My PHP file is a jQuery url:"test4.php", type: "GET", and is not the main file. The main file is called main.php and the test4.php is something that's called in jQuery when the user clicks on rename.
Somebody suggested console log so here's what chrome says:
<div class="refto" id="refto">image_name is not empty</div>[{"original_path":"Downloads","media":"shorter.jpg"},{"original_path":"Album 2","media":"balls.jpg"}] <script type="text/javascript">
var jArray= [{"original_path":"Downloads","media":"shorter.jpg"},{"original_path":"Album 2","media":"balls.jpg"}];
</script>
something2
Your ajax php file isn't render in browser, then the variable jArray is undefined. With your case, let return php file to json and you can get it as variable in result.
<?php
include 'db/mysqli_connect.php';
$username = "slick";
if (empty($_GET['image_name'])) {
//echo '<div class="refto" id="refto">image_name is empty</div>';
} else {
//echo '<div class="refto" id="refto">image_name is not empty</div>';
foreach ($_GET['image_name'] as $rowid_rename) {
//echo '<br><p class="colourful">rowid_refto: '.$rowid_refto.'</p><br>';
$active = 1;
$command = "Rename";
$stmt = $mysqli->prepare("UPDATE " . $username . " SET active=?, command=? WHERE rowid=?");
$stmt->bind_param("isi", $active, $command, $rowid_rename);
$stmt->execute();
$stmt->close();
}
//go to database, get parameters of sort
$command = "Rename";
$active = 1;
$stmt = $mysqli->prepare("SELECT original_path, media FROM " . $username . " WHERE active=? and command=?");
$stmt->bind_param("is", $active, $command);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$arri[] = $row;
}
foreach ($arri as $rows) { //put them into workable variables
$rowt = $rows['original_path'];
$rowy = $rows['media'];
//echo 'rows[\'original_path\'] = '.$rows['original_path'].''.$rows['media'].'';
}
$stmt->close();
echo json_encode($arri);
//stop render here
die();
}
?>
php file need return only json string. Then we'll get result as json variable in javascript.
And Js:
$.ajax
(
{
url:"test4.php",
type: "GET",
data: $('form').serialize(),
success:function(result)
{
var jArray = JSON.parse(result);
/*alert(result);*/
var txt = "";
jArray.forEach(function(array_values){
txt += `<img src=\""array_values.original_path."/"array_values.media"/>`;
})
document.getElementById("images_to_rename").innerHTML = txt;
}
}
);

Dynamically show SQL query on a PHP page on click, using AJAX

Basically, I want to retrieve a certain product after clicking on an element. I'm using AJAX to pass the variable, and PHP to display the SQL query. I will use the product id on a WHERE statement, to retrieve and display the correct product.
Here is part of my code so far:
<html>
<head>
<title>Left Frame</title>
<link href='http://fonts.googleapis.com/css?family=Indie+Flower' rel='stylesheet' type='text/css'>
<link href="stylesheets/main.css" rel="stylesheet" type="text/css">
<script src="javascripts/jquery-1.11.2.js">
</script>
</head>
<body>
<div class="container">
<div id="bottomHalf">
<img id="blank" src="assets/bottom_half.png" style= "z-index: 5" >
<img src="assets/frosen_food.png"
usemap="#Map2"
border="0"
id="frozen"
style="z-index: 0;
visibility:hidden;" >
<map name="Map2">
<area shape="rect" coords="7,95,126,146" alt="Hamburger Patties" href="#" id="hamburgerPatties">
</div>
</div>
<script language="javascript">
$("#hamburgerPatties").click(function(){
var hamburgerPatties = "1002";
$.ajax({
type:"GET",
url: "topRightFrame.php",
data: "variable1=" + encodeURIComponent(hamburgerPatties),
success: function(){
//display something if it succeeds
alert( hamburgerPatties );
}
});
});
</script>
</body>
</html>
Part of my PHP code:
<?php
$product_id =(int)$_GET['variable1'];
$servername = "************";
$username = "************";
$password = "*************";
$dbname = "poti";
$tableName = "products";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM $tableName ";
$result = $conn->query($sql);
// Display all products on the database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Product ID: " . $row["product_id"]. " - Product Name: " . $row["product_name"]. " Unit Price:" . $row["unit_price"]. "<br>";
}
} else {
echo "0 results";
}
// Display product I clicked on the other frame
if (isset($GET['variable1'])) {
$sql = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
$result = $conn->query($sql);
if ($result) {
echo '<table>';
while ($row = $result->fetch_assoc())
{
echo '<tr>';
echo '<td>', "Product ID: " . $row["product_id"]. " - Product Name: " . $row["product_name"]. " Unit Price:" . $row["unit_price"]. "<br>";
echo '</tr>';
}
echo '</table>';
}
}
$conn->close();
?>
I'm able to display all the products. But starting from the ifsset statement, the code no long works. I get no error message or anything. How can I solve this? I'm pretty new to PHP.
EDIT: Ok, I managed to get the product I want when I hard code the product id. Now I need to get this variable using javascript.
You have syntax errors in your if statements.
When you're setting if, you should enclose the statement in braces:
instead of if something : do if(something): and then end it with endif; (when using colons :)
// Display product I clicked on the other frame
if (isset($GET['variable1'])):
$query = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
$result = mysqli_query($conn, $query);
if ($result):
echo '<table>';
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>', $row['product_id'], '</td>'; // and others
echo '</tr>';
}
echo '</table>';
endif;
endif;
Or, use {} braces instead of colons :
// Display product I clicked on the other frame
if (isset($GET['variable1'])){
$query = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
$result = mysqli_query($conn, $query);
if ($result){
echo '<table>';
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>', $row['product_id'], '</td>'; // and others
echo '</tr>';
}
echo '</table>';
}
}
You have syntax error in if block. use {} for if block also use echo instead of pure html tag(table). This error prevents successful state of ajax request. also don't forget to close table.
if ($result)
{
echo '<table>';
while ($row = $result->fetch_assoc())
{
echo '<tr>';
echo '<td>', $row['product_id'], '</td><td>'; // and others
echo '</tr>';
}
echo '</table>';
}
and the ajax code to display php result instead of test alert would be this:
<script language="javascript">
$("#hamburgerPatties").click(function(){
var hamburgerPatties = "1002";
$.ajax({
type:"GET",
url: "topRightFrame.php",
data: "variable1=" + encodeURIComponent(hamburgerPatties),
success: function(data){
alert(data);
}
});
});
</script>

Creating jQuery array variable and Transferring array to another page PHP

I currently have this function exactly how I want it except for the jQuery at the bottom in which I am only alerting and not creating a real variable. It all works but I am stuck on how I can take all of the data from the jQuery script and then make it into a variable so that I can bring it to another page? Any ideas, NEED HELP!
function getGrade($id, $grades_array) {
$counter = 0;
$sql = "Select grade FROM grades";
$result = mysql_query($sql) or die (mysql_error());
echo '<select name="grades_selected" multiple="multiple" id="grades_selected">';
while ($row = mysql_fetch_array($result)) {
if ($row['grade'] != $grades_array[$counter]) {
echo "<option>" . $row['grade'] . "</option>";
} else {
echo "<option selected=" . $row['grade'] . ">" . $row['grade'] . "</option>";
$counter = $counter + 1;
}
}
mysql_free_result($result);
echo '</select>';
$_SESSION['test'] = $grades_array;
?>
<script>
$(document).ready(function() {
$('#grades_selected').change(function() {
alert($(this).val());
});
});
</script>
<?
}
You need to use ajax within on change function:
$(document).ready(function() {
$('#grades_selected').change(function() {
var variable = $(this).val();
$.ajax({
type: 'post',
url: 'target_page.php',
data: {variable : variable},
success: function (res) {
alert(res);
}
});
});
});
On target_page.php:
echo $_POST['variable'];

How to properly load one ajax request after another

I am creating a messaging system for a website that I am making. Basically, it consists of clicking one button and two Ajax Requests afterwards. I am not even sure I am going about this the right way. On click of the button the first Ajax starts to call. The first ajax request loads a file that loads the style of the messages and retrieves them from a database. The problem I am having is that the first request sometimes takes to long to finish and the other request does not get complete. Another problem I am having is that if I put an "animation delay" type thing on it then it will look like the page it running slow. You can run an example at "http://www.linkmesocial.com/linkme.php?activeTab=mes" you must type or copy and past the whole length for it to work otherwise you will redirect to the login page. Any advice would be AWESOME! If there is some easier way to set up a messaging system please feel free to give me some advice or direct me to a tutorial. THANK YOU SO MUCH!
I would also like the know if this is a good practice. Please :)
My Original file. On click of class "mes_tab" a form is submitted. also the function mes_main() is called.
session_start();
$username = $_SESSION['user'];
$messages = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username'");
echo "<div id=\"mes_main-bar_top\" class=\"center\">Messages</div>";
echo "<div id=\"mes_main\">";
echo "<table id=\"mes_main-allView\" class=\"left\">";
echo "<td class=\"mes_tab-change\" >^</td>";
$from=array("","","", "", "", "", "", "");
for ($msgCount = 0; $msgCount < 8; $msgCount++){
$row = mysqli_fetch_array($messages);
$from[$msgCount] = $row['sender'];
for ($prev = 0; $prev < $msgCount; $prev++)
{
if ($from[$msgCount] == $from[$prev] )
{
$cont = true;
break;
}
}
if ($cont)
{
$cont = false;
continue;
}
if ($row['message'] == ""){
break;
}
echo "<tr><td class=\"mes_tab\" onclick=\"mes_main('" . $row['sender'] . "')\">";
echo "<h3 class=\"center\">" . $row['sender'] . "</h3>";
echo "<form id=\"" . $row['sender'] . "\" >";
echo "<input name=\"sender\" value=\"" . $row['sender'] . "\" hidden/>";
echo "<input name=\"id\" value=\"" . $row['id'] . "\" hidden/>";
echo "</form>";
echo "</td></tr>";
}
if ($msgCount == 8)
{
echo "<td id=\"mes_tab-change_bottom\" class=\"mes_tab-change\">V</td>";
}
echo "</table> <!-- end mes_main-allView -->";
echo "<div id=\"mes_main-mesView\" class=\"right\">";
echo "</div> <!-- end mes_main-mesView -->";
echo "</div> <!-- end mes_main -->";
mes_main() function from above. The two ajax functions inside are what I am referring to in the post above.
function mes_main(x)
{
var sender = x;
$( sender ).submit(function( event ) {
event.preventDefault();
});
ajax_req_mes("scripts/home/php/mes_load.php?" + sender , "mes_main-mesView");
ajax_req_mes("scripts/home/php/mes_content.php?" + sender ,"mes_content");
}
mes_load.php
the $sender var is created by passing the sender username through the URL. That is why I do php explode on the url.
session_start();
$username = $_SESSION['user'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$sender = explode('?', $url);
$recieved = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username' AND sender='$sender[1]'");
$sent = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$sender[1]' AND sender='$username'");
echo "<div id=\"mes_content\"></div>";
echo "<div id=\"mes_field\" class=\"right\"></div>";
mes_content.php
session_start();
$username = $_SESSION['user'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$sender = explode('?', $url);
$recieved = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username' AND sender='$sender[1]'");
$sent = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$sender[1]' AND sender='$username'");
echo "<table id=\"mesView-table\">";
$REC = array();
$SENT = array();
$ID = array();
for ($i = 0; $i < 25; $i++)
{
$rec = mysqli_fetch_array($recieved);
$sent = mysqli_fetch_array($sent);
if ($rec['id'] > 0)
{
$REC[$i] = $rec['id'];
}
if ($sent['id'] > 0)
{
$SENT[$i] = $sent['id'];
}
}
$ID = array_merge($SENT, $REC);
sort($ID);
for ($x = 0; $x < count($ID); $x++)
{
$key = $ID[$x];
$result = mysqli_query($con, "SELECT * FROM messages WHERE id = '$key'");
$res = mysqli_fetch_array($result);
if (in_array($key, $REC))
{
echo "<tr><td class='mes_recieved'>";
echo $res['message'];
echo "</tr></td>";
}
elseif (in_array($key, $SENT))
{
echo "<tr><td class='mes_sent'>";
echo $res['message'];
echo "</tr></td>";
}
}
echo "</table>";
Set async to false in your ajax requests!That's how the second one will wait for completing the first one and then start.
Also you can catch the on success and on error for the purposes you have.
Just use the "success" and "error" callbacks.
Also you could use the "done" callback
But, IMO, for that kind of problem I think a better alternative would be using Websockets
EDIT:
Here is some example of how you could do it:
jQuery.ajax({
type : "POST",
data : {msg:"your message"}
url : "http://fu.com/myfile.php",
success: function(response){
//Do something with your response
}
}).done(secondCall());
function secondCall(){
jQuery.ajax({
type : "POST",
data : {data:"data"}
url : "http://fu.com/myfile.php",
success: function(response){
//Do something with your response
}
});
}
EDIT2:
For visibility, here is a tutorial using websockets: http://www.sanwebe.com/2013/05/chat-using-websocket-php-socket

calling a php function in javascript

I dont know how to use ajax in my problem:
I have a function in php (assign) that update a temporary table in database, I want to when user user click on a button (feedback function that is defined in javascript) this function (assign) run, what should I do?
<script>
function feedback(){
var boxes = document.getElementsByClassName('box');
for(var j = 0; j < boxes.length; j++){
if(boxes[j].checked) {
assign(1);
}
else{
assign(0);
}
}
}
</script>
<?php
$con = mysql_connect("localhost", "root", "")
or die(mysql_error());
if (!$con) {
die('Could not connect to MySQL: ' . mysql_error());
}
mysql_select_db("project", $con)
or die(mysql_error());
$result = mysql_query("select * from words");
echo "<table border='1'>
<tr>
<th>word</th>
<th>meaning</th>
<th>checking</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['word'] . "</td>";
$idd= $row['id'] ;
echo "<td>". "<div class='hiding' style='display:none'>".$row['meaning']."</div>"."</td>";
echo "<td>";
echo "<input class=\"box\" name=\"$idd\" type=\"checkbox\" value=\"\"> ";
echo "</td>";
echo "</tr>";
}
echo "</table>";
function assign($checkparm){
//mysql_query("update words set checking=$checkparm ");
mysql_query("create TEMPORARY TABLE words1user1 as (SELECT * FROM words) ");
mysql_query("update words1user1 set checking=$checkparm ");
}
mysql_close($con);
?>
<button onclick="ShowMeanings()">ShowMeanings</button>
<button onclick="feedback()">sendfeedback</button>
There is only one way to call a php function after the page is loaded:
1.ajax:
function callPHP() {
$.ajax ({
url: "yourPageName.php",
data: { action : assign }, //optional
success: function( result ) {
//do something after you receive the result
}
}
in your PHP, write
if ($_POST["action"] == "assign")
{
assign(your parameters); //You need to put the parameters you want to pass in
//the data field of the ajax call, and use $_POST[]
//to get them
}
There are many great guides on the internet. I will however suggest you get too know JQuery. It will help you on your learning curve.
function ajaxCall(){
$.ajax({
type: "GET",
url: "scripts/on/serverside.php"
});
};

Categories