in my webpage, I have the following code:
<?php
echo "<td class=\"action\">
?>
<script>
function deleteline(a) {
var r=window.confirm("Voulez-vous vraiment supprimer le viager " + a +"?");
if (r)
{
<?php
$test="<script> document.write(a);</script>";
mysql_connect("localhost", "xxxxxx", "xxxxxx") or die (mysql_error ());
mysql_select_db("xxxxxx") or die(mysql_error());
$strSQL =("update viagers set statut='deleted' where id=????");
$rs = mysql_query($strSQL);
mysql_close();
?>;
}
}
</script>
In a php table, i have an small delete icon in each row. I want the user to be able to click on it so it deletes the record in the sql db. I can't find a way to retrieve the 'a' variable in the php code of my script function (replace by ????).
Could you please help?
thanks and regards
Harold
You can't mix javascript and PHP like that. Make another PHP file for deletion, and send the a by javascript to the file through AJAX.
PHP code inside javascript is not a good approach. As lqbal Fauzi mentioned, send a variable - row id by javascript to the php file through AJAX - or as I do below, by using JQUERY. In php file, you can do your database stuff and if wanted, send some result back to your application.
In your HTML file you have to have scripts with JQUERY library source files.. Download these 2 files from here:
https://mega.co.nz/#!IUAFCYZb!Cu0mQoAVAkJHzqvac40-RYA-n3TnhYGtoazw5k_PMv4
https://mega.co.nz/#!hABhFDiS!Q_L8rERVq8330zrOxXXen0uxmLCes7zYG6J6SCncz6M
and save/copy those files into the folder containing your html file.
Your html file should look something like this:
<html>
<head>
<meta charset="utf-8" />
<title>Your page Title</title>
<script src="jquery.mobile-1.3.2.min.js"></script>
<script src="jquery-1.9.1.min.js"></script>
<script>
function yourJavascriptfunction(sender){
var r=window.confirm("Voulez-vous vraiment supprimer le viager " + sender.name +"?");
if (r)
{
$.post("YourPHPPageToAccessDatabaseAndSendResult.php", {
UserID:sender.name
})
.success(function(data){
//some code on data return if you want
alert(data); //should pop up with message saying "Hello, this is the result data"
})
.fail(function(error){
alert("Unable to retrieve data from the server");
});
}
}
</script>
</head>
<body>
<button type="button" name="YourRowID" onclick="yourJavascriptfunction(this)" > your button text</button>
</body>
</html>
and in the php file named YourPHPPageToAccessDatabaseAndSendResult.php which has to be in this case in the same directory as your html file following code:
<?php
$connection = mysql_connect("localhost","USER","YOURPASSWORD") or die(mysql_error());
mysql_select_db("DatabaseName",$connection);
$UserID= $_POST['UserID'];
$strSQL =("update viagers set statut='deleted' where id=$UserID");
$rs = mysql_query($strSQL);
mysql_close();
//by printing with echo you sent some data that you want return to your html file
echo "Hello, this is the result data";
?>
The above code is not tested for functionality, there might be some typos, but the logic in there should work and help you in the future
Don't forget to substitute the YourRowID in button name in html file to whatever you need, and set correct USER, YOURPASSWORD and DatabaseName in the php file.
Related
Im building an app using PHoneGap as the compiler so using HTML5, CSS, JQuery, AJAX etc. Ive manage to get AJAX to GET all the rows from the Database perfectly well, as I have to use .HTML extension on my files I'm struggling to be able to link through to specific DB record. I can do this perfectly in PHP. Im struggling with the HTML part.
Here is my AJAX Loader to get all Rows from DB
var inProcessVideos = false;//Just to make sure that the last ajax call is not in process
setTimeout( function () {
if (inProcessVideos) {
return false;//Another request is active, decline timer call ...
}
inProcessVideos = true;//make it burn ;)
jQuery.ajax({
url: 'https://MY-URL.COM/videos-mysql.php', //Define your script url here ...
data: '', //Pass some data if you need to
method: 'POST', //Makes sense only if you passing data
success: function(answer) {
jQuery('#videos-modules').html(answer);//update your div with new content, yey ....
inProcessVideos = false;//Queue is free, guys ;)
},
error: function() {
//unknown error occorupted
inProcessVideos = false;//Queue is free, guys ;)
}
});
}, 500 );
And here is the contents of the PHP File that renders all the Results from the Database. This part displays the content perfectly.
<?php
include ("../config/mysqli_connect.php");
$sql = ("SELECT * FROM videos");
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "
<a href='" . $row["id"]. "'>
<div class='video-module'>
<div class='video-thumb'><img src='https://MY-URL.COM/thumbs/" . $row["video_thumb"]. "'></div>
<div class='video-thumb-details'>
<div class='video-thumb-title'> " . $row["id"]. " - " . $row["video_title"]. "</div>
" . $row["publisher_name"]. "
</div>
</div></a>
";
}
} else {
echo "0 results";
}
?>
After the ECHO statement I would normally put something like video-Profile.php?id=$id and it would go to that page and pull in that record from the Database.
However now that I have to do it only in HTML, and im assuming AJAX, how to I achieve this.
Here is the PHP and the MYSQL Query to GET the specific record from the Database. Its currently in MYSQL, I will convert it to MYSQLi once I've got it working and got my head around it.
<?php
// Use the URL 'id' variable to set who we want to query info about
$id = ereg_replace("[^0-9]", "", $_GET['id']); // filter everything but numbers for security
if ($id == "") {
echo "Missing Data to Run";
exit();
}
//Connect to the database through our include
include_once "../config/connect_to_mysql.php";
// Query member data from the database and ready it for display
$sql = mysql_query("SELECT * FROM videos WHERE id='$id' LIMIT 1");
$count = mysql_num_rows($sql);
if ($count > 1) {
echo "There is no user with that id here.";
exit();
}
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$video_title = $row["video_title"];
$video_thumb = $row["video_thumb"];
$publisher_name = $row["publisher_name"];
$video_directory = $row["video_directory"];
$video_path = $row["video_path"];
$upload_date = $row["upload_date"];
$video_views = $row["video_views"];
}
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<?php echo ("$id");?> - <?php echo ("$video_thumb");?>
</body>
</html>
I know this works if I'm running PHP files, and my server is set to PHPv5.3., but before I make it live, it will be sorted to MYSQLi and run on PHP7???
Im looking for inspiration to get this to function via HTML only files.
thanks for your help everyone.
This is a pretty brutalistic way of doing this - typically you'd return JSON or similar from the PHP and then process this into the HTML elements within your JS. But for this case you can do this:
//within call
success: function(answer) {
var contents = jQuery(answer); // You have now converted the HTML into a jquery model
contents.filter(function(element){
return $(element).attr('id') === id
}) // This allows you to search your child elements and pick them based on criteria
jQuery('#videos-modules').html(contents); // now assign the remaining elements into your html as before
},
I have Tried this but i cant seem to find out how to Run a Console Log as it is Run on iOS iPad at the moment. Can not get it to render in the Browser.
var inProcessVideos = false;//Just to make sure that the last ajax call is not in process
setTimeout( function () {
if (inProcessVideos) {
return false;//Another request is active, decline timer call
}
inProcessVideos = true;//make it burn ;)
jQuery.ajax({
url: 'https://MYURL.COM/appFiles/tablet/video-profile.php', //Define your script url here ...
data: '', //Pass some data if you need to
method: 'GET', //Makes sense only if you passing data
success: function(answer) {
var contents = jQuery(answer); // You have now converted the HTML into a jquery model
contents.filter(function(element){
return $(element).attr('id') === id;
});
jQuery('#videoProfile').html(answer);//update your div with new content, yey ....
inProcessVideos = false;//Queue is free, guys ;)
},
});
}, 500 );
Struggling with this, i've looked at all the JQuery, AJAX MySQL web sites i can find including W3Schools, Jquery.com and many others. Just can not get it to pass the ID to the PHP file to get the Record from the DB via AJAX.
My Links in the first JQuery AJAX Call are:
<a href='video-Profile.html' data='".$row["id"]."' value='".$row["id"]." '>Some HTML STUFF/Images/Text etc</a>
I can get the ID and the First AJAX Call to show ALL the rows in the DB Table. Now just need to show Record by ID. This is what i cant get my head around. And it must be in .HTML Page as its an App compiled via PhoneGap. I know im repeating my self, Just not to sure if im making my point clear. Thanks for the help in advance.
I am attempting of using a plain text-file (text.txt) as part of html5 - server side events.
Currently I am not seeing any printout of text in browser. If just running this line, without using an external file for input data, it works:
echo "data: test\n\n";
Question: What do I need to adjust to make the external file data to be visible in the browser, assuming the setup of below files?
My html file
<h1>SSE</h1>
<div id="result"></div>
<script>
// Create an object
var source = new EventSource("updater.php");
// Detect message receipt
source.onmessage = function(event) {
// Write the received data to the page
document.getElementById("result").innerHTML += event.data + "<br>";
};
</script>
my php file
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
// Include files
echo include("text.txt");
flush();
?>
my text file:
"data: t1972\n\n";
The solution for the question, works if using [file_get_contents] as specified below.
$data = file_get_contents('text.txt');
echo "data: " . $data . "\n\n";
This also means that the file [text.txt] is left with only text, removing the [data: ] and [\n\n].
I want to display a download link inside a WordPress widget. The file to be downloaded is located in the download subfolder of the site root, so that it can be uploaded via FTP. The name of the file and the text to be displayed for the download link shall be stored in a simple text file in the same folder.
Assuming WordPress is installed on www.mysite.com. The file name is setup_1_0.zip and the link display is Setup 1.0.
I am open to the file format how this information is stored as long as I can upload that file via FTP, too.
How can I embed this information inside a Custom HTML widget to get a valid download link with the text taken from that file?
How to automate the process of uploading latest software's build and download link creation in WordPress?
Based on your logic.
You are trying to automate the download process of your latest software version.
You don't want to update things manually and you just want to upload your latest build in the /download/ folder. (Only drop your latest version using FTP; that's all)
This is how I would do it:
Referencing those questions:
Get the latest file addition in a directory
How to force file download with PHP
I propose two solutions: First two separte codes, Second One inline code.
Just for educational purpose
First solution: Quick and short usage:
(You might need a way or a plugin to activate running PHP in Widget; this plugin helps PHP Code Widget)
<?php
$path = "download/";
$latest_ctime = 0;
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
echo 'Download '. $latest_filename . '';
?>
Second solution:
(Again, you might need a way or a plugin to activate running PHP in Widget; this plugin helps PHP Code Widget)
A) Create download.php in http://www.example.com/download.php
Add the following code:
<?php
$path = "download";
$latest_ctime = 0; //ctime stands for creation time.
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
// echo $latest_filename; un-comment to debug
$file_url = 'http://www.example.com/download/'.$latest_filename;
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url); // do the double-download-dance (dirty but worky)
?>
B) in your WordPress HTML Widget add the following code
<?php
$path = "download";
$latest_ctime = 0;
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
echo 'Download '. $latest_filename . '';
?>
Further explanation:
A) is responsiple for downloading the latest software build automatically.
B) is responsiple for displaying Latest build name and Creating the link.
Now, You only need to upload one file to your /download/ folder which is your latest build (setup_1_0.zip, setup_1_1.zip, setup_1_2.zip ...etc. The proposed solution will check creation date regardless of file's name.)
Important note: You can see that the latest file checker function is repeated twice; once in download.php and once in WordPress Widget. Because if we combine in one file we will get header already sent error.
Dose this answer your question please? Kindly feedback.
Let's say I have completed my index.html file with all the CSS and JavaScripts and I want to create some other ones like: "contact", "about us", "music" etc.
They all have to go into the same root folder as the index.html. Well this is ok with me since there's not that many, but what about sub-categories? Like in music I would like to have 10 different genres.html and inside that, 20 more artists.html and so on. This would entirely cluster my root folder. And putting them into a sub-folder doesn't work either, because then all the links to the centralized resources (like: CSS files, images, JavaScript) break. And having to manually adjust every absolute path is also a pain. I gave <base> a try but it messed other things up.
What is the best and simplest way to organize your website's page structure (preferably without a CMS)?
If PHP is an possibility, you could use an very simple script like this:
{root}/index.php
<?php
if(!isset($_GET['route'])){ // If no route is given
require_once 'pages/index.html'; // Load the default index page
}else if(!file_exists('pages/' . $_GET['route'] . '.html')){ // If an route is given, check if the page exists
require_once 'pages/404.html'; // If not, load an 404 page
}else{
require_once 'pages/' . $_GET['route'] . '.html'; // Or else load the given route
}
The url's will then be something like this:
www.yoursite.com/index.php?route=index (index.html inside the pages folder)
www.yoursite.com/index.php?route=contact (pages/contact.html)
www.yoursite.com/index.php?route=catalog/category/something/list (pages/catalog/category/something/list.html)
This is very simple and basic PHP using so called $_GET variables (More about that here )
All the requests will be handeld by the index.php inside the root of your website.
Because of that, your include link for your JS and CSS files, will always be from the root directory. Therefore, you don't need to worry about all the different paths.
If you need more help, just ask.
Update
Your folder structure could be something like this than:
root/
css/
js/
img/
pages/
music/
artist.html
something/
else/
stuff.php
index.html
contact.html
index.php
And instead of doing $_GET['route'] . 'html', you could also use just $_GET['route'] and append the file extension to the url. This way you can use all different types of file extensions. (www.yoursite.com/index.php?route=music/artist.php)
Or you could just change .html to .php. That's all up to you!
I use to design my page's structure with the help of PHP.
Here's how I would do it:
Template page
you can make your own template and only fill in the content:
<?php
$root = "";
require_once $root . 'class/page.php';
$page = new Page();
?>
<!DOCTYPE html>
<html>
<head>
<?php
$page->metaTags();
$page->metaDescription("");
$page->metaKeywords("");
$page->defaultStyles();
$page->addStyle("styleName");
$page->title("your page title");
$page->defaultScripts();
?>
</head>
<body>
<?php
$page->navigation();
$page->header();
$page->openContainer();
$page->openContentSection();
?>
Your page content
<?php
$page->closeContentSection();
$page->closeContainer();
?>
</body>
</html>
Now the page class will handle the layout and the links so you can make your changes in 1 place and still affect all the pages in your site.
Page class
class Page{
private $db;
private $root;
private $terms;
public function __construct() {
$this->db = new db();
...
}
public function metaDescription($desc){
echo '
<meta name="description" content="' . $desc . '" />';
}
public function defaultStyles(){
echo '
<link href="' . $this->root . 'css/bootstrap.min.css" rel="stylesheet" />';
}
....
}
Now, the pages can be anywhere you want them to be, you just set the $root to your absolute website url and all the includes will be correct no matter where your files are being saved.
I,m trying to access Magento session data outside Magento using Json.Json is working fine in IE but when i tried to access Magento session data using json then it does't work.
Code works in FF,Chrome,Opera .. but not in IE 7
Here is my server.php file
<?php
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
Mage::app();
if(isset($_GET['cart_item'])){
Mage::getSingleton('core/session', array('name'=>'frontend'));
$_cartQty=0;
$_cartItem='My Bag is empty';
foreach (Mage::helper('checkout/cart')->getCart()->getItems() as $item){
$_cartQty+=$item->getQty();
}
if ($_cartQty>0)
$_cartItem='My Bag ('. $_cartQty.')';
echo $_GET['callback'] . '('.json_encode(array('response'=>$_cartItem)).');';
}
?>
here is my client.html file
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
function change_cart_item(){
var cartItemUrl=jQuery('#cart_item_url').val();
jQuery.getJSON(cartItemUrl, function(json) {
var result=json.response;
alert(result);
//var cartItem = jQuery(result).find('#cart_item').html();
//jQuery("#show_cart span").html(result);
});
return false;
}
</script>
<input id="cart_item_url" name="cart_item_url" type="hidden" value="http://test.com/ie.php?callback=?&cart_item=cart_item" />
<input type="button" onclick="change_cart_item()" value="Change cart item" />
The above code always return "My Bag is empty" in IE.
I suggest checking why IE doesn't send the cookie headers to the /ie.php script. IE must somehow evaluate the cookie path value differently.
As a workaround try implementing a regular Magento action controller that simply returns the JSON, since that is bound to receive the cookie headers by IE (otherwise the whole store front of Magento would not work with IE).
To return JSON from a action controller use:
public function jsonAction()
{
$_cartItem = 'My Bag is empty';
$_cartQty = Mage::helper('checkout/cart')->getItemsQty();
if ($_cartQty > 0) {
$_cartItem = 'My Bag ('. $_cartQty.')';
}
$this->getResponse()->setBody(
$_GET['callback'] . '(' . Mage::helper('core')->jsonEncode(array('response'=>$_cartItem)).');'
);
}
There is a bug in IE's implementation of WinInet. If you have a cookie that has a path with a filename in it, IE will not make it available via the document.cookies property in Javascript. Such a cookie should be transmitted to the server though.