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?
Related
Ive searched high and low for information online for this question and have found absolutely nothing.
I have an admin.php file which gets a list of "unchecked" booking references;
$query = "SELECT * FROM $table WHERE servStatus = 'unchecked'";
And for each unchecked iteam thats returned i create a table with the status linked to the corresponding button;
echo "<tr>";
echo "<td colspan=2 style='text-align:center;'>";
echo "<input name=\"sbutton\" type=\"button\" onClick=\"confirm('confirm.php','content', $fetched_serv_ref)\" value=\"Confirm $fetched_serv_ref\" />";
echo "</td>";
echo "</tr>";
On click, i need this to update a status within the DB to 'checked' which is part of the confirm.php file;
$query = "UPDATE $table SET `servStatus` = 'checked' WHERE `assign2`.`servRef` = '$sbutton'";
and the corospong JS/HXR function is as the below;
var hr = createRequest();
function confirm(dataSource, divID, sbutton) {
if (hr) {
var obj = document.getElementById(divID);
var requestbody = "sbutton=" + encodeURIComponent(sbutton);
hr.open("POST", dataSource, true);
hr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
obj.innerHTML = hr.responseText;
} // end if
}; // end anonymous call-back function
hr.send(requestbody);
}
}
However, on click, the console is logging "Uncaught SyntaxError: Invalid or unexpected token - admin.html:1
ANY help or guidance would be appreciated!
Thanks.
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.
I'm trying to delete data from database but when I click on delete button then its delete the first row not where I'm clicking.
my PHP Code:
<?php
$connect = mysqli_connect("localhost","root","","abu");
if($connect){
$showdata = mysqli_query($connect,"SELECT * FROM dealers");
if(mysqli_num_rows($showdata)>0){
$i = 1;
while($rows = mysqli_fetch_assoc($showdata)){
echo "<tr>";
echo "<td>".$i."</td>";
echo "<td>".$rows["dealer_name"]."</td>";
echo "<td><button onclick='deleteproduct()' class='delete'>Delete</button><input type='hidden' id='productid' vlaue='".$rows["id"]."'></td>";
echo "</tr>";
$i++;
}
}else {
echo "<center><i>No Dealers to show</i></center>";
}
}
?>
And this is my ajax code:
function deleteproduct(){
if(window.XMLHttpRequest){
http = new XMLHttpRequest();
}else {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
http.onreadystatechange = function(){
if(http.readyState == 4 && http.status == 200){
document.getElementById("alerts").innerHTML = http.responseText;
}
}
var delid = document.getElementById("productid").value;
var file = "assets/php/addproduct_deletedata.php";
var senddata = "productid="+delid;
http.open("POST",file,true);
http.setRequestHeader("content-type","application/x-www-form-urlencoded");
http.send(senddata);
}
I want that when I click on delete button then it delete the row where I clicked not others.
FIRST OF ALL YOU CANNOT ASSIGN THE SAME ID TO MORE THAN ONE ELEMENTS ON A PAGE.
The browser won't mind it but It makes the HTML invalid. You can use class attribute for this purpose.
You can validate your HTML online here
echo "<td><button onclick='deleteproduct()' class='delete'>Delete</button><input type='hidden' id='productid' vlaue='".$rows["id"]."'></td>";
For your requirement, you can use anchor tag instead of using a form with a hidden input field to reduce the DOM size and call the function on click and pass the function the productId as a parameter.
Here's the code:
<?php
$connect = mysqli_connect("localhost","root","","abu");
if($connect){
$showdata = mysqli_query($connect,"SELECT * FROM dealers");
if(mysqli_num_rows($showdata)>0){
$i = 1;
while($rows = mysqli_fetch_assoc($showdata)){
echo "<tr id='row-".$rows["id"]."'>";
echo "<td>".$i."</td>";
echo "<td>".$rows["dealer_name"]."</td>";
echo "<td><a href='#' onclick='return deleteproduct(".$rows["id"].")'>Delete</a></td>";
echo "</tr>";
$i++;
}
}else {
echo "<center><i>No Dealers to show</i></center>";
}
}
?>
JavaScript:
function deleteproduct( delId ){
var tableRowId = 'row-'+delId;
// you got delId and tableRowId to remove the table row
// do ajax stuff here...
return false;
}
Let me know how it went.
because its "value" and not "vlaue" ;)
input type='hidden' id='productid' vlaue='".$rows["id"]."'
2.
you're iterating over your resultset and printing out an input-field with the id "productid".
In your code, EVERY column has the SAME id. Thats the reason your javascript isn't working as expected. An ID needs to be unique.
You need to send the value (product id) as the function parameters. Do it like this:
<input type="hidden" onclick="deleteproduct(this.value)" value="$yourRowId"/>
or
<input type="hidden" onclick="deleteproduct($yourRowId)" />
and this is how you can retrieve the value in JS:
<script type="text/javascript">
function deleteproduct(id)
{
alert(id); // your product ID
}
</script>
Iam trying to make a live ajax search . When you put a word it automatically shows suggestions bellow just like w3schools. But for some reason my index file and my php doesnt exchange data value or my database doesnt connect for some reason.What i always get is "no country found". Can you check the code for errors?
this is the php file :
<?php
include_once('dbconnect.php');
$q = intval($_GET['q']);
$query = mysqli_query($conn,"SELECT * FROM `users` WHERE userCountry LIKE '%".$q."%'");
$count = mysqli_num_rows($query);
//Replace table_name with your table name and `thing_to_search` with the column you want to search
if($count == "0" || $q == ""){
$s[] = "No Country found!";
}else{
while($row = mysqli_fetch_array($query)){
$s[] = $row['userCountry']; // Replace column_to_display with the column you want the results from
}
}
for($x = 0; $x < $count; $x++) {
echo $s[$x];
echo "<br>";
}
?>
and this is my index.php file :
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
function showCountry(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","indexsearchquery.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<input id="search-box" name="q" type="text" autocomplete="off" placeholder="Search country..." onchange="showCountry(this.value)" />
<input type='image' name='search' id="search-icon" value='Submit' src="search-icon.png" >
<p style="color:white;">Suggestions: <span id="txtHint" ></span></p>
Your country name will not in integer. but you convert it into intval change your php file to
include_once('dbconnect.php');
$q = $_GET['q']; //<-----remove intval
$query = mysqli_query($conn,"SELECT * FROM `users` WHERE userCountry LIKE '%".$q."%'");
$count = mysqli_num_rows($query);
//Replace table_name with your table name and `thing_to_search` with the column you want to search
if($count == "0" || $q == ""){
$s[] = "No Country found!";
}else{
while($row = mysqli_fetch_array($query)){
$s[] = $row['userCountry']; // Replace column_to_display with the column you want the results from
}
}
for($x = 0; $x < $count; $x++) {
echo $s[$x];
echo "<br>";
}
it is important to know the content of the dbconnect.php file because it the one that contains database connection variables.
Check if your MySQL Server is up and that all variable are well set.
I need to insert a value got from a document.getElementById into a sql query.
I need to do this because i'm trying to autofill a second input box depending on the result of the first (i.e. if i type Rome in the first one i would like the second one to autofill with the related country found in my db, like Italy)
Here is the code:
<?php
echo (" <form NAME='Form1' id='Form1' method=post class=statsform action=page.php > " );
echo (" <input type=text name=city id=city size=50 class=formfield value='$city' onBlur='Assigncode();' > " );
echo (" <input type=text name='Country' id='Country' size=12 value='$Country' > " );
?>
<script>
function Assigncode() {
var elemento = document.getElementById("city");
var elementoCod = document.getElementById("Country");
if (elemento != null && elemento.value != '') {
var city = elemento.value;
if (elementoCod == null || elementoCod.value == '') {
<?php
$query2 = "SELECT * FROM table WHERE city = 'put here the getElementById of the city' ";
$result2 = MYSQL_QUERY($query2);
$i2 = 0;
$country = mysql_result($result2,0,"T_Country");
?>
eval( "document.Form1. Country").value = '<?php echo($country)?>';
}
}
}
</script>
Any suggestion?
Thanks
Here is a slightly modified version of an AJAX example script found on Wikipedia. It should give you the basic idea on how to proceed. If you use jQuery then a lot of this JavaScript could be reduced to just a few lines.
// This is the client-side javascript script. You will need a second PHP script
// which just returns the value you want.
// Initialize the Http request.
var xhr = new XMLHttpRequest();
xhr.open('get', 'send-ajax-data.php?city=' + elemento.value);
// Track the state changes of the request.
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
document.Form1.Country.value = xhr.responseText; // 'This is the returned text.'
} else {
alert('Error: ' + xhr.status); // An error occurred during the request.
}
}
};
// Send the request to send-ajax-data.php
xhr.send(null);
send-ajax-data.php:
<?php
$city = $_GET['city'];
$query2 = "SELECT * FROM table WHERE city = '$city'";
$result2 = MYSQL_QUERY($query2);
$country = mysql_result($result2,0,"T_Country");
echo $country;
By the way, the $city variable should be validated and escaped prior to using it in an SQL query.