this is my first post.. my question probably is very simple but i cannot find the right way..!
I have a php page with a query selection from a database to show many records, for each record i've put form with some fields need to be updated and a "save" button
so for each record i have a column in the result table containing a form like:
$code = "<td><form method='POST' action='mypage.php' target='_blank' />";
$code .= " <input type='hidden' name='function' value='formtaglieok' />";
$code .= " <input type='hidden' name='email' value='".$email."' />";
$code .= " <input type='hidden' name='main' value='".$main."' />";
..... some other editing fields
$code .= "<input type='text' name='field1' value='' size='2' />"
..... some other editing fields
$code .= "<td><input type='submit' value='Save' /></td>"
after this column i've put label that i want to change after pressing the button and the updating of the record, like:
$code .= "<td><div id='<this_record_id>' ></div></td>";
in mypage.php i have the php code to update the record:
function updaterecord($_POST){
...connection to db, prepare the query etc..
$stid = OCIParse($conn, $query);
if (OCIExecute($stid)) {
$res .= "Saved ";
} else {
$res .= "Error";
}
echo $res;
}
obviously, with this kind of form action and the target "_blank", i see in a new page the result "Saved" or "Error" and the updating of the record in DB is ok
The thing i would is not put "Saved" in a new page, but update the div this_record_id beside the "save" button
so, i'll try to add the onClick event to the submit button
<input type='submit' value='Save' onclick='jSaved(<this_record_id>)' />
and put this code in the head of the page
<script type='text/javascript'>
function jSaved(bcode){
document.getElementById(bcode).innerHTML = 'Saved';
}
</script>
and it updating the label correctly but opening also another page.
what i would to do is executing my updating function inside the JS code using the $_POST array, so don't get a new page but only the result of the function in the label..
someone can help me?
edit: SOLVED
1) my php main page with a form like (IMPORTANT set the form_id):
$code = "<form name='frm_".$record['TD001_SEQ']."' id='frm_".$record['TD001_SEQ']."' action='' />";
$code .= " <input type='hidden' name='function' id='function' value='formtaglieok' />";
$code .= " <input type='hidden' name='email' id='email' value='".$email."' />";
$code .= " <input type='hidden' name='main' id='main' value='".$main."' />";
$code .= " <input type='hidden' name='store' id='store' value='".$store."' />";
$code .= " <input type='hidden' name='valuta' id='valuta' value='".$valuta."' />";
....other fields
//the code for the button (not submit)
$code .= "<td><input type='button' value='Save' onclick='jSaved(".$record['TD001_SEQ']."); '/></td>";
//the label DIV with the same reference of the form/record updating
$code .= "<td><div id='res_".$record['TD001_SEQ']."' ></div></td>";
2) the javascript code
function jSaved(td001){
//searching for exact form from the document page
var form = false;
var length = document.forms.length;
for(var i = 0; i < length; i++) {
if(document.forms[i].id == "frm_" + td001) {
form = document.forms[i];
}
}
//create a string containing all key/values from the form (parameters)
length = form.length;
var sParams = "";
for(var i = 0; i < length; i++) {
//will be key1=val1&key2=val2 ....
sParams = sParams + form.elements[i].id + "=" + form.elements[i].value + "&";
}
//execute the php update function with params in POST, td001 is needed to write le DIV label after update
var updResult = updateRecord("upd.php", sParams, td001);
}
//ajax code
function updateRecord(strUrl, params, idDiv) {
var xmlHttpReq = false;
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpReq.open('POST', strUrl, true);
xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttpReq.send(params);
xmlHttpReq.onreadystatechange = function() {
/*state evaluation
* 0 - UNINITIALIZED
* 1 - LOADING
* 2 - LOADED
* 3 - INTERACTIVE
* 4 - COMPLETE*/
//state complete
if (xmlHttpReq.readyState == 4) {
//updating the DIV label with upd.php result
document.getElementById('res_' + idDiv).innerHTML = xmlHttpReq.responseText;
}
}
return resUpd;
}
</script>
3) the upd.php page
if (isset($_POST)) {
funFormTaglieOK($_POST);
} else {
echo "Denied";
}
function funFormTaglieOK($params){
global $dbdw_usr, $dbdw_pwd, $dbdw_SID;
// Try to connect to Oracle
if ($conn = OCILogon($dbdw_usr, $dbdw_pwd, $dbdw_SID)) {
//execute record update
if (recordupdate is ok){
echo "Update"
} else {
echo "Error"
}
}
}
Ok so you should use ajax, and don't use target=_blank.
If you want a new window, you can still open that by Javascript.
In Your PHP code which is called by an ajax call, you should return the right results in a JSON format. You have to parse that string in JS, and do your DOM update accordingly.
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?
I'm sending an ajax request through JavaScript on clicking a button. When button gets clicked a function is called from where ajax request is performed.
Here is the html code where function is called:
echo "
<form > ";
if ($status == 'regular') {
echo "<input type='hidden' value='".$id."' name='id'>";
echo "<input type='hidden' value='official' name='status'>";
echo "<td><button class='btn btn-info' onclick='UpdateStatus(".$id.",'official')'>UPDATE TO OFFICIAL</button><br><br>";
}
if ($status == 'official') {
echo "<input type='hidden' value='".$id."' name='id'>";
echo "<input type='hidden' value='regular' name='status'>";
echo "<td><button class='btn btn-success' onclick='UpdateStatus(".$id.",'regular')'>UPDATE TO REGULAR</button><br><br>";
}
echo "</form>";
UpdateStatus() is the function in which there is ajax request. From here I'm sending $id which is user ID and the status which is to be updated.
Here is the UpdateStatus() function:
<script>
function UpdateStatus(str,str1) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
//ready
};
xmlhttp.open("GET", "update_status.php?id=" + str + "&status=" + str1, true);
xmlhttp.send();
}
}
</script>
The str and str1 are the Id and status respectively. Here is the update_status.php:
<?php
$id = $_REQUEST["id"];
$status = $_REQUEST["status"];
$server_name = "localhost";
$user_name = "root";
$password = "";
$db = "diwan";
$conect = new mysqli($server_name, $user_name, $password, $db);
if($conect->connect_error)
{ die("Connection failed ".$conect->connect_error); }
$sql = "UPDATE user SET status = '$status' WHERE UserID = $id";
if(!$conect->query($sql))
{echo "error in adding record ".$conect->error;}
$result = $conect->query($sql);
?>
And when I click on button I get url of this format:
http://localhost/diwan_web/manageusers.php?id=2&status=official
But it's not updating the data in database. Please guide me where I'm wrong or if anything is missing. Any suggestion will be highly appreciated.
Looks like your syntax is wrong. Try
$sql = "UPDATE user SET status = ".$status." WHERE UserID = ".$id";
Code looks good. There is probably an error you are not seeing.
Add this to top:
ini_set('error_reporting', E_ALL);
ini_set('display_errors', true);
There were some issues:
You need to ensure the button does not reload the page (with type='button' as mentioned in another post).
We should always use double-quote for HTML attributes to prevent such mistakes (use onclick=\"UpdateStatus('param-here')\" instead of onclick='...')
If you use PHP's double-quote features you do not need to concatenate manually (If PHP finds $ in double-quotes like echo "Variable is: $x" it tries to find and concatenate the $x variable automatically).
If you apply above mentioned changes your code should look like:
echo "<form >";
if ($status == 'regular') {
echo "<input type='hidden' value='$id' name='id'>";
echo "<input type='hidden' value='official' name='status'>";
echo "<td><button type='button' class='btn btn-info' onclick=\"UpdateStatus('$id','official')\">UPDATE TO OFFICIAL</button><br><br>";
}
if ($status == 'official') {
echo "<input type='hidden' value='$id' name='id'>";
echo "<input type='hidden' value='regular' name='status'>";
echo "<td><button type='button' class='btn btn-success' onclick=\"UpdateStatus('$id','regular')\">UPDATE TO REGULAR</button><br><br>";
}
echo "</form>";
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>
I am developing a survey form for recreational activities. The user is required to input a location which is then searched in a MYSQL database to ensure that the name entered matches the standard names for locations. The results are to be displayed in a select form to allow the user to choose the specific location.
The query appears to be working correctly. I have verified the return string via an alert window. However, the form appears for a brief second then disappears. I have tried writing the innerHTML string to both a tag and directly to the form. Other posts on this topic that I have found indicated that a form tag is not closed properly. This does not appear to be my problem.
When I run the php script from a test page using hard coded locations, and no other elements on the page, it works just fine.
My js script:
<script> function getLoc(){
var dataRequest;
try {
// Opera 8.0+, Firefox, Safari
dataRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
dataRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
dataRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser needs to be updated to run this
application!");
return false;
}
}
}
dataRequest.onreadystatechange = function() {
if(dataRequest.readyState == 4) {
if (dataRequest.status==200 ||
window.location.href.indexOf("http")==-1){
document.getElementById("locDropDown").innerHTML =
dataRequest.responseText;
}
else{
alert("An error has occured making the request");
}
}
}
var queryString = "";
queryString =
encodeURIComponent(document.getElementById('locStr').value.toUpperCase());
dataRequest.open("POST", "retrieveLoc.php", true);
dataRequest.setRequestHeader("Content-type", "application/x-www-form-
urlencoded");
dataRequest.send("searchValue=" + queryString);
}
</script>
<div>
<form id="floc">
<strong>Where Did You Go:</strong> <input type="text" id = "locStr"
placeholder="location">
<input type="submit" value="Search" onclick="getLoc()">
</form>
</div>
<!-- <div id="dataDiv"> -->
<form id="locDropDown">
</form>
<!-- </div> -->
The relevant portion of my php script:
<?php
$queryStr = htmlspecialchars($_POST['searchValue']);
$queryStr .= "%";
// Check sql
$locSql = "SELECT location FROM `location_lkup` \n"
. "WHERE location LIKE '" .$queryStr. "' \n"
. "ORDER BY `location_lkup`.`location` ASC";
$locRslt = $conn->query($locSql);
//Build Result String
/* $display_string = "<form id = 'locDropDown'>"; */
$display_string .= "<select name = 'locChoices'>";
// If returned records >0 insert a new row in the select form for each loc
returned
if ($locRslt -> num_rows > 0) {
$rowcounter = 1;
while($row = $locRslt -> fetch_array(MYSQLI_ASSOC)) {
$display_string .= "<option value = " . $rowcounter . ">" . $row['location']
. "</option>";
$rowcounter++;
}
}
else {
$display_string .= "<option value = '1'> NO DATA </option>" ;
}
$display_string .= "</select>";
$display_string .= "<input type = 'button' value= 'Select' onclick=
'getSelectedloc()'>";
/* $display_string .= "</form>"; */
echo $display_string;
?>
Any suggestions would be greatly appreciated. Thanks.
When I'm passing a form id to JavaScript function, the actual value what is passed there is not a string but [object HTMLFormElement].
Here is the code of a JavaScript:
function hideSowDiv(id) {
alert(id);
if (document.getElementById(id).style.display == "none") {
document.getElementById(id).style.display = "block";
} else {
document.getElementById(id).style.display = "none";
}
}
and it is a php part of the code:
while($ProductList = mysql_fetch_array($GetUers)){
echo "<div >";
echo "<input type='submit' name='OpenBtn' value='+' onclick='hideSowDiv(ItemUnit".$ProductList[0].")' > ";
echo "<span >".$UserList[4]." </span>";
echo "</div>";
//echo "<div id='".$UserList[0]."' style='display:none;>";
populateUserDivs($ProductList[0]);
//echo "</div>";
}
function populateUserDivs($Id){
$List_Query = "SELECT * FROM product WHERE product_id = ".$Id.";";
$GetList = mysql_query( $List_Query, $Connection ) or die("ERROR".mysql_error());
while($Output_List = mysql_fetch_array($GetList))
echo "<form id='ItemUnit".$UserId."' name='ItemUnit".$UserId."' method='POST' style='display:none;' >";
echo "<span class='AddingForm' > Name*: </span> <input type='textbox' name='UserName' class='Text_boxes' value='".$Output_List[1]."' required> ";;
echo "<input type='submit' name='EdtItem".$Output_List[0]."' id='DelItem".$Output_List[0]."' value='save' '>
echo " </form>";
}
}
So I wonder what am I doing wrong that the form id is not being passed to the JavaScript function, but the [object HTMLFormElement] instead.
The reason I'm passing the form id is if I put the form inside a div, the submit button is being treated just like an image and form is not working at all.
So if somebody can point me how can I turn the [object HTMLFormElement] into the form id I will be really grateful.