Fetching td value in php file and sending back - javascript

I'm facing an issue to get the value of td when a link is clicked
search_code.php
echo "<table class='table table-hover'>";
echo "<tr><th>Institute ID</th><th>Institute Name</th><th>State</th><th>District</th><th>City</th><th>General Seats</th><th>Reserved Seats</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td id='instid'>".$row["collegeUniqueId"]."</td><td id='instname'><a href='#' onClick='getCourses(".$row["collegeUniqueId"].");'>".$row["name"]."</a></td><td>".$row["state"]."</td><td>".$row["district"]."</td><td>".$row["city"]."</td><td>".$row["openSeat"]."</td><td>".$row["reservedSeat"]."</td></tr>";
}
echo "</table>";
and in search.php
<script>
$(document).ready(function(){
$('#search').click(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'search_code.php?state=' + $('#state').val() + '&district=' + $('#district').val(),
success: function(institute){
$('#institute').html(institute);
}
});
});
function getCourses(id) {
$id = id;
$.ajax({
type: 'POST',
url: 'courses.php?courseid=' + id,
success: function(courses){
$('#courses').html(courses);
}
});
}
});
</script>

You haven't shown the HTML that gets produced, but if the "ID" value is anything other than a number, you need to put it in quotes:
echo "...onClick='getCourses(\"".$row["collegeUniqueId"]."\");'>...";
// --------------------------^^---------------------------^^
Side note: You'll also want to deal with those repeated id values the loop creates (assuming there's ever more than one row in the result set).
Side note 2: You're falling prey to The Horror of Implicit Globals in your getCourses function: You never declare the $id variable. You can just remove it, you're not using it for anything.

ID in HTML needs to be unique you can't have multiple elements with same ID.
There are at least 2 ways to fix it:
Use class attribute and use data-id attribute to get ID of particular row
In your PHP you can generate id with ROW id <td id='instid-".$row["collegeUniqueId"]."'>

Related

Pass array of data from form, to ajax, to PHP post file

I'll try and keep this short.
I have a form who's input fields (54 of them) are auto filled with data from a database. The ID of each input field is assigned with an ID using a PHP while loop. The user can edit the values and click submit. When the form is submitted, the data is passed to an array in jquery. I want to be able to pass that array from ajax to PHP via POST.
Form/submit page
$settings = array();
$counter = 0;
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)) {
$settings[$counter] = $row['value'];
echo "<tr>
<td>" . $row[$settings] . "</td>
<td><input type=\"text\" id=\"" . $counter . "\" value=\""
. $settings[$counter] . "\"></td>";
counter++;
}
}
mysqli_close($svr_link);
jQuery script (inside of the form/submit page)
$('#update').click(function(event) {
event.preventDefault();
var settings = [];
for (i=0; i<55; i++) {
settings[i] = $('#' + i).val();
}
$.ajax({
type: "POST",
url: "pages/post.php",
data: {settings:settings},
success: function(data) {
$('#message').html(data);
}
});
});
My question is:
Did I properly set up that data array in the ajax call?
How do I pull and deal with the data array in the post.php file?
Let me know if I omitted something relevant
If you're sending array data as JSON, it'd be recomendable to set dataType in your ajax set up at client.
$.ajax({
type: "POST",
url: "pages/post.php",
dataType: 'json',
data: {settings:settings},
success: function(data) {
$('#message').html(data);
}
});
At server side, use json_decode function to get an array, that way you can easily work with data. It'd be something like this:
json_decode($_POST['settings'], true);
Add name attribute to all the inputs in array form
while($row = mysqli_fetch_assoc($result)) {
$settings[$counter] = $row['value'];
echo "<tr>
<td>{$row[$settings]}</td>
<td>
<input
type=\"text\"
id=\"{$counter}\"
name=\"settings[{$counter}]\"
value=\"{$settings[$counter]}\"
>
</td>";
counter++;
}
Then add an id to the form (if you don't have a form tag, place the id on some HTML element that contains all the inputs, like probably the table), ad rely on jQuery serializeArray()
let data = $('#formId').find(':input').serializeArray();
So, your code become:
$('#update').click(function(event) {
event.preventDefault();
let data = $('#formId').find(':input').serializeArray();
$.ajax({
type: "POST",
url: "pages/post.php",
data: data,
success: function(data) {
$('#message').html(data);
}
});
});
jQuery.serializeArray()
Encode a set of form elements as an array of names and values.
from jQuery.serializeArray() documentation

how to delete a comment in javascript and ajax?

I am trying to write a simple delete function for a comment system that i am working on. the comments are stored in a database where each comment has a cid that is incremented automatically. i have noticed that the user can only delete the first comment he/she has written but when a the user writes two comments and presses delete on the second one, the comment can not be deleted, can someone help fix this. here is my code. thank you for your help.
this is my meatballs.php file where i have the comments loaded.
<div class = "page" id = "comments">
<p class = "style">Comments</p>
<button class="btn" id="load-comments">See Previous Comments</button><br>
<br>
<?php
if(isset($_SESSION['u_id'])){
echo " <input type = 'hidden' id = 'uid' value = '".$_SESSION['u_uid']."'>
<input type = 'hidden' id = 'date' value = '".date('Y-m-d H:i:s')."'>
<textarea id = 'message'></textarea><br>
<button class = 'btn' type = 'submit' id = 'meatballsSubmit'>Comment</button>";
}
else{
echo "<p>Please log in to comment</p>";}
?>
</div><br>
<script>
$(document).ready(function(){
$("#load-comments").click(function(){
document.getElementById('#comments').innerHTML=
$("#comments").load("getComments.php");
});
});
</script>
as for getCommetns.php file which retrieves the comments from the database.
<?php
include 'includes/dbh.inc.php';
session_start();
$sql = "SELECT * FROM meatballscomments";
$result = mysqli_query($conn, $sql);
while($row = $result->fetch_assoc()){
echo "<div class = 'comment-box'>";
echo '<span class = "user">'.$row['user_uid'].'</span><br><br>';
echo "<p>".htmlspecialchars($row['message'])."</p>";
echo '<span class = "datef">'.$row['date'].'</span>';
if(isset($_SESSION['u_id']) && $_SESSION['u_uid'] == $row['user_uid']){
echo "<br>";
echo "<input type = 'hidden' id = 'cid' value = '".$row['cid']."'>";
echo "<button class = 'btn' type = 'submit' id = 'meatballsDelete'>Delete</button>";
}
echo "</div><hr>";
}
?>
<script>
$(document).ready(function(){
$("#meatballsDelete").click(function(){
var cid = $("#cid").val();
$.ajax({
url: "deleteComment.php",
type: "POST",
async: false,
data: {
"cid": cid
}});
alert("Your comment has been deleted");
});
});
</script>
the deleteComment.php file that i have is very short and here it is.
<?php
include 'includes/dbh.inc.php';
$cid = $_POST['cid'];
$sql = "DELETE FROM meatballscomments WHERE cid = '$cid'";
$result = mysqli_query($conn, $sql);
You're assigning the same id on multiple html elements & using val() on the result of the jQuery selector which returns the first element with the id of cid. From jQuery:
Each id value must be used only once within a document. If more than
one element has been assigned the same ID, queries that use that ID
will only select the first matched element in the DOM.
Therefore there's no guarantee that it automatically grabs the right element for you, when you're using the same id multiple times.
The quickest fix would be to change #meatballsDelete to .meatballsDelete, and add the meatballsDelete class to your button, that way clicking will register on both buttons. Also add the $row['cid'] value as attribute to the button and then grab that with $(this).attr("myAttribute") in the function in click, which will always guarantee that the id is returned which belongs to the button.
Like #u_mulder says in the comments, you're also using an id to register the click, which will also bind to the first element with that id.
A reasonably easy way to modify your code to resolve this issue would be to get rid of the hidden cid input and add the cid value as a data value to your button. You also need to change the button to have a class meatballsDelete rather than an id, since id values must be unique. So change this:
echo "<input type = 'hidden' id = 'cid' value = '".$row['cid']."'>";
echo "<button class = 'btn' type = 'submit' id = 'meatballsDelete'>Delete</button>";
To
echo "<button class = 'btn meatballsDelete' type = 'submit' data-cid = '{$row['cid']}'>Delete</button>";
and then modify your javascript to add the click handler to items of class meatballsDelete (instead of id) and retrieve the cid value from the data-cid attribute:
$(document).ready(function(){
$(".meatballsDelete").click(function(){
var cid = $(this).data('cid');
$.ajax({
url: "deleteComment.php",
type: "POST",
async: false,
data: {
"cid": cid
}});
alert("Your comment has been deleted");
});
});
if(isset($_SESSION['u_id']) && $_SESSION['u_uid'] == $row['user_uid']){
echo "<br>";
echo "<p id='demo'></p>";
$commentId = $row['cid'];
echo "<input type = 'hidden' id = 'cid' value = '".$row['cid']."'>";
echo "<button class = 'btn' type = 'submit' onclick= 'deleteFunction($commentId, 1)'>Delete</button>";
}
and the script i used
<script>
function deleteFunction(cid, page){
//document.getElementById("demo").innerHTML = cid + " ----"+ page;
$.ajax({
url: "deleteComment.php",
type: "POST",
async: false,
data: {
"cid": cid,
"page": page}
});
alert("Your comment has been deleted!");
}
</script>

ajax request, query database, json_encode, return on success, show results

I'm working on a new piece of code and I'm new to ajax so I cant get it to work. I've got a textbox that has a javascript onKeyUp assigned to it. The first function is a delay function. It sets a delay timer, and as long as no other request is made via that delay timer, it runs a second function with the ajax after a certain time period. Inside the ajax, it runs a database query located in the second file based on the text that was entered in the textbox. It sets up an array of the results, json_encodes them, and returns them back to the original page. Then, I need to populate the page with the results (with php).
The Textbox
<input type="text" onKeyUp="delay_method('search_customer',search_customer(this.value),'2000')" />
The delay function
<script type="text/javascript">
function delay_method(label,callback,time){
if(typeof window.delayed_methods=="undefined"){window.delayed_methods={};}
delayed_methods[label]=Date.now();
var t=delayed_methods[label];
setTimeout(function(){ if(delayed_methods[label]!=t){return;}else{ callback();}}, time||500);
}
</script>
The ajax function
<script type="text/javascript">
function search_customer(value){
console.log(value);
$.ajax({
type: "POST",
url: "secondpage.php",
data: query,
dataType: 'json',
success: function(data){
console.log(data.name); // customer name
console.log(data.company); // customer company name
}
});
}
</script>
second page
set up an array for testing. Bypassing the query for now. Just need to get results back into main page. I can set up the array from the php once its working. My query will use LIKE %search text%
$arr = array(
'name'=>'overflow',
'company'=>'value'
);
echo json_encode($arr);
I have NO clue how to retrieve the data from the ajax function and populate the results. I would love to get the results back into a php array, and then loop through the array to echo out the results. I can loop through the array in php...my biggest concern is getting the results back into a php array.
Any assistance would be great. I cant seem to get the code to work. I am new to ajax so I'm learning this as I go.
UPDATE
Everything is working the way it should except the delay. Its not putting a delay on anything. I need it to wait for 2 seconds from each keyup before it activates the ajax function. If it receives another keyup, it waits an additional 2 seconds. IT continues until there is 2 seconds with no keyups. That way its not querying the database on every single keyup if the person is still typing. Right now its processing everything with each keyup.
textbox
<input type="text" onKeyUp="delay_method('search_customer',search_customer(this.value),'2000')" />
delay
function delay_method(label,callback,time){
if(typeof window.delayed_methods=="undefined"){window.delayed_methods={};}
delayed_methods[label]=Date.now();
var t=delayed_methods[label];
setTimeout(function(){ if(delayed_methods[label]!=t){return;}else{ callback();}}, time||500);
}
ajax function
function search_customer(value){
console.log(value);
$.ajax({
type: "POST",
url: "secondpage.php",
data: { "value": value },
dataType: 'html',
success: function(data){
$('#resultDiv').html(data);
}
});
}
second page:
$value = $_POST['value'];
if ((isset($value)) && ($value != "")) {
$arr = array();
$search_query = $db1q->query("SELECT first_name, company FROM Users WHERE first_name LIKE '%$value%' OR last_name LIKE '%$value%' OR company LIKE '%$value%'");
if ($search_query->num_rows > 0) {
while ($search_result = $search_query->fetch_assoc()) {
$arr[$search_result['first_name']] = $search_result['company'];
}
}
$html = '';
$html .= '<div>';
foreach ($arr as $key => $value) {
$html .= '<div class="sub-div"><h2>'.$key.'</h2> : ' . '<h4>' . $value . '</h4></div>';
}
$html .= '</div>';
echo $html;
}
You can't get the results back into a php array in js. So, what you have to do is to pass processed html in js and just print on page.
For example,
In second page
$arr = array(
'name'=>'overflow',
'company'=>'value'
);
using above array $arr make html over here and store it in variable. pass that variable into js.
For Ex :
$html = '';
$html .= '<div>';
foreach ($arr as $key => $value) {
$html .= '<div class="sub-div"><h2>'.$key.'</h2> : ' . '<h4>' . $value . '</h4></div>';
}
$html .= '</div>';
echo $html;
Now you will get html in your ajax success. just show on div like
$('resultDiv').html(data);
Your problem with my snippet of code (The delay function) is that on the keyup event when you are calling the delay function and passing the function/callback argument you are calling it and executing it immediately which is not the purpose of it. You should pass it as an anonymous function that calls your functions ( in a closure way). Also because you are using the html element to provide the values, you need to send them to the function scope / closure. Otherwise the closure will lost the parent context of (this) in this case the input.. so to solve it, you should use the bind javascript method, to preserve the "this" parent and its values. This is the key.
The correct input onkeyup event becomes this one:
<input type="text" onKeyUp="delay_method('search_customer',function(){search_customer(this.value);}.bind(this),'2000')" />
There are multiple commas after URL tag in ajax request remove it like following:
url: "secondpage.php",
Generally, the ajax request format should be the following using jQuery:
var index=0;
var menuId = $( "ul.nav" ).first().attr( "id" );
var request = $.ajax({
url: "script.php",
method: "POST",
data: { id : menuId },
dataType: "html"
});
request.done(function( msg ) {
index++;
//Append the result to the js array and then try storing the array value to PHP using HTML;
//Call your next event;
$( "#log" ).html( msg );
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
Now for your logic rather go with delayed call you should be using done or success event. Inside the success event, you should be calling next requirement. Because Ajax is asynchronous.

How to do an Ajax request to parse table row column data to PHP on click of table row?

I have a datatable with an numeric value in the first column of the <tr><td> row.
I want to click on that row and parse this value to a PHP page in order to assign this number into a session.
I have below code snippet, but this isn't do the push.
selected is the class of the row when I click on it.
$(".selected td").click(function(parsegroupid) {
var group_id = $(this).attr('data');
$.ajax({
url: "./includes/indexPage/assign_session.php",
type: "post",
data: {
id: group_id
},
success: function(response) {
}
});
});
This is my PHP code:
<?php
ob_start();
if (session_id() == '') {
session_start();
}
$GrpID = $_POST['group_id'];
$_SESSION['grp'] = $GrpID;
ob_end_flush();
?>
Below is a screenshot of the row when selected.
First, you need to check if the ajax call is made.
Based on your previous comments, it seems this is not happening.
You can try to specify the table id in your onclick event:
$("#table_id tbody").on( 'click', 'tr', function (){
var group_id = $(this).find("td:first-child").text();
$.ajax({
url: "./includes/indexPage/assign_session.php",
type: "post",
data: {
id: group_id
},
success: function(response) {
}
});
}
Make the change in your assign_session.php file your have pass the value in id and trying to access value of group_id.
Instead of $_POST['group_id'] use $_POST['id']
change the code like below
<?php
ob_start();
if (session_id() == '') {
session_start();
}
$GrpID = $_POST['id']; // change
$_SESSION['grp'] = $GrpID;
ob_end_flush();
?>
If the ID is in the cell of the and not as an attribute, try this:
var group_id = $(this).html();
Go with this code.
You are posting id and group_id is your value and you added $_POST['group_id'] instead of $_POST['id'].
Hope this will helps you :)
<?php
ob_start();
if (session_id() == '') {
session_start();
}
$GrpID = $_POST['id']; // Change here
$_SESSION['grp'] = $GrpID;
ob_end_flush();
?>

AJAX PHP function onchange select box

I have a problem about which I am very confused. I have a select box with s dynamically generated using a mysqli query:
$result = mysqli_query($db, "SELECT * FROM `users` WHERE `user_id` > 0");
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
while($row = $result->fetch_assoc()){
echo '<option value = '.$row['user_name'].'>'.$row['user_name'] . '</option>';
}
echo '</select></form>';
I am completely new to AJAX, but I need to use jquery and ajax to pass the this.value variable to a php variable for use in a later query.
Here is my script (most of which was found online):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
$("#contacts").change(function() {
//get the selected value
var selectedValue = this.value;
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});
</script>
Now, when I click a value in the select box, nothing happens. There are no warnings or errors, etc.
Please help me.
p.s. function.php does exist. It is just a simple echo for now (for testing purposes)
UPDATE: HERE IS FUNCION.PHP:
<?php
/*$val = $_REQUEST['selectedValue'];
echo $val;*/
function function(){
$val = $_REQUEST['selectedValue'];
echo $val;
}
?>
UPDATE: Thank you everyone for all your help. I have now got it to work in that the network section of chrome inspect shows the function.php being requested however I still don't get the echo (I used external .js files to get it to work). My J query function is also successful (the success function echoes into the console)
Your select box has no ID and you are watching the change event of $("#contacts").
Change:
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
to:
echo '<html><form name="contacts" method="post"><select name="contacts" id="contacts"><option value="Contact list">Contact List</option>';
^^^^^^^^^^^^^ here
You also only need one event handler, so I have removed the inline one which doesn't seem to do anything anyway.
Edit: If the select is created using ajax as well, you need event delegation:
$("body").on('change', '#contacts', function() {
^^^^ for example
Edit 2: Your variable is called $_REQUEST['option'] and not $_REQUEST['selectedValue']. You are also not calling your -badly named - function so you will not get any output from php except from an error like Parse error: syntax error, unexpected 'function' ....
Call onchange function in select tag as below
echo '<form name="contacts" method="post"><select name="contacts" onchange="func(this.value)"><option value="Contact list">Contact List</option></form>';
Javascript src should be in head of the html page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
Add the above one in head of html. Update javacript as below
As onchange function is called in the select tag itself, following is enough
<script>
function func(selectedValue)
{
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
}
</script>
Updated php: If you must want to get value from function, you must call it. Otherwise, simply, you can make as below
<?php
if($_REQUEST['option'])
{
$val=$_REQUEST['option'];
echo $val;
}
?>
In .php file, receive it first-
$val = $_REQUEST['selectedValue'];
echo $val;
set an id attribute in your php code for the select tag and
please don't use the same value for the name attribute in form and select tags !!
just change your function to a 'body'.on, and give your elements an id of 'contacts'
$("body").on('change', '#contacts', function() {
//get the selected value
var selectedValue = $(this).val();
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});

Categories