I am using Codigniter to redo a website. I have the following controller code:
public function get_topics()
{
$topic = $this->input->post('input_data');
$topics = $this->firstcoast_model->get_topics_like($topic);
foreach ($topics as $val) {
echo "<pre id = \"pre_" . $val['id'] . "\">";
echo $val['formula'];
echo "<br />";
// generate a unique javascript file.
$f = "file_" . $val['id'] . ".js";
if (!file_exists($f));
{
$file = fopen($f,"w");
$js = "\$(\"#button_" . $val['id'] . "\").click(function(){\$(\"#pre_" . $val['id'] . "\").hide();});";
fwrite($file,$js);
fclose($file);
}
echo "<script src=\"file_" . $val['id'] . ".js\"></script>";
echo "<button id=\"button_" . $val['id'] . "\">Hide</button>";
echo "</pre>";
}
}
The basic idea to make an AJAX call to the function to retrieve a list of formulas.
The purpose of the javascript is to be able to hide any of the formulas by
hiding the <pre> </pre> tag that surrounds them The js file (i.e. file_1.js) I generate looks like:
$("#button_1").click(function(){$("#pre_1").hide();});
and the button code is:
<button id="button_1">Hide</button>
The problem is that it doesn't work. The files get generated, but clicking on the "Hide"
button does nothing. The puzzling part is that the exact same code works on the original website where I just make an AJAX call to a PHP file that generates the same code.
Any ideas what could be going on here?
Edit:
On my old website I used:
$query = "SELECT * FROM topics WHERE term LIKE '%" . $term . "%'";
$result = mysql_query($query);
while ($val = mysql_fetch_array($result))
{
echo "<pre id = \"pre_" . $val['id'] . "\">";
etc.
etc.
}
and everything works fine. If I now put the results of the while loop into to an array and then do a foreach loop on that, the results are very intermittent. I'm wondering if the foreach loop is the problem.
i think you can return list buttons in json response
public function get_topics()
{
$topic = $this->input->post('input_data');
$topics = $this->firstcoast_model->get_topics_like($topic);
$response = array('buttons' => $topics);
header('Content-Type: application/json');
echo json_encode( $arr );
}
so client can parse which button element to be hide.
<script type="text/javascript">
$(document).ready(function(){
$('somEL').on('submit', function() { // This event fires when a somEl loaded
$.ajax({
url: 'url to getTopics() controller',
type : "POST",
data: 'input_data=' + $(this).val(), // change this based on your input name
dataType: 'json', // Choosing a JSON datatype
success: function(data)
{
for (var btn in data.buttons) {
$(btn).hide();
}
}
});
return false; // prevent page from refreshing
});
});
</script>
Related
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.
I have a questions for which I need some help.
I have a page which, after it is finished loading, executes an AJAX, creates a table in PHP containing 2 buttons: 1 change password, the other is delete. Once the table is complete it is injected into a div in the main file. That works great so far. Now after that table is loaded, I want to be able to call another AJAX function linked in the JS file in the main page. So I have 3 components:
1. <div id="DbInfo"></div>
That is where I add the information from the users.
my php which executes the code and gets the information from my database.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT LoginName FROM table";
$res = mysqli_query($conn, $sql);
if (mysqli_num_rows($res) > 0) {echo "<center>";
echo "<table border='1'>";
echo "<tr>";
echo "<td>User</td>";
echo "<td colspan=2 align=center>Available Functions</td>";
echo "</tr>";
while($row = mysqli_fetch_assoc($res)) {
echo "<tr>";
echo "<td>" . $row['User'] . "</td>";
echo "<td><button type='button' class='smallbutton' id='removeUser' value='" . $row['LoginName'] . "'>Delete User</button></td>";
echo "<td><button type='button' class='smallbutton' id='CPW' value='" . $row['LoginName'] . "'>Change Password</button></td>";
echo "</tr>";
}
echo "</table>";
echo "</center>";
} else {
echo "";
}
mysqli_close($conn);
And lastly the AJAX which does the injection of the created table into the HTML:
$(document).ready(function(){
$.ajax({
method: "POST",
url: "UserData.php",
success: function(data){
//document.getElementById("DbInfo").innerHTML = data;
document.getElementById("DbInfo").html(data);
}
});
});
Again, these functions are working fine. What I want to do after the page is done, be able to click one of these injected buttons and execute another AJAX. Unfortunately the standard declaration that I use for AJAX does not work.
$(document).ready(function(){
$("#removeUser").click(function(){
The question: How can I make sure after the table is injected, that I can call an AJAX function which is linked as an external source (<script src="script.js"></script>) in the main document?
Thanks for your help.
try :
$('#DbInfo').on('click', 'button[id="removeUser"]', function(i,e){
console.log('remove :' + $(this).val());
});
Say I have 10 items in my db that I am trying to shuffle, how could I alter my current code so that every time it pulls a name out of the db that it shows up one at a time, rather than all at once?
$con = mysqli_connect("XXX", "XXX", "XXX", "XXX");
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` = 3");
echo 'Normal results: <br>';
$array = array();
while ($row = mysqli_fetch_assoc($query)) {
$array[] = $row;
echo $row['firstname'] . ' ' . $row['lastname'] . '<br>';
}
?>
<form method="post">
<input type="submit" value="Shuffle" name="shuffle">
</form>
<?php
if (isset($_POST['shuffle'])) {
shuffle($array);
echo 'Shuffled results: <br>';
foreach ($array as $result) {
$shuffle_firstname = $result['firstname'];
$shuffle_lastname = $result['lastname'];
?>
<div id="shuffle_results">
<?php echo $shuffle_firstname . ' ' . $shuffle_lastname . '<br>';?>
</div>
<?php }
}
//What I added in and this is the spot I added it as well
$get_shuffle = array($array);
$shuffle_one = array_pop($get_shuffle);
print_r($get_shuffle);
?>
I want them all to stay put once they have shown.. I just want all of them to come out one at a time. Say, there is 10 pieces of paper in a bag and you are drawing one at a time and then put the pieces of paper on a table to show what was drawn, that is what I want.
As a follow up to my comment suggesting you use JavaScript instead of PHP for the animation, here is a basic way to do it. (This code assumes you have jQuery on the page).
Note: I haven't tested this code and there is likely a bug or two, but I hope you get the general idea.
Your HTML
<div id="shuffle_results"></div>
<form onsubmit="getData()">
<input type="submit" value="Shuffle" name="shuffle">
</form>
Your PHP
$con = mysqli_connect("localhost", "root", "", "db");
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` = 3");
$array = array();
while ($row = mysqli_fetch_assoc($query)) {
array_push($array, $row);
}
header('Content-Type: application/json');
echo json_encode($array);
Your JavaScript
function getData() {
$.ajax({
url: 'url to PHP script',
dataType: 'json',
success: function(data) {
for(var i = 0, l = data.length; i < l; ++i) {
window.setTimeout(addResult, 2000, data[i].firstname, data[i].lastname);
}
},
error: function(jqXHR, textStatus, error) {
alert('Connection to script failed.\n\n' + textStatus + '\n\n' + error);
}
});
}
function addResult(firstname, lastname) {
$('#shuffle_results').append("<p>" + firstname + " " + lastname + "</p>");
}
The basic idea here is that you shouldn't use PHP to do DOM manipulation. PHP can load data into your webpage (and that data can be DOM elements, JSON data as I have shown, or other types of data), but once there JavaScript should be used to interact with it. Recall, PHP runs on your server, while JavaScript (traditionally) runs in the client's web browser.
As the question suggest can you tell me how i can update mysql database using a dropdown menu with the help of ajax. I want to update my database with out reloading my whole webpage.When a user click edit button the selected option from the drop down list is updated. After searching a while i found some tutorials for this method and took ajax codes from there. But when i tried those in my database; it didn't worked out. Below is the sample code for my php script, parent file contains both ajax script and php code in a single php file called samefile.php. Below script only contains the problematic codes, some html and php codes are intentionally removed.
//THIS AJAX SCRIPT FETCHES VALUES FROM THE SELECTED DROPDOWN
<script>
function get_da(str){
$.ajax({
url: "samefile.php",
type: "POST",
async: true,
data: { dropdown1:$("#dropdown").val()}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
}
);
</script>
///////////////////////////////FIRST BLOCK//////////////////
<?php
//THIS PHP SCRIPT GENERATES DROP DOWN VALUES FROM DATABASE
echo "<select name='dropdown' onChange='get_da(this.value)'>";
while ($row = mysql_fetch_array($result))
{
if($row['id']==$row['user'])
{
echo "<option value='" . $row['id'] . "' selected>" . $row['name'] . "</option>";
}
else{
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
}
echo "</select>";
/////////////////////////////SECOND BLOCK//////////////////////////////
//THIS PHP SCRIPT VALIDATES THE SELECTED DROPOWN VALUE AND PASS THOSE VALES FOR FURTHER PROCESSING.
if(isset($_REQUEST['dropdown1']))
{
$name=get_the_selected_dropdown_name; //i dont know how to fetch name from dropdown menu
$sql = "UPDATE table SET name = '$name' WHERE id =10";
mysql_real_escape_string($sql);
$result = mysql_query($sql) or die (mysql_error());
if ($result==1) {
echo "Success";
}
else { echo "Failed";}
}
//////////////////////////////THIRD BLOCK////////////////////////////////////
?>
I believe this is how my above script works. when a user select a particular option from the drop down menu this function onChange='get_da(this.value)' sends the value (both id and name) to ajax query. in ajax query the drop down values are collected (both id and name) and renames as dropdown1 (data: { dropdown1:$("#dropdown").val()}) and pass it to php script inside the same file. Php script confirms the request from ajax using this if(isset($_REQUEST['dropdown1'])) and the script inside will be executed.
Please forgive me if i made a mess of my code. I suck at java script and ajax so am not sure whether my coding is right for those scripts. if possible can you suggest any other scripts for updating mysql database using ajax drop down list.
EDITED
ID DROPDOWN VALUE
1 ROY
2 TOM
3 CHASE
4 THOMAS
5 GEORGE
6 MICHAEL
have tried by printing the value you are sending in ajax request. You are passing this.value to your function get_da(str). But I think you are using it anywhere , In ajax post you are sending the value like
data: {dropdown1:$('#dropdown').val()}
But this will not post your selected vaule from dropdown, Try like this:
<script>
function get_da(this){
var id = $("#dropdown option:selected").val();
var selectedName = $("#dropdown option:selected").text();
$.ajax({
url: "samefile.php",
type: "POST",
async: true,
data: { dropdown1:id, name:selectedName}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
//drawVisualization();
},
});
}
</script>
Hope this will work.
Your dropdown script should be like this:
<?php
echo "<select name="dropdown" onchange="get_da()" id="dropdown">";
while ($row = mysql_fetch_array($result))
{
if($row['id']==$row['user'])
{
echo "<option value='" . $row['id'] . "' selected>" . $row['name'] . "</option>";
}
else{
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
}
echo "</select>";
This will send your selected value from drop down to your samefile.php.And also you are not doing good with your php script it should be like:
if(isset($_REQUEST['dropdown1']))
{
$id=$_REQUEST['dropdown1'];
$name=$_REQUEST['name'];
$sql = "UPDATE table SET name = '$name' WHERE id ='$id'";
mysql_real_escape_string($sql);
$result = mysql_query($sql) or die (mysql_error());
if ($result==1) {
echo "Success";
}
else { echo "Failed";}
}
?>
Ok so I have:
A PHP file that queries a database and displays the results of the query,
a HTML file that displays the results using AJAX and
another PHP file that I need to send the data from the first PHP file to.
How can I do this?
My first PHP file displays:
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shopresult .= "<div class='result'><a id='shoplink' href='#shop'><strong><div id='hiddenid'>" .
$row['id'] . "</div>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br><i>" .
$row['sold'] . "</i></div></a>";
}
So the AJAX brings this in and displays it in the HTML. Is there a way of sending the ID field when the link is clicked so that it can be used in another PHP file to display the data for that specific ID.
$( "#result" ).click(function() {
$.ajax({
type: "POST",
url: "external-data/shop.php",
data: $("#hiddenid"),
success: function (data) {
$("#individualshop").load("external-data/shop.php");
}
});
So that the data from the #hiddendiv ($row ['ID']) will be sent to the new PHP file. This isn't working.
shop.php has the code:
//get shop ID
$shopid = $_POST['ID'];
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM shops WHERE ID='$shopid'";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shops .= "<div class='searchresult'><strong>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br><i>" .
$row['sold'] . "</i></div>";
}
But I'm not sure how to retrieve the ID?
Basically I need to be able to click on each search result and have another PHP file bring in specific data associated with the ID of the search result. Any suggestions??
Thanks in advance!
I'm not 100% sure this is what you want but this is one way.
This is your first php file. I've added an onclick listener to it so when a user clicks a row it will fire a JavaScript passing the $row['id'] variable.
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shopresult .= "<div onclick='someFunction(" . $row['id'] . ")' class='result'><div id='shoplink' href='#shop'><strong><div id='hiddenid'>" .
$row['id'] . "</div>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br><i>" .
$row['sold'] . "</i></div></div>";
}
Then add this script to the header of the page.
<script>
function someFunction(d){
var response = httpGet("http://yourdomain.com/newphpfile.php?page_id=" +d);
document.getElementById('someResultArea').innerHTML = response;
}
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "POST", theUrl, false );
xmlHttp.send();
return xmlHttp.responseText;
}
</script>
Then your new php file should do something like this.
newphpfile.php
<?php
session_start();
$page_id = strip_tags($_GET['page_id']);
$processResult = 'handle your result';
echo $processResult;
?>
I hope this helps you out.
Use this;
$( "#result" ).click(function() {
$.ajax({
type: "POST",
url: "external-data/shop.php",
data: "ID=" + $("#hiddenid"),
success: function (data) {
$("#individualshop").html(data);
}
});
});
Note: Do not forget to return html in shop.php
You can fetch the clicked element id by using either javascript or jquery, and put it in the GET parameters on the php link
the ajax target would be ajax.php?id=test
Then get the value of id via $_GET['id']