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>";
Related
I try to send the data from the HTML form to php code by Ajax and it does not get the response
the html form get user_id from the user entry then send it by java script function that handle ajax code and send the user_id to php code to get user_id by $user_id = $_GET['user_id']; and search by the user_id then show what ever in php code in the other html code to show div content showdocument.getElementById("content").innerHTML=xmlhttp.responseText; response from php
function showUser(str) {
if (str == "") {
document.getElementById("content").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("content").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "http://localhost/gpms/admin_modify_user.php?user_id=" + str, true);
xmlhttp.send();
}
<head>
<script src="http://localhost/gpms/admin_user.js"></script>
</head>
<body>
<form method=post>
<label> Enter User ID: </label>
<input id="user_id" type=text name=user_id>
<br><br>
<input id="modify" type=submit value=Modify onclick="<script>showUser(user_id);</script>">
</form>
</body>
<?php
$user_id = $_GET['user_id'];
//create connection
$conn = mysqli_connect("localhost","root","","gpms");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM user WHERE user_id = '$user_id' ";
$result = mysqli_query($conn, $sql);
if (mysqli_query($conn, $sql)) {
$row = mysqli_fetch_assoc($result);
if ($row == 0) {
echo "No Results";
}
else {
$id = $row['user_id'];
$name = $row['user_name'];
$password = $row['user_password'];
$email = $row['user_email'];
$department = $row['user_department'];
echo "<div id = demo>";
echo "<table>";
echo "<tr>";
echo "<td> ID </td><td> Name </td><td> Password </td><td> E-mail </td><td> Department </td>";
echo "</tr>";
echo "<tr>";
echo '<td> '. $id .' </td><td> '. $name .' </td><td> '. $password .' </td><td> '. $email .' </td><td> '. $department .' </td>';
echo "</tr>";
echo "</table>";
echo "<button onclick = 'editUser(\"$id\",\"$name\",\"$password\",\"$email\",\"$department\")' > Edit </button>";
echo "<button onclick = 'deleteUser(".$id.")' > Delete </button>";
echo "</div>";
}
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
$conn->close();
?>
Your onclick attribute is wrong. It should just be the Javascript code, it shouldn't have <script>...</script> around it.
<input id="modify" type=submit value=Modify onclick="showUser(user_id);">
If you had looked in your Javascript console you would have seen it complain of a syntax error when you clicked.
And in the PHP, this line:
if (mysqli_query($conn, $sql)) {
should be:
if ($result) {
Otherwise you do the same query twice, which is unnecessary.
Im using this is an ID
$id = $row['id'];
echo "<input type='text' id='$id' value='$row["s_code"]'>";
How can I get that ID in javascript function? I want it in here...
var scode = $('#').val();
While loop..
while ($row = mysqli_fetch_array($sqlSimplex , MYSQLI_ASSOC)) {
echo "<tr><td>";
$id = $row['id'];
echo "<input type='text' id='$id' value='".$row['s_code']."' readonly>";
echo "</td><td>";
echo $row['description'];
echo "</td>";
echo "<input type='hidden' id='comval' value='$newProductID'>";
echo "<td>";
echo "<input type='text' size='7' id='userqtyval'>";
echo "</td><td>";
echo "<input type='button' onclick='addthis()' value='Add!'>";
echo "</td></tr>";
}
Javascript
function addthis() {
var myID = '$id';
var scode = $("#"+myID).val();
alert(scode);
$.ajax({
type: 'POST',
url: 'insertsimplextoc_comp.php',
data: { simplexcode: scode },
});
}
Been stuck on this for over a week!
PHP:
while ($row = mysqli_fetch_array($sqlSimplex , MYSQLI_ASSOC)) {
echo "<tr><td>";
$id = $row['id'];
echo "<input type='text' id='$id' value='".$row['s_code']."' readonly>";
echo "</td><td>";
echo $row['description'];
echo "</td>";
echo "<input type='hidden' id='comval' value='$newProductID'>";
echo "<td>";
echo "<input type='text' size='7' id='userqtyval'>";
echo "</td><td>";
echo "<input type='button' class='submit-scode' data-field-id='$id' value='Add!'>";
echo "</td></tr>";
}
Javascript (using jQuery click event):
$('.submit-scode').click(function(){
var field_id = $(this).attr('data-field-id');
var scode = $("#"+field_id).val();
$.ajax({
type: 'POST',
url: 'insertsimplextoc_comp.php',
data: { simplexcode: scode },
});
});
Untested, but it should work.
Add the id of the current loop as a parameter to the addthis function:
echo "<input type='button' onclick='addthis(\"$id\")' value='Add!'>";
Then grab the id when the function is called like so:
function addthis(myID)
{
var scode = $("#"+myID).val();
//etc
}
have to keep track of that dynamic id's
It you have that id then you can do something like this
var id="assign php varable";
var scode =$('#'+id).val();
I'm guessing you want it to be used in the addthis() function ?
In this case, you'll hve to give a similar class to all your readonly inputs.
Then, while clicking on the add button, you'll have to check for its parent <tr>
I made some example here : http://jsfiddle.net/captain_torche/frzadnbb/
Or, you could alteratively put the ID as a parameter of the addthis() function, like so :
echo "<input type='button' onclick='addthis(".$id.")' value='Add!'>";
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.
I have an issue with my login script where I have implemented ajax so the message will display on the same page if there was an invalid login but I have some issue when user puts the right information nothing happens, I have to refresh the page then its says welcome user but when user puts wrong information it displays invalid login message immediately.
index.php
<?php
if (!isset($_SESSION['uid'])) {
echo "<p>Welcome to our homepage. you can be part of our awesome community by signing up.</p>";
}else{
echo "<p>You are now logged in and able to post comments in our site</p>";
}
?>
<?php
if (!isset($_SESSION['uid'])) {
echo "<form action='login_parse.php' method='post' style='display: inline-block'>
Username: <input type='text' name='username' id='username' />
Password: <input type='password' name='password' id='password' />
<input id='submit-button' type = 'button' value='login' id='submit' />";
echo "</form>";
echo "<form action='signup.php' method='post' style='display: inline-block'>";
echo " ";
echo "<input type='submit' name='submit' value='Signup'>";
echo "</form>";
} else {
echo "<form style='display: inline-block'>";
echo "<p>You are logged in as ".$_SESSION['username']."";
echo "</form>";
echo "<form action='logout_parse.php' method='post' style='display: inline-block'>";
echo " ";
echo "<input type='submit' value='logout'>";
echo "</form>";
echo "<form action='profile.php' method='post' style='display: inline-block'>";
echo " ";
echo "<input type='submit' value='profile'>";
echo "</form>";
}
?>
<script src="ajax.js"></script>
<script>
var HTTP = loadXMLDoc();
var submitEvent = document.getElementById("submit-button").onclick = function(){
hello2(HTTP);
};
</script>
ajax.js
function hello2(){
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
var url = "login.php?username="+username+"&password="+password;
HTTP.onreadystatechange=function()
{
if (HTTP.readyState==4 && HTTP.status==200)
{
document.getElementById("ack1").innerHTML=HTTP.responseText;
}
};
HTTP.open("POST", url ,true);
HTTP.send();
}
login.php
<?php
session_start();
include_once("connect.php");
if (isset($_REQUEST['username'])) {
$username = mysql_real_escape_string( $_GET["username"]);
$password = mysql_real_escape_string( md5 ($_GET["password"]));
$sql = "SELECT * FROM users WHERE username='".$username."' AND password='".$password."' LIMIT 1";
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res) == 1) {
$row = mysql_fetch_assoc($res);
$_SESSION['uid'] = $row['id'];
$_SESSION['username'] = $row['username'];
header("location: index.php");
exit();
} else{
echo "INVALID login information.";
exit();
}
}
?>
to get around this issue I tried refreshing the page using header function in login.php but still nothings happens, I have to refresh the page manually n then it load welcome user. Am I doing something wrong.
You cannot use a header / server-side redirect when you call a file using ajax.
Instead you would have to check the results in the success function of your ajax call and use javascript to redirect if the login processed correctly.
here is some changes i made so its is properly working now
function hello2(){
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
var url = "login.php?username="+username+"&password="+password;
HTTP.onreadystatechange=function()
{
if (HTTP.readyState==4 && HTTP.status==200)
{
if (HTTP.responseText == 1){
window.location.replace("index.php");
}
else{
document.getElementById("ack1").innerHTML=HTTP.responseText;
}
}
}
HTTP.open("POST", url ,true);
HTTP.send();
}
You can put location.reload() to your HTTPhandler.
HTTP.onreadystatechange=function()
{
if (HTTP.readyState==4 && HTTP.status==200)
{
document.getElementById("ack1").innerHTML=HTTP.responseText;
}
else {
location.reload();
}
};
When a user enter correct credentials you does not return correct response for the ajax call.
if(mysql_num_rows($res) == 1) {
$row = mysql_fetch_assoc($res);
$_SESSION['uid'] = $row['id'];
$_SESSION['username'] = $row['username'];
echo "Logged in as ".$row['username'];
exit();
} else{
echo "INVALID login information.";
exit();
}
You can use JavaScript's window.location.replace('redirectURL') for redirecting to particular page.
I have a function on ajax that retrieves the int on the input button onclick, this is the javascript ajax code:
function checkBoxes(str){
var xmlhttp=browsers();
if(str=""){
document.getElementById("txt").innerHTML="";
return;
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("txt").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax.php?h"+str,true);
xmlhttp.send();
}
I use php to print the results on the screen, with an onclick button:
if(isset($_GET['k'])){
$con=oci_connect('jvillegas','1234','XE');
if(!$con){
die("No s'ha pogut connectar: ".mysqli_error($con));
}
$k=intval($_GET['k']);
$sql3=oci_parse($con, "SELECT TARIFAS.ID, TARIFAS.ID_TIPO_ACTIVIDAD, TARIFAS.TIPO, TIPO_ACTIVIDAD.TEMPS_KM, TARIFAS.PRECIO
FROM TARIFAS, TIPO_ACTIVIDAD
WHERE TARIFAS.ID_TIPO_ACTIVIDAD=TIPO_ACTIVIDAD.ID
AND TARIFAS.ID_TIPO_ACTIVIDAD=$k");
oci_execute($sql3);
echo "<div class='divPrecios'>";
echo "<table border='1'>";
echo "<tr class='tabPreciosTitles'>";
echo "<td>Tipus Tarifa</td>
<td>Temps/Km</td>
<td>Preu</td>
<td><input type='button' class='carrito' value=''></td>";
echo "</tr>";
while (($row=oci_fetch_array($sql3,OCI_BOTH))!=false){
echo "<tr>";
echo "<td>".$row['TIPO']."</td>";
echo "<td>".$row['TEMPS_KM']."</td>";
echo "<td>".$row['PRECIO']."</td>";
echo "<td>".$row['ID']."</td>";
echo "<td><input type='button' name='checkbox[]' onclick=checkBoxes('".$row['ID']."') value='".$row['ID']."'/></td>";
echo "</tr>";
}
echo "</table>";
echo "</div>";
}
I thougt there is the error:
input type='button' name='checkbox[]' onclick=checkBoxes('".$row['ID']."') value='".$row['ID']."';
I do tests and if I pass a single int valor, it returns 0... why??
So the table with the result if all it's correct:
if(isset($_GET['h'])){
$con=oci_connect('jvillegas','1234','XE');
if(!$con){
die("No s'ha pogut connectar: ".mysqli_error($con));
}
echo "<table border=1>";
echo "<tr class='tabPreciosTitles'>";
echo "<td>Nom Activitat</td>
<td>Nom Tipus Activitat</td>
<td>Tipus Tarifa</td>
<td>Temps/km</td>
<td>Preu</td>";
echo "</tr>";
$h=intval($_GET['h']);
$sql4=oci_parse($con, "SELECT ACTIVIDAD.NOM AS NOM_ACTIVIDAD, TIPO_ACTIVIDAD.NOM AS NOM_TACTIVIDAD, TARIFAS.TIPO, TIPO_ACTIVIDAD.TEMPS_KM, TARIFAS.PRECIO
FROM TARIFAS, ACTIVIDAD, TIPO_ACTIVIDAD
WHERE TARIFAS.ID=$h
AND TARIFAS.ID_TIPO_ACTIVIDAD = TIPO_ACTIVIDAD.ID
AND TIPO_ACTIVIDAD.ID_ACTIVIDAD = ACTIVIDAD.ID");
oci_execute($sql4);
$array=array(
0=>array(),
1=>array(),
2=>array(),
3=>array(),
4=>array()
);
while (($row=oci_fetch_array($sql4,OCI_BOTH))!=false){
array_push($array[0],$row['NOM_ACTIVIDAD']);
array_push($array[1],$row['NOM_TACTIVIDAD']);
array_push($array[2],$row['TIPO']);
array_push($array[3],$row['TEMPS_KM']);
array_push($array[4],$row['PRECIO']);
}
for ($x=0;$x<count($array[4]);$x++){
echo "<tr>";
echo " <td>".$array[0][$x]."</td>";
echo " <td>".$array[1][$x]."</td>";
echo " <td>".$array[2][$x]."</td>";
echo " <td>".$array[3][$x]."</td>";
echo " <td>".$array[4][$x]."</td>";
echo " <td><input type='submit' class='carritoElim' value=''></td>";
echo "</tr>";
}
echo "</table>";
}
And to show these results I use divs:
<div id='txtHint'></div>
<div id='txtIhnt'></div>
<div id='txt'></div>
If I put an int on the query of the last table, change the $h for a 13, it works, or if I change the ajax function on > xmlhttp.open("GET","ajax.php?h=13",true); it works too.
I think your problem is coming from this line here
if(str=""){
Rather that doing a comparison you are assigned an empty string to the str variable. So from that point on in the function the value of str will be "". You want to change it to
if(str==""){