Updating the database on click of a table row - javascript

I am having a table in which data is being populated through the database.Now what i want is that as soon as i click on one of the row a alert message displays and the READSTATUS of that row become true in my database that is database gets updated .
Now my problem is where to write the code for updating the database as i dont want to move to a different page to do so.
Like my table is something like this :
<input type=hidden name="notifyidd" id="notifyidd" value="<%=messageid%>"/>
<tr bgcolor="#5D1B90" color="#FFFFFF" onmouseover="ChangeColor(this, true,false);" onmouseout="ChangeColor(this, false,false);" onclick="DoNav('shownotification.jsp?mid=<%=messageid%>');">
<td><input type="checkbox" name="" onclick="DoRemove(event);" width="20" class="select_all_mail" value=<%=messageid%>></td>
<td callspan="3" width="1000px"><%=messagesubject%> at <%=sendingtime%></td>
</tr>
and in onclick method of each row i had called the alert.But how to update the database now ?
function DoNav(theUrl)
{
var tt = document.myinbox.notifyidd.value;
alert(tt);
//document.location.href = theUrl;
}
As if i uncomment this line then it will move to next page.But i want to do it on same page only.Please help
EDIT :
I wrote a ajax code to do it.But it gives error.Please help
$(document).ready(function() {
$('#myrow').click(function ()
{
$.ajax({
type: "post",
url: "shownotification.jsp", //this is my servlet
data: {
notifyidd: $('#notifyidd').val()
},
success: function(msg){
if(msg == "success")
alert('Data updated.');
}
});
});
});
Here i assign myrow as id to my table row.Also i removed doNav function now
My error image clicked :
http://postimg.org/image/vix1vzvq5/
Though the error is resolved but this ajax call is not functioning.For test i make my shownotification.jsp as :
<body>
<% String notifyid = request.getParameter("notifyidd");%>
success
</body>

The error message says the server-side code is failing when looking for the attribute "groupid". The post you are sending has notifyidd instead. The server code has no way of knowing if this should map to groupid or not.
Try this. If it doesn't work, update us with the error.
$(document).ready(function() {
$('#myrow').click(function ()
{
$.ajax({
type: "post",
url: "shownotification.jsp", //this is my servlet
data: {
groupid: $('#notifyidd').val()
},
success: function(msg){
if(msg == "success")
alert('Data updated.');
}
});
});
});

Related

AJAX post method working in one area but not another

I have an AJAX post method that works in two places both on "Ladder" page, but not another, a "matches" page. This method sets posts the "player ID" which php picks up and sets a session variable
$("form .singles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Working page form:
<form><button type='submit' id='playerInfo' class='singles-player-name' name='viewPlayer' value='",$sglsPlayerID,"'>", $curSGLSRankLName, ", ", $curSGLSRankFName, "</button></form>
Sets session variable
if (!empty($_POST['viewPlayerID'])){
$viewPlayer = isset($_POST['viewPlayerID']) ? $_POST['viewPlayerID'] : 'No data found';
$viewPlayerSql = "SELECT * FROM `PLAYERS` WHERE `ID` LIKE '".$viewPlayer."'";
$viewPlayerQuery = #$conn->query($viewPlayerSql);
$viewPlayerRow=mysqli_fetch_assoc($viewPlayerQuery);
$_SESSION['playerID'] = $viewPlayerRow["ID"];
echo "", $_SESSION['playerID'],"";}
Second working version that lives on the same page as the first but is for doubles players:
$("form .doubles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Form for that ajax method:
<form><button type='submit' id='playerInfo' class='doubles-player-name' name='viewPlayer' value='",$dblsPlayerID,"'>", $curDBLSRankLName, ", ", $curDBLSRankFName, "</button></form>
Then on complete, the ajax methods redirect to the player page and pulls up that players info on that page (ex. https://urlexample.com/Player). This part, from this point-up, works! However, I have another page, the "Matches" page, where I want it to do the same exact thing, and set that session variable, then redirect to the player page, so I have this method below. But for some reason, this one does not work:
$("form .singlesMatch-player1-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
console.log(data);
window.location.href = "Player";
});
});
Not working form:
<form><button type='submit' id='playerInfo' class='singlesMatch-player1-name' name='viewPlayer' value='",$sglsPlayer1ID,"'>", $P1LN, ", ", $P1FN, "</button></form>
For some reason, all this second method does is post it to the URL (ex. https://urlexample.com/WeeklyMatchUps?viewPlayer=1) instead of setting the session variable and redirecting to the player page (ex. https://urlexample.com/Player). All thats different between the 2 is the class name of the button.
$sglsPlayer1ID should probably be $sglsPlayerID.
Also, try adding a success and error condition to your AJAX conditions instead of just using a done operator. This will allow you to dump helpful error codes on a failure to better resolve these kinds of issues in the future.
I had a function being called on the page that was commented out causing an error before jQuery was added in a script at the bottom of the page. removing that function from being called fixed the issue.
S/O to #line88 for the assistance!

Not able to POST Variable to Another Page (PHP, Javascript, AJAX)

I have a while loop (inside the "searchvessel.php") that display the content of a query and have a button "upgrade" for each record of that query.
`while($fetch = $read->fetch_array()) {
?>
<tr>
<td id="1" style="display:none;"><?php echo $fetch['VesselID']?></td>
<td id="2"><?php echo $fetch['VesselName']?></td>
<td><input type="submit" class="button" name=<?php echo $fetch['VesselID']; ?> value="Upgrade"/></td>
</tr>`
This "Upgrade" button when click will call to a Javascript code that use the value inside the tag name to pass to another page using AJAX.
<script type = "text/javascript">
$('.button').click(function(){
alert($(this).attr('name'));
$.ajax({
type: "POST",
data: {
name: $(this).attr('name')
},
url: "vesselrecord.php",
dataType: "json",
async: true,
beforeSend: function(){
$(".ajaxTest").text("Trying to upgrade...");
},
complete: function(){
window.location.href = "vesselrecord.php";
},
success: function(data) {
$(".ajaxTest").text(data.a);
if (data.b == "true") {
location.reload();
}
}
});
});
</script>
I were able to prompt/alert the value of vessel identification using the "alert($(this).attr('name'));" then
Move/Transfer to the "vesselrecord.php
But inside the "vesselrecord.php" there is no value in the $_POST['name']. Looks like there is an issue on my ajax code. Can you guide me on this? TIA.
Below is my code inside the "vesselrecord.php"
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$vessel_id = strip_tags($_POST['name']);
}
When you change the location of the window, you make a $get request not $post, that is why you are not getting any value $_POST['name'].
You can change the location from-
window.location.href = "vesselrecord.php"
to-
window.location.href = "vesselrecord.php?myquerystringdata=" + $(this).attr("name");
and then on you php file you can write code to get value from query string.
'name' is nested within 'data'. Maybe you need to access data.name? I'm more used to JS than PHP so I'm not sure how to express this. Hope this helps.
data:{
name:'Al'
}

Passing JSON through AJAX Plus Button Dilema

so I am attempting to pass some information in a JSON object and have a php page insert the data into a database. However, I am running into some trouble. The "update" button exists in a popup window. The user then clicks "update" and the inputted data should be processed accordingly. However, I fear that I am not even reaching my .click function. None of my alerts seems to be triggered. Below I will point out where issues are occurring. Thank you!
<script>
function updateTable()
{
document.getElementById("testLand").innerHTML = "Post Json";
//echo new table values for ID = x
}
$('#update').click( function() {
alert("help!");
var popupObj = {};
popupObj["Verified_By"] = $('#popupVBy').val();
popupObj["Date_Verified"] = $('#popupDV').val();
popupObj["Comments"] = $('#popupC').val();
popupObj["Notes"] = $('#popupN').val();
var popupString = JSON.stringify(popupObj);
alert(popupString);
#.ajax({
type: "POST",
dataType: "json",
url: "popupAjax.php",
//data: 'popUpString = '+ popupString,
data: popupObj,
cache: false,
success: function(data) {
updateTable();
alert("testing tests");
}
});
});
</script>
<html>
<button onClick="openPopup(<?php echo $row['ID'];?>);"><?php echo $row['ID'];?></button> <!--opens a popup with input options-->
<button id="update">Update</button> <!-- this button is supposed to cause the javascript above to run when clicked, however none of my alerts seem to be reached.-->
</html>
Thank you for looking!
1)I can only guess that you're trying to use JQUERY?
Where do you include the library?
2 )#.ajax isnt valid Jquery function
try $.ajax instead

retrieve data from database without refreshing the page

When the user press entre the data will be save into database.
Ajax
$('td.edit').keydown(function(event){
arr = $(this).attr('class').split( " " );
var clientid=document.getElementById("client").value;
account_id=document.getElementById("account_id").value;
if(event.which == 13)
{
$.ajax({ type: "POST",
url:"clientnetworkpricelist/update.php",
data: "value="+$('.ajax input').val()+"&rowid="+arr[2]+"&field="+arr[1]+"&clientid="+clientid+"&account_id="+account_id,
success: function(data){
$('#CPH_GridView1_Status').append(data);
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
}});
}
}
Html
<td id="CPH_GridView1_Status'.$rows['net_id'].'" class="edit2 status '.$rows["net_id"].' "><img src="image/'.$rows["status"].'f.png" /></td>
After success I want to retrieve data from database and place it in the proper td ( in the same row of the clicked td) i am success to retrieve data but not retrieve in the correct td
which row you want to load data?
change it:
$('#CPH_GridView1_Status').append(data);
to
$('#CPH_GridView1_Status'+arr[2]).append(data);
Before appending data first clear current '' using
$('#CPH_GridView1_Status'+arr[2]).empty();
and then append data
$('#CPH_GridView1_Status'+arr[2]).append(data);

how to pass php value from one file to another through java script

I am working with Concrete-5 CMS, I have an issue in passing value form view to controller.In my application I am using following code for displaying employee role.
foreach($rd as $data){
echo "<tr><td>".$data[role_name]."</td><td>".$data[role_description]."</td><td>Edit</td><td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td></tr>";
}
<input type="hidden" name="rno" id="rno" />
script:
$delConfirmJS = t('Are you sure you want to remove this Role?'); ?>
<script type="text/javascript">
function deleteRole(myvar) {
var role = document.getElementById('rno');
role.value = myvar;
if (confirm('<?php echo $delConfirmJS ?>')) {
$('#rolelist').submit();
//location.href = "<?php echo $this->url('/role/add_role/', 'delete', 'myvar')?>";
}
}
</script>
html code
I did edit operation by passing role_id through edit action. But, In case of delete i should ask for a conformation, so I use java script to conform it and call the href location and all.
But i don't know how to pass the role_id to script and pass to my controller. how to achieve this task?
thanks
Kumar
You can pass value to server using ajax calls.
See the following code. Here We use a confirm box to get user confirmation.
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm)
{
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}
In delete.php you can take the employee id by using $_POST['emp_id']
You can do it easily by using jquery
var dataString = 'any_variable='+ <?=$phpvariable?>;
$.ajax({
type: "POST",
url: "otherfile.php",
data: dataString,
success: function(msg){
// msg is return value of your otherfile.php
}
}); //END $.ajax
I would add an extra variable in to the delete link address. Preferrably the ID of the row that you need to be deleted.
I don't know Concrete-5 CMS. But, i am giving you the general idea
I think, you are using some button on which users can click if they want to delete role.
<td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td>
My suggestion,
add onClick to button
onClick="deleteEmployee(roleId);" // roleId - dynamic id of the role by looping over
Frankly speaking dude, i dont know how you will add this to your button that i guess there would surely be some way to simply add this to existing html.
And now, simply use Sajith's function
// Sajith's function here
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm){
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}

Categories