How do I to pass html cell id to php variable - javascript

I'm trying to create a sign up page for people to select open time slots for an event booth. I've hijacked code from "phpmyreservation" but I need specific dates. So I've created two arrays. One for "Day" and One for "Time". The combination of these two values are the id of the each table cell and are values stored in the MySQL table with the person/group that has chosen to man the booth on that date and time.
Assuming I need code to replace "void(0)" and a script that would put the $Aday and $Atime into one or two php variables.
How do I pass the HTML TABLE CELL ID to PHP variables?
<?php
echo '<table><tr><td></td> ';
foreach($global_days as $Aday) {
echo '<th>'.$Aday.'</th>';
}
echo '</tr>';
foreach($global_times as $Atime) {
echo '<tr><th class="reservation_time_th">' . $Atime . '</th>';
foreach($global_days as $Aday) {
echo '<td><div id="div:' . $Aday . ':' . $Atime . '" onclick="void(0)">' . read_reservation($Aday, $Atime) . '</div></div></td>';
}
echo '</tr>';
}
echo '</table>';
?>
This may be useful:
https://github.com/olejon/phpmyreservation
I think I've made progress, but I'm still stumped
I changed:
onclick="void(0)"
to
onclick="process(\'' . $Aday . '\',\'' . $Atime . '\')"
and
created the js file:
function process() {
var theDay = Aday;
var theTime = Atime;
var request = $.ajax({
type: 'post',
url: 'reservation.php',
dataType: "html",
data: { Aday: theDay, Atime: theTime }
});
request.done(function(msg) {
alert ( "Response: " + msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
and added to php file:
if(isset($_GET['theDay']))
{
$day = $_POST[$theDay];
$time = $_POST[$theTime];
}
The page appears to work to some extent but not... $day & $time are null

According to your if statement, a blank response is expected.
You need to check $_POST instead of $_GET since you are making a POST request and of course output something.
if(isset($_POST['theDay']))
{
$day = $_POST[$theDay];
$time = $_POST[$theTime];
echo $day . " " . $time;
}
Also, you have to make process() accept parameters. So your code would look like:
function process(Aday, Atime) {
var theDay = Aday;
var theTime = Atime;
var request = $.ajax({
type: 'post',
url: 'reservation.php',
dataType: "html",
data: { Aday: theDay, Atime: theTime }
});
request.done(function(msg) {
alert ( "Response: " + msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
And your onclick attribute would look like onclick="process($Aday, $Atime)".

Related

AJAX won't call the PHP file when using $.post()

I have been trying to export a search result to an Excel file (type .xls), before this, I have been using purely PHP and it works.
However, my client requests to have "live search" effect, so I have to shift to AJAX.
Here is the starting point: User clicks "Export" button, and in the javascript (in the main php file viewdata.php):
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
....
$(document).ready(function () {
var guid = <?php echo $guid ?>;
var date = document.getElementById("cbXDate").value;
var key = document.getElementById("cbsearch").value;
console.log("GUID: '" + guid + "', Date: '" + date + "' Key: '" + key + "'");
$.post("export_contacts.php",
{ sGuid: guid, sDate: date, sKey: key },
function () { console.log("Complete"); } );
});
cbXDate is an input field of type date to let user choose a date from whence to export the data, and cbsearch is a text input field to include a search keyword. console commands are added to see where the code execution has went through.
in the export_contact.php:
<?php
echo '<script> console.log("Export PHP activated."); </script>';
?>
I removed the PHP MySQL data selection code just to debug the problem (full source code below).
Problem is: export_contacts.php is never called. The "Export PHP activated" message never popped up in the console. The console only displayed the data values and "Completed", i.e. export_contacts.php was never called.
Output:
GUID: '0001', Date: '2021-08-01' Key: 'Jo'
Complete
Out of curiosity, I replaced $.post(...) with $("#export_div").load(...) and the console message showed up:
$(document).ready(function () {
var guid = <?php echo $guid ?>;
var date = document.getElementById("cbXDate").value;
var key = document.getElementById("cbsearch").value;
console.log("GUID: '" + guid + "', Date: '" + date + "' Key: '" + key + "'");
$("#export_div").load("export_contacts.php",
{ sGuid: guid, sDate: date, sKey: key },
function () { console.log("Complete"); } );
});
Output:
GUID: '0001', Date: '2021-08-01' Key: 'Jo'
Export PHP activated.
Complete
But this is not what I want, I want to write the output to a file, not display them in a div in the webpage. However, the data shown in the "export_div" div is correct, but the header part is not running, I know the quirkyness in header() calls, but I didn't output anything before the header() calls (unless output from the calling viewdata.php file also count?), here is the full export_contacts.php source code:
<?php
include("./php/auth.php");
$guid = $_POST['sGuid'];
$date = $_POST['sDate'];
$skey = $_POST['sKey'];
$searchKey = $_POST['sKey'];
if($searchKey == "")
{
$skey = "'%'";
}
else
{
$skey = "'%".$searchKey."%'";
}
$sql = "SELECT *, FROM_UNIXTIME(ROUND((date / 1000), 0) + 46800) AS date
FROM contacts
WHERE owner = '$guid' AND contact <> ''
AND (contact LIKE $skey OR name LIKE $skey) ";
if(!empty($date))
{
"AND date >= '$date' ";
}
$sql .= "ORDER BY contact;";
if($result = mysqli_query($link, $sql))
{
$columnHeader = '';
$columnHeader = "Owner" . "\t" . "Contact" . "\t" . "Name" . "\t" . "SaveDate" . "\t";
$setData = '';
while($rows = mysqli_fetch_assoc($result))
{
$rowData = '';
foreach ($rows as $value)
{
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
}
// in case of .load() used,
// code works up until this point
// code doesn't work since here...
header("Content-type: application/xls");
header("Content-Disposition: attachment; filename=contact_".$guid.".xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader) . "\n" . $setData . "\n";
// until here
// this will show in console in case of .load() used
echo '<script> console.log("Export PHP activated."); </script>';
die();
}
else
{
echo "<script>window.alert('ERROR: '".mysqli_error($link).")</script>";
}
include("./php/cleanup.php");
?>
This code is working in the pure PHP version. I don't know why this header() part isn't working in here, could be due to its output got redirected to the div?
To make things clear, my question is: "Why $.post(...) isn't calling the PHP file, while $("#export_div").load(...) did?".
The header() part is just a sub question, and is fine if it's ignored.
As Kmoser pointed out, I was doing things wrong. None of the tutorial sites I visited did mention that $.post() will not return any result at all, while my php code is expecting the return of the search result and write them in a file in the header() calls.

How to change database values with dynamically created buttons in PHP

I am dynamically creating html content with PHP and I am creating a button and when that button is clicked It should invoke a PHP script that will update the values of a column of a specific row in the database
Here is my code:
<?php
session_start();
if(!isset($_SESSION['id'])){
header("Location: login.php");
}else{
require_once("mysqli_connect.php");
$query = "SELECT * FROM markeri WHERE odobreno ='F'";
$response = #mysqli_query($dbc,$query);
if($response){
echo "<hr>";
while($row = mysqli_fetch_assoc($response)){
echo "<div align='center' id='markeri'><h3>Naziv: " . $row['naziv'] . "</h3>";
echo "<h3>Ulica: " . $row['ulica'] . "</h3>";
echo "<h3>Opis:</h3>" . "<p>" . $row['opis'] . "</p>";
echo "<h4>Email: " . $row['email'] . "</h4>";
echo "<img src='" . $row['link_slike'] . "' width='300px' /></br>";
echo "<form action='update.php' method='POST'>";
echo "<textarea rows='10' cols='30' maxlength='500' placeholder='Komentar' name='" . $row['marker_id'] . "'></textarea></br>";
echo "<input type='button' value='Odobri' name='" . $row['marker_id'] . "b" . "' /></form><hr>";
}
}
}
?>
I tried something like making the name of the textarea equal to the marker_id in my database and making the name of the button the value of marker_id + the string "b" but I don't know how to call them on my update.php script. Usually when it is a normal case and when there is no dynamic content I know how to do it with $_POST['name'];
EDIT:
I used AJAX to dynamically create the HTML as you told me but I've encountered another problem
<script>
function page_loaded(){
jQuery.ajax({
method: "GET",
url: "get_data_dashboard.php",
success: function(data){
var markers = JSON.parse(data);
for(var i = 0; i < markers.length; i++){
var m = markers[i];
var markerHTML = "<div class='marker'>" +
"<span id='naziv'>Naziv zahtjeva: " + m.naziv + "</span></br>" +
"<span id='ulica'>Ulica: " + m.ulica + "</span></br>" +
"<p id='opis'>Opis:</br>" + m.opis + "</p></br>" +
"<span id='email'>Email: " + m.email + "</span></br>" +
"<img id='slika' src='" + m.link_slike + "' />" + "</br>" +
"<textarea rows='5' cols='30' maxlength='500' id='t" + m.marker_id + "' placeholder='Komentar'>" + "</textarea></br>"
+ "<div class='buttons'><a href='odobri_prijavu.php?id=" + m.marker_id + "'>Odobri</a>" +
"<a href='izbrisi_prijavu.php?id=" + m.marker_id + "'>IzbriĆĄi</a>" + "</div>" +
"</div><hr>";
$('#content').append(markerHTML);
}
}
})
}
$(document).ready(page_loaded());
</script>
I tried to use buttons but I couldn't figure how to add event handlers to dynamically created buttons that will post a request via AJAX to some php script with the proper id as the value and the value of the textarea. So I used the anchor tag and I was able to send the id, but I can't send the value of the textarea because I don't know how to reference it and even if I referenced it, it will be NULL because its value is set to the anchor tag at the very beginning and I want to type in text in the textarea.
try this
$(".btn_class_nm").click(function(){
$.ajax({
type: "POST",
url: "http://domain.com/phpscript_filenm.php",
data: {
val1:"val1",
val2:"val1",
},
success: function(msg){
alert( "record updated"); //Anything you want
}
});
});
First of all give a Class Name to the Button as it is being generated dynamically and the number of them can vary based on the number of records the query returns. Something like this:-
echo "<input type='button' class='btn btn-primary btn-xs btn-block active view_data' value='Odobri' name='" . $row['marker_id'] . "b" . "' /></form><hr>";
Note that I have add view_data in the class definition. This will help is trapping the onclick event through jquery.
the jquery will be something like
$('.view_data').click(function(){
var yourvariable = JSON.stringify($(this).val()); //Gets Clicked button value
$.ajax({
url:"workstatus.php",
method:"post",
data:{yourvariable:yourvariable, anymoreyourvariables:anymoreyourvariables, , },
success:function(data){
$('#htmldivID').html(data);//If you want result there.
alert( "record updated"); //Anything you want
}
});
I hope this helps you.

PHP MySQL JS AJAX - Loop issue

I have PHP loop. I take the id, lat, lon data from record, passed it to script to do some calculations, then I passed this data to AJAX which will save the results of that calculation in MySQL DB, if it's successful then it will add the line of confirmation text to a results div.
My Code (I did trim it to keep focus on the issue)
<div id="distance_results"></div>
<?php
$result = $mysqli->query("SELECT * FROM test")
while($row = $result->fetch_array()) {
$id = $row['id'];
$city = $row['city'];
$lat = $row['lat'];
$lon = $row['lon'];
$driving_from = "51.528308,-0.3817765";
$driving_to = "$lat,$lon";
?>
<script>
var id = '<?php echo $id ?>';
var city = '<?php echo $city ?>';
var start = '<?php echo $driving_from ?>';
var end = '<?php echo $driving_to ?>';
// code
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// code
var mi = response.routes[0].legs[0].distance.value;
console.log(id);
console.log(city);
console.log(mi);
//Ajax Begin
$.ajax({
type: 'post',
url: 'test-dc-upd.php',
data: {'updateid': id, 'distance': mi},
success: function() {
html="Distance between London and " + city + " is " + mi;
$("#distance_results").append("<p>"+html+"</p>");
}
});
//Ajax End
} else {}
});
</script>
<?php } ?>
AND CODE FOR "test-dc-upd.php"
$id = $_POST['updateid'];
$distance = $_POST['distance'];
$result = $mysqli->query("UPDATE test SET distance='$distance' WHERE id='$id' LIMIT 1");
So PHP is looping thru MySQL DB, when but when I look at console:
'mi' values are calculated well according to lat / lon;
PROBLEMS:
1) 'id' and 'city' values stay the same (values of last record in the loop);
2) AJAX is updating value of last record in the loop only
So it obvious there is a some issue with the loop.
Any suggestion to what i do wrong?
Change this
$("<p>"+ html +"</p>").append("#distance_results");
To
$("#distance_results").append("<p>"+ html +"</p>");
Your jquery code is wrong. First you have to put selector and in append function the html code.
Nita, change the success function from:
success: function() {
html="Distance between CITYX and " + city + " is " + mi;
$("<p>"+ html +"</p>").append("#distance_results");
}
});
To
success: function() {
html="Distance between CITYX and " + city + " is " + mi;
$("#distance_results").append(<p>"+ html +"</p>);
// this will append the dynamic content to #distance_results
}
});
Explanation:
To put a dynamic content is some html object you have to first prepare
the content than select the html object and put the content into it.
In a loop calling ajax request is not a good practice we can easily pass array of values to javascript using the function implode like this
this implode function is for single dimensional array,
var ar = <?php echo '["' . implode('", "', $ar) . '"]' ?>;
For your question you need to create a multi dimensional array for the result like this ..
<?php
$result = $mysqli->query("SELECT * FROM test");
$arr= array();
while($row = $result->fetch_array()) {
$arr[]=array('id'=>$row['id'],'city'=>$row['city],'lat'=>$row['lat']...etc);
}
?>
afetr that you can pass each item in the array to javascript like this
var idArray= <?php echo '["' . implode(', ', array_column($arr, 'id')); . '"]' ?>;
var cityArray= <?php echo '["' . implode(', ', array_column($arr, 'city')); . '"]' ?>;
you can get each tag as array in javascript after that using a sing ajax request pass all javascript array to php script. and manipulate in the server side .
Your ajax request is like this
$.ajax({
type: 'post',
url: 'test-dc-upd.php',
data: {
'idArray':idArray,
'cityArray':cityArray, //etc you need pass all array like this
},
success: function(data) {
// your success code goes here
}
});
Note that array_column() function only supported by php 5.3 or above
I manage to do it a little different way i was hoping for ( But distance and travel time has been calculate for more then 3000 locations).
So what i did is to make sure mysql (test-dc.php) finds record where distance and travel time has not been calculated, makes calculation, update record with Ajax. Ajax on succesion opens the (test-dc.php) again, And is looping thru all results till there is nothing else to calculate. Had to refesh few times but thats fine, job done.
Adjustment to Mysql query:
$result = $mysqli->query("SELECT * FROM test WHERE distance='' LIMIT 1")
and to AJAX:
success: function() {
html="Distance between London and " + city + " is " + mi;
$("#distance_results").append("<p>"+html+"</p>");
location.href = "test-dc.php"
}
So that did the trick, but i still belive there is a better way of achiving the same result, i will be happy if someone could help me to figure it out.

Display data from php script in a table using ajax

I am looking to display data by running some query via php script and then using ajax to show it on an html page.
I have a php script that echos the data from a sql query in json format. The output looks like this:
{"Username":"Server","RICS":12739,"Exclusive_RICS":0}{"Username":"eikon1","RICS":4,"Exclusive_RICS":0}{"Username":"balbla","RICS":552,"Exclusive_RICS":0}{"Username":"somename","RICS":221,"Exclusive_RICS":201}
I would like to display this data using an $.ajax call.
I did some research and came up with this:
$(document).ready(function(){
$.ajax({
url : 'query.php',
type : 'POST',
data : {
//'numberOfWords' : 10
},
dataType:'json',
success : function(data) {
window.alert(data.Username)
},
error : function(request,error)
{
alert("Request: "+JSON.stringify(request));
}
});
});
However, it's not working properly. I just get this alert:
I am new to js/ajax/php so excuse me if I missed something simple.
Any help is appreciated. Thanks!
EDIT:
php code:
$sql = 'select * from table';
$retval = sqlsrv_query($conn,$sql);
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while( $row = sqlsrv_fetch_array( $retval, SQLSRV_FETCH_ASSOC) ) {
echo json_encode($row);
}
sqlsrv_free_stmt($retval);
//echo "Fetched data successfully\n";
sqlsrv_close($conn);
EDIT 2:
Managed to get the output of php in correct JSON format through this. Now just need to display this using ajax.
while( $row = sqlsrv_fetch_array( $retval, SQLSRV_FETCH_ASSOC) ) {
$rows[] = $row;
}
echo json_encode($rows);
Looping through your SQL result set and echoing each row separately produces an invalid JSON format. Instead you should json_decode the entire SQL result set.
Here's how you can update your PHP code so that it outputs the correct format:
php code:
$sql = 'select * from table';
$retval = sqlsrv_query($conn,$sql);
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
echo json_encode( sqlsrv_fetch_array( $retval, SQLSRV_FETCH_ASSOC) );
sqlsrv_free_stmt($retval);
//echo "Fetched data successfully\n";
sqlsrv_close($conn);
There may be one more step necessary in your AJAX success callback. You'll have to JSON.stringify the result because PHP will send it back as plain text:
success : function(data) {
var result = JSON.stringify( data );
window.alert(result.Username)
},
Thanks for the help everyone. I was eventually able to figure out the issue.
First of all, as pointed by users, my json format was not right. I
fixed that with the solution in my edit.
Secondly, I had to reference my php directly with the exact address. I think it has to do with running queries from same server. Not sure perfectly.
Thirdly, i tried a plain ajax call and even that was failing. It turns out my browser (chrome) needed a clean up. I cleared my cookies and it started to work fine. Why it was acting weird? I have no idea!
Finally, now I needed to display the data in a table format and
update the table frequently. I am still working with that but this is
what I got going for me right now:
$(document).ready(function() {
(function poll() {
$.ajax({
url : 'http://localhost/scripts/query.php',
type : 'POST',
data : {},
dataType:'json',
success : function(response) {
var json_obj = $.parseJSON(JSON.stringify(response));
var output="";
for (var i in json_obj)
{
output+="<tr>";
output+="<td>" + json_obj[i].time.date + "</td>" + "<td>" + json_obj[i].username + "</td>" + "<td>" + json_obj[i].rics + "</td>" + "<td>" + json_obj[i].exclusive_rics +"</td>";
output+="</tr>";
}
$('#table_content').html(output);
},
error : function(request,error)
{
alert("Request: "+JSON.stringify(request));
} ,
dataType: "json",
complete: setTimeout(function() {poll()}, 5000),
timeout: 2000
})
})();
});
I really don't understand why this was so hard to do. I am sure this is a common scenario and I really wish there was a more straightforward way of doing this. Hopefully, my final code will avoid others from wasting so much of their time. Good luck!

"SyntaxError: JSON.parse: unexpected character" Error when passing multiple variables from AJAX to PHP

I am using AJAX to pass variables from a form to a PHP page to process data at a database.
Once the user clicks a button it fires a the following JavaScript:
$(document).ready(function() {
$("#myForm").submit(function(event) {
/* validate the fields */
var firstDate= "11/10/2014"
var secondDate = "10/10/2014"
var myString = "some Text";
var myArray = ["name1", "name2", "name3", "123-123-33gf"];
processIT(firstDate, secondDate, muString, myArray);
});/* end of submit */
});
function processIT(firstDate, secondDate, muString, myArray) {
var response = "";
$(function () {
$.ajax({
url: 'api.php', // the script to call to get data
type: "POST",
data: {
firstDate: firstDate,
secondDate : secondDate ,
myString : myString ,
myArray : myArray ,
}, // you can insert url argumnets here to pass to api.php
dataType: 'json', // return data format
success: function(data) { //
alert(data);
},
error: function (jqXHR, textStatus, errorThrown){
console.log(textStatus, errorThrown);
},
});
});
return response;
}
The api.php page has the following
<?php
if ( isset($_POST["firstDate"]) && !empty($_POST["firstDate"])){
$response .= "<p>firstDate= " . $_POST["firstDate"] . "</p>";
}
else $response .= " 1 ";
if ( isset($_POST["secondDate"]) && !empty($_POST["secondDate"])){
$response .= "<p>secondDate = " . $_POST["secondDate"] . "</p>";
}
else $response .= " 2 ";
if ( isset($_POST["myString"]) && !empty($_POST["myString"])){
$response .= "<p>myString = " . $_POST["myString"] . "</p>";
}
else $response .= " 3 ";
if ( isset($_POST["myArray"]) && !empty($_POST["myArray"])){
$response .= "<p>myArray = " . $_POST["myArray"] . "</p>";
}
else $response .= " 4 ";
echo json_encode($response);
?>
But when I click the button I get the following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of
the JSON data
But if I change the POST to GET, I can see the passed variables, but still get the same error.
Any ideas what I am doing wrong?
Your PHP file is not outputting a valid JSON response, that's why JSON.parse is throwing an error. There are a number of errors in your PHP code, and those errors are being included in the output, thus making an invalid JSON response.
console.log("firstDate" + $_POST["firstDate"]);
This is not valid PHP code. PHP doesn't have console.log(). It has echo. P.S. You use . to concatenate strings in PHP, not +.
$_POST["secondDate "]
$_POST["myString "]
$_POST["myArray "]
These keys. There is no space at the end. They should be:
$_POST["secondDate"]
$_POST["myString"]
$_POST["myArray"]
Finally, $_POST["myArray"] is an array. You can't concatenate it to a string. Try this:
$response .= "<p>myArray = ".implode(', ', $_POST["myArray"])."</p>";

Categories

Resources