If possible to run again a php line after update a table in the database?
I have html button that fire a jQuery.post:
btn.onclick = function(e) {
$.post('inc/pstPts.php',
{
pts: pts
});
}
In pstPts.php I make the query and it update the target row with success.
I had loaded that row in a html with this:
<?php
for ($i=0; $i < $q->query_numrows(); $i++) {
print '<tr><td>' . $d[$i]['user_nom'] . ' ';
print '<tr><td>' . $d[$i]['user_ape'] . ' ';
print '<tr><td>' . $d[$i]['user_email'] . ' ';
print '<tr><td>' . $d[$i]['user_cel'] . ' '; }
?>
But this had loaded the old data.
I want to run just this 5 lines after the update.
since you have very less code, i will just post pseudocode to give an idea.
Server SIde:
//get the inputs from $_POST
// update the database
$update = $db->update($_POST); //simplified. just an example
if($update !== false)
{
$entry = $db->query("SELECT * FROM foo ...... WHERE id = $_POST['id']"); //take care of sql injections.
foreach($entry as $i)
{
//build up the html and echo it
}
}
Note: to bind the params (to make the query safe from sql injection), follow the examples in this binding links
Client Side:
$.post({
//url
}).done(function(data){
$('#selector').html(data);
});
done....
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.
Im working on a JS shopping cart site and I am trying to send the cart details to mail at the check out function using php mail,here im passing my cart details to php via ajax.
in php when try to send all the cart values using foreach im only able to recive the just last row of cart as foreach is repalcing the previous value
how do i retrive the cart values and send them in a format
js
function SendMail() {
var tableContent = localStorage.getItem('productsInCart');
$.post('read.php', {tableContent: tableContent}, function (data) {
console.log(tableContent);
});
}
php
if (isset($_POST['tableContent'])) {
$tableContent = json_decode($_POST['tableContent']);
foreach ($tableContent as $tableContent) {
$name = ($tableContent->name);
$price = ($tableContent->price);
$quantity = ($tableContent->inCart);
}
$mailTo = "xxxxxxxxxxxxx";
$Subject = " order details ";
$headers = "from :" . $contact;
$txt = "New registration \n Item:" . $name . "\n Quantity:" . $quantity . "\n Price:" . $price . "\n\n\n CUSTOMER DERAILS\n\n Name:" . $contact . "\n Reg No:" . $reg;
mail($mailTo, $Subject, $txt, $headers);
header("location: read.php?mailsend");
}
You're currently overwriting the same variables on each iteration of the loop, which is why they will only contain the last entry.
You should append the values instead, doing something like:
$tableContent = json_decode($_POST['tableContent']);
// Define a variable to store the items in
$items = '';
// Let's add a total sum as well
$total = 0;
// Let's also use different variable names here
foreach ($tableContent as $item) {
// Append to the variable (notice the . before the =)
$items .= 'Item: ' . $item->name . "\n";
$items .= 'Quantity: ' . $item->inCart . "\n";
$items .= 'Price: ' . $item->price . "\n\n";
// Add the price to the total (I'm assuming that the price is an integer)
$total += $tableContent->price;
}
Now when outputting the email body, we have all the items and the total in those variables:
$txt = "New registration \n" . $items . "Sum total: " . $total . "\n\n\n CUSTOMER DERAILS\n\n Name:".$contact."\n Reg No:".$reg;
As you can see, I changed the layout of the mail a bit since the cart seems to be able to contain several items while your email body was written as if only could contain one.
A warning about this approach
You shouldn't get the cart values, like name and price, from the client in a POST request like this. The client should only send the item id and quantity and then you would fetch the name and price from a database or similar in the backend. Otherwise, anyone can modify the price to be anything they want before it's posted. Never ever trust user data.
I am writing a hybrid app using Visual Studio with Cordova exetnstion and trying to pull data from www.a.com/b.php
My b.php code is:
<?php
// Connect to database server
mysql_connect("http://www.yo.com", "ya", "ye") or die (mysql_error());
// Select database
mysql_select_db("oh") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM Properties ORDER BY number DESC";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
echo '<select name="Address" id="address_search" style="width:282px; display:block;" required>';
while($row = mysql_fetch_array($rs))
{
// Write the value of the full address including unit code, address, city, state, zipcode (which is now in the array $row)
echo '<option value="'. $row['number'] . ", " . $row['address'] . ", " . $row['city'] . ", " . $row['state'] . ", " . $row['zipcode'] .'">'
. $row['number'] . ", " . $row['address'] . ", " . $row['city'] . ", " . $row['state'] . ", " . $row['zipcode'] .
'</option>';
}
echo '</select>';
// Close the database connection
mysql_close();?>
I already add select tag form directly in php code, but I don't know how to display the whole select box (with options being retrieved data) in .html.
Any help or tutorial? Thanks.
I have solved this issue like this:
First, in the server side-code (php in this case), in "file.php", I have an array with the database elements and I do the following:
$arrayElements = json_encode($arrayElements );
echo $_GET['jsoncallback'] . '(' . $arrayElements . ');';
After that, in the app js code, I use jQuery method $.getJSON() for getting the php array we prepare before. When the function get the server answer, then execute the code inside. Note that the variable "respuestaServer" is the array you have sent from php file, so you can go throw it with a loop and taking its values to your select (if you need to pass variables to your php file and receive them via GET just add the js variables inside the {}, in this example I send the variable datosUsuario and in php I receive it $_GET['usuario']).
var archivoValidacion = "http://example.com/file.php?jsoncallback=?";
var select = document.getElementById("idSelect");
$.getJSON( archivoValidacion, { usuario:datosUsuario ,password:datosPassword})
.done(function(respuestaServer) {
for(var i = 0; i < respuestaServer.length;i++){
var option = document.createElement("option");
var textNode = document.createTextNode(respuestaServer[i]);
option.appendChild(textNode);
select.appendChild(option);
}
})
I hope this can help you. If you have some questions just tweet me #ulisesveraes ;)
it is not clear how you call this code
I suppose you do this with jQuery ajax function
so your code will like something this
$('box-selector').load('b.php');
I would like to add an if statement regarding the 'type' column. Is there something after the .attr('type') which will allow me to specify a particular value for type?
$.get("map_process.php", function (data) {
$(data).find("marker").each(function () {
var name = $(this).attr('name');
var address = '<p>'+ $(this).attr('address') +'</p>';
var type = $(this).attr('type');
So $(this).attr('type'); is loading all the rows in my tables 'type' column value. eg:
Table
Name, Address, Type*
Name1, Address1, TypeA,
Name2, Address2, TypeB,
Name3, Address3, TypeA,
etc
How can I 'get access' to what actually the value of the 'type' column; eg. $(this).attr('type').<something>('TypeA');
Is this possible?
Edit2: map_process.php end
// Select all the rows in the markers table
$query = "SELECT * FROM markers";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo 'description="' . parseToXML($row['description']) . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
You have two options:
(1) If you have full control over the ajax page you are calling, the best solution would be to:
"send the selected checkbox value into map_process.php and get the
selected value from table and update the markers again in Map." –
Krish R
//jQuery
var cbVal = "TYPEA"; //Assign with checkbox value's associated string
$.get("map_process.php?checkboxval=" + cbVal, function (data)
{
//do something with the data returned
});
//PHP
$query = "SELECT * FROM markers where type = '".$_GET["checkboxval"]."'";
(2) If you don't have control over the source of the ajax call (for example from a third party source), OR you want to return all markers every time, consider using the jQuery Filter method.
//jQuery
var cbVal = "TYPEA"; //Assign with checkbox value's associated string
$(data).filter(function(index,val)
{
return $(val).attr('type') === cbVal;
}).each(function ()
{
//do something with the data returned
});
See the example for option (2) on this JSFiddle
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>