Calling onClick() within an echo'd php file - javascript

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.

Related

Why won't my innerHTML change upon PHP echo?

I have a program that gets an input from an HTML input field
<form method>
<input name="filmslike" id="input">
</form>
Then it goes through a javascript file that gets an ajax response from a PHP file
let div2Change = document.getElementById("div2Change");
let input = document.getElementById("input");
input.addEventListener("change", getTable);
function getTable(){
let ajax = new XMLHttpRequest();
ajax.open("GET", "filmslike.php");
ajax.send();
ajax.onreadystatechange = function(){
if (ajax.readyState == 4 && ajax.status == 200){
alert("in if");
array = JSON.parse(ajax.responseText);
str = "<table class='table'>";
for (i = 0; i < array.length; i++){
str += "<tr><td>" + array[i] + "</td></tr>";
}
str += "<table>";
div2Change.innerHTML = str;
}
}
}
the PHP file gives back an array from a database
require "DatabaseAdaptor.php"; // This includes class DatabaseAdaptor as if it where above this code.
$theDBA = new DatabaseAdaptor(); // constructor a DatabaseAdaptor object.
$moviesLike = $_GET['filmslike'];
$array = $theDBA->getAllMoviesLike($moviesLike);
echo json_encode($array);
and the database function returns items that are similar to $part
public function getAllMoviesLike($part) {
$stmt = $this->DB->prepare("SELECT * FROM movies WHERE name like '%" . $part . "%'");
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
I don't understand why I'm not getting any change to my innerHTML. The alert says that it goes into the if statement (though it only activates inconsistently). I tried to use POST instead of GET, and it didn't work. What is wrong?
You don't send anything to the server for searching from AJAX. You need to add input value to the request:
ajax.open("GET", "filmslike.php?filmslike="+document.getElementById("input").value);
ajax.send();

Choosing a district by city problem with php

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?

Not able to read/pass JS value to server in PHP

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.

how to delete data from database in php,ajax,javascript(no jquery)

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>

Use a document.getElementById into a query or another way to do this

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.

Categories