I'm fetching value from Mysql in DropDown. Based on user selection a table should be populated.
But whatever I'm selecting in dropdown, it's not getting sent to server.
Please find below code:
Fetch value in dropdown
<?php
$result = mysqli_query($con, "SELECT name FROM restaurants;");
echo "<select name='sub1' id='resdropdown' onchange = 'showMenu(this.value)'>";
while ($row = mysqli_fetch_array($result)){
echo "<option value='" . $row['name'] ."'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
Script to send value to server
function showMenu(str) {
/* var x = document.getElementById('resdropdown');
str = x.value;
alert(str); */
var ajax = new XMLHttpRequest();
var method = "GET";
var asynchronous = true;
var data = str;
ajax.open(method, "test.php?q="+data, asynchronous);
//sending ajax request
ajax.send();
ajax.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("testajaxid").innerHTML = this.responseText;
alert(str);
}
};
}
Get Response from server
$q = $_GET['data'];
$result = mysqli_query($con, "SELECT * FROM items where id = '".$q."'");
while($row = mysqli_fetch_array($result))
{
echo '<tr><td>'.$row["name"].'</td><td>'.$row["price"].'</td>';
echo '<td><div class="input-field col s12"><label for='.$row["id"].' class="">Quantity</label>';
echo '<input id="'.$row["id"].'" name="'.$row['id'].'" type="text" data-error=".errorTxt'.$row["id"].'"><div class="errorTxt'.$row["id"].'"></div></td></tr>';
}
Your $_GET variable should be $_GET['q'] instead of $_GET['data'], because you set the URL to test.php?q=data.
Also, you shouldn't put raw user provided data in SQL queries, use prepared statement instead, because of risks of SQL injection.
Related
I try to make when you select the city, show the district of this city. I am adding my code to below. I made it on local and it has not any issue but whenever I add this on online it's show noting. It consists of 3 parts; First part is input area, second part is Javascript area and last part for connect to database and get date.
here's input area:
<form action="#institutions" method="post">
<p>Select City*</p>
<select class="institutionsSelect" name="cityinstitutions" id="orders-institutions" onchange="getDetaiinstitutions(this.value);">
</select>
<p>Select District </p>
<select class="institutionsSelect" name="districtinstitutions" id="order-details-institutions">
</select> <br>
<input type="submit" name="institutionsList" autocomplete="off" value="LİST OF INSTITUTIONS" class="btn btn-md btn-blue black-hover" >
</form>
Here's javascript area;
<script type="text/javascript">
function getOrdersinstitutions() {
var ajax = new XMLHttpRequest();
ajax.open("GET", "get-orders-institutions.php", true);
ajax.send();
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
var html = "<option>Select City</option>";
for (var a = 0; a < response.length; a++) {
html += "<option value='" + response[a].cityId + "'>";
html += response[a].cityName;
html += "</option>";
}
document.getElementById("orders-institutions").innerHTML = html;
}
};
}
function getDetailinstitutions(cityId) {
var ajax = new XMLHttpRequest();
ajax.open("GET", "get-order-detail-institutions.php?cityId=" + cityId, true);
ajax.send();
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
var html = "<option></option>";
for (var a = 0; a < response.length; a++) {
html += "<option value='" + response[a].districtId + "'>";
html += response[a].districtName;
html += "</option>";
}
document.getElementById("order-details-institutions").innerHTML = html;
}
};
}
getOrdersinstitutions();
And here's is datebase connection areas. There are 2 different page one call get-orders-institutions.php and other is get-order-detail-institutions.php
**get-orders-institutions.php **
<?php
$connection = mysqli_connect("localhost", "userName", "password", "ys_table");
$sql = "SELECT * FROM ys_city";
$result = mysqli_query($connection, $sql);
$data = array();
while ($row = mysqli_fetch_object($result))
array_push($data, $row);
echo json_encode($data);
?>
and get-order-detail-institutions.php
<?php
$cityId = $_GET["cityId"];
$connection = mysqli_connect("localhost", "userName", "password", "ys_table");
$sql = "SELECT * FROM ys_district WHERE cityId='$cityId'";
$result = mysqli_query($connection, $sql);
$data = array();
while ($row = mysqli_fetch_object($result))
array_push($data, $row);
echo json_encode($data);
?>
Here all i used codes.
As the first option, select city should be written, but it is an empty input line. Whenever i change datebase setting i mean when i write wrong username and password Select City appear.
By the way these codes work fine in local with exactly the same codes with the same database.
Here is online page
online input area
here is local
Local input area
Local input result
What i suppose to do for take same result in online like local?
thanks in advance
UPDATE: I find what's the problem but i dont know how can i fix it.
If more than 16 rows of data are loaded into the ys_city table, it gives an error like this
How can i fix it?
My Ajax request has failed. Javascript
if (this.readyState == 4 && this.status == 200) {
document.getElementById("orderSummary").innerHTML = "success";
document.getElementById("product").innerHTML = this.responseText;
} else {
document.getElementById("orderSummary").innerHTML = "failure";
this js code send a get request to my php file. Now i output text to orderSummary to see where my code fail. Apparently the status did not go 4 and 200 which is success
is that a networking issue or codes. code is very simple so no syntx issue
<?php
include "config.php";
$prodid = intval($_GET["prodcat"]; // prod id whether is is skin or fragrance
$sql = "SELECT name, detail, price FROM products WHERE type=" . $prodid;
$result = mysqli_query($con,$sql);
$product_arr = array();
while( $row = mysqli_fetch_array($result)){
echo "<select>";
echo "<option>" . $row["name"] . "</option>";
}
echo "</select>";
?>
Recently I have been assigned a group project for a college class and I will need to query a customers name from a database and then print out the rest of the row in form fields. I have the select menu working correctly and it will print to the form field. However, the problem occurring is the query results will only show the last row in the MYSQL table I selected. Any help here would be greatly appreciated. I have been spinning my wheels for a few days on this issue. I am only a beginner coder, so it might be a little messy.
Thanks,
Connection.PHP File
<?php
function Connect()
{
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "medley";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);
return $conn;
}
?>
My Query Page
<?php
require 'connection.php';
$conn = Connect();
$sql = "SELECT * FROM cust_info";
$result = $conn->query($sql);
echo "<select id='firstName' name='firstname' onchange=populatesecondbox()>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['F_Name'] . "', '" . $row['L_Name'] . "'> " . $row['F_Name'] . " " . $row['L_Name'] . "</option>";
$pphone = $row['P_Phone'];
}
echo "</select>";
?>
<input id="secondinputbox" type="text" />
<script type="text/javascript">
function populatesecondbox(val) {
var dropdown = document.getElementById("firstName");
var pphone = document.getElementById("secondinputbox");
var secondfname = document.getElementById("thirdinputbox");
var str = "<?php echo $pphone ?>";
var sfname = "<?php echo $sfname ?>";
pphone.value = str;
secondfname.value = sfname;
}
</script>
Instead of using
$row = mysqli_fetch_array($result)
on line 10, use
$row = $result->fetch_assoc()
or
$row = $result->fetch_array()
The difference between fetch_assoc and fetch_array is that fetch_array contains both numeric indices and named indices. For example echo $row[0] will output as same as echo $row['id']. Whereas, fetch_assoc only contains named indices.
Based on the provided loop statement
$pphone = $row['P_Phone'];
$pphone is getting assigned to the last row on termination of the loop because each iteration is overriding $pphone with the current row until at which point in the loop $pphone gets the last value.
Instead of using
$pphone = $row['P_Phone'];
Try the following in the loop.
$pphone[] = $row['P_Phone'];
Your concatenated phones should be provided after the loop.
$pphones = "['".join("','" , $pphone)."']";
In your js script tag just get $pphones as a string;
var pphones = <?php echo $pphones; ?>;
ddl = document.getElementById('firstname');
pphone.value = pphones[ddl.selectedIndex];
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
I am using AJAX in order to access data from a php file.
I have problem with the format of retrieved data from database, please help.
So, this is my ajax function splice. It retrieves data from find_account.php
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
form_prof.prof_id.value = req.responseText;
form_prof.prof_name.value = req.responseText;
form_prof.prof_username.value = req.responseText;
form_prof.prof_password.value = req.responseText;
}
else {
alert("Problem in retrieving the XML data:\n" + req.statusText);
}
}
}
find_account.php
<?php
include("connect.php");
session_start();
$account = $_GET['account'];
$query = "SELECT * FROM profs WHERE profs_name = '".$account."'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if(empty($num))
{
echo 'DATA NOT FOUND';
}
else
{
$arr = mysql_fetch_array($result);
$id = $arr['profs_number'];
$name = $arr['profs_name'];
$username = $arr['profs_username'];
$password = $arr['profs_password'];
}
header("Content-type: text/plain");
echo $id;
echo $name;
echo $username;
echo $password;
?>
and I have 4 input boxes in my HTML from where the req.responseText puts the value
and everytime I search the name in the input field for example:
Search: [ Dorothy Perkins ]
The output goes like [id,name,username,password]:
[20111Dorothy Perkinsdperkins#mail.com123456] [same with 1st field] [same] [same]
Wherein I want it to be like...
[20111] [Dorothy Pekins] [dperkins#mail.com] [123456]
Where [ ] are input fields.
Please help me arrange my format, I am so confused. I am new to this.
You can encode return values in json before sending back.
In PHP
<?php
include("connect.php");
session_start();
$account = $_GET['account'];
$query = "SELECT * FROM profs WHERE profs_name = '".$account."'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if(empty($num))
{
$returnValues = 'DATA NOT FOUND';
}
else
{
$arr = mysql_fetch_array($result);
$returnValues = json_encode($arr);
}
echo $returnValues;
?>
In Javascript
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
req = JSON.parse(reg);
form_prof.prof_id.value = req.id;
form_prof.prof_name.value = req.name;
form_prof.prof_username.value = req.username;
form_prof.prof_password.value = req.password;
}
else {
alert("Problem in retrieving the XML data:\n" + req.statusText);
}
}
}
You have to write the data in some format from your PHP code (XML, json, or simply separate the values with a comma), and parse it from your javascript.
For example, in PHP:
echo $id . "," . $name . "," . $username . "," . $password;
And then in the javascript:
values = req.responseText.split(",");
form_prof.prof_id.value = values[0]
form_prof.prof_name.value = values[1];
form_prof.prof_username.value = values[2];
form_prof.prof_password.value = values[3];
Of course you may have to do something more complicated if the values may contain a comma.
You can try this
$account = $_GET['account'];
$query = "SELECT * FROM profs WHERE profs_name = '".$account."'";
$result = mysql_query($query, MYSQLI_STORE_RESULT);
while($arr = $result->fetch_array(MYSQLI_ASSOC)) {
$returnValues = json_encode($arr);
break;
}
echo $returnValues;
Note that column names are used as associative index for $arr
Hope it works.