Bear with me; this is my first StackOverflow question. I'm having trouble writing a proper algorithm. Perhaps doing all this to "force" it means I'm over-complicating a simple concept, but it's also very likely I'm just unaware of the fix.
I'm building an experimental cookbook that reads from a database and displays in the browser. I created a list (note: NOT a <ul> or <ol> element) that is populated by <span> items generated by a PDO query to the database. These spans reference the name of each recipe in the database.
<p>
<?php
$recList = $pdo->query('SELECT name FROM Recipe');
$rowCount = $recList->rowCount();
echo 'There are ' . $rowCount . ' recipes currently in our database!';
echo '<br /><br />';
while ($row = $recList->fetch()) {
echo '<span class="recName"';
echo '>' . $row['name'] . "</span><br />";
}
?>
</p>
I then created a scrolling div element:
<div id="recWindow">
<!-- Display recipe queried from the database here -->
<?php require("$DOCUMENT_ROOT/$rec_source"); ?>
</div>
I would like the user to be able to click on the recipe names generated by php and the chosen recipe to display within the <div>. Choosing different recipes should not cause the page to reload.
I feel like the answer lies in an AJAX request to a php file listening for a variable containing the recipe to display, but that's where I'm stuck. Somehow I need to pass the php list items a unique identifier that is recognized by javascript, which in turn handles the onclick change in the div by passing that identifier BACK to php to query the database. While typing that out, I'm almost certain that I've over-complicated this entire process.
I thought of using a dropdown select menu and a GET request, but I'd like to retain the clickable names function if possible.
Answers that conclude my proposed method is too "dirty" and point me in a better direction are completely acceptable. I'm happy to provide any necessary information I left out. Thank you so much in advance.
Environment: Virtual LAMP (CentOS7, MariaDB)
Try something like this
<p>
<?php
$recList = $pdo->query('SELECT name FROM Recipe');
$rowCount = $recList->rowCount();
echo 'There are ' . $rowCount . ' recipes currently in our database!';
echo '<br /><br />';
while ($row = $recList->fetch()) {
echo '<span class="recName" data-id="' . $row['id'] . '"';
echo '>' . $row['name'] . "</span><br />";
}
?>
</p>
<div id="recWindow">
<!-- Display recipe queried from the database here -->
<?php require("$DOCUMENT_ROOT/$rec_source"); ?>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("body").on("click", "recName", function() {
//* get id of required recipe
var recId = $(this).attr("data-id");
//* send ajax-request to back-end
$.ajax({
url: "/get-recipe.php",
method: "GET",
data: {
id: recId
},
success: function(respond) {
//* put recipe-data into container
$("#recWindow").html(respond);
}
});
});
});
</script>
I hope, it shows you the main idea
Related
First, please understand I have just begun to learn php, javascript and ajax in the past 10 days so I will need some hand-holding and step-by-step examples and guidance. I've carefully read the courses for those topics at w3schools and found them very helpful; as a result, I was able to write some basic code for my project by using their examples and other snippets I've found here and other sites.
This post is a little lengthy so I can explain my ultimate goal for this code and what I've already tried.
I have started writing a piece of very complex code that has multiple parts, but the final result will be a dropdown selection list with an image thumbnail button of the main_image of that page linked to an external URL which is dynamically created based on the user's dropdown list selection.
This is my project:
I am building a website with Joomla 3.x.x, Bootstrap 3 and j2store (with other components and modules) that features photos for sale as digital images and that can be applied to physical products (canvas prints, t-shirts, coffee mugs, etc). Those physical products exist on a 3rd party website (Zazzle) which are embedded into my private website with Zazzle's RSS feed and another 3rd party javascript code (to embed Zazzle RSS feed grid displays into my website).
The Zazzle API allows my users to choose any image from my private website and apply that image to any product available in Zazzle's marketplace.
My users would ultimately select a category of products from a dropdown list on my website and then click a button that would open a new window to connect to the Zazzle marketplace which would display a grid of relevant physical products featuring the image shown on the active page of my website where the user clicked the button.
For example, the user starts by looking at the page on my website with the main_image "Light Purple African Daisy", chooses a category of electronic products from a dropdown list and then clicks the "Design Your Own Gifts" button which opens a new window, connects to the Zazzle marketplace and displays a grid of electronic products showing the "Light Purple African Daisy" image on the user's chosen products.
The URL behind the "Design Your Own Gifts" button needs to be created dynamically with the selected value after the user chooses a category of products from a dropdown list on my website.
This is the Zazzle API I need to use:
https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg= <DYNAMIC CATEGORY ID FROM DROPDOWN SELECTION LIST> &t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid= <URLENCODED DYNAMIC PATH OF ACTIVE PAGE MAIN_IMAGE>"
I have created 2 tables in mysql database that hold the Names, Category IDs and Department IDs for the products in my Zazzle marketplace. I am also getting the main_image path from my j2store productimages table.
The code I have been able to write so far accomplishes the following tasks:
Connect to the database
Choose Columns/Tables
GET Data from Columns/Tables
Create HTML Form to Display Result of MYSQL Query
Create Dropdown Selection List of Query Results
Echo encoded URL with Zazzle API concatenated with Parameters/Dynamic Values
This is my code so far:
<div class="form-group" style="margin: 30px 10%;">
<h3>Create Zazzle Products</h3><p><h4>Select a Template Category</h4>
<form name="create-zproducts" id="create-zproducts" action="create-zproduct.php" method="POST">
<?php
//connection
$con = mysqli_connect('localhost', 'user', 'password', 'database');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT * FROM david_cim_template_categories, david_j2store_productimages";
$cg = $_GET['cim_template_cg'];
$coverimage_iid = $_GET['main_image'];
$result = mysqli_query($con,$sql);
?>
<select name="selectZcategories" id="selectZcategories">
<?php
while($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['cim_template_cg'].':'.$row['cim_template_cgname']'">'.$row['cim_template_cgname'].'</option>';
}
?>
</select>
<button onclick="ajaxFunction();">Submit</button><br /><br />
<?php
<script>
function ajaxFunction() {
var selectedData=$("#selectZcategories option:selected").val();
$.ajax({
type : "POST",
url: "select_zproduct.php",
data: { selection : selectedData },
success: function (html) {
//Success handling
}
})
}
</script>
?>
<?php
echo $ZAPI = "https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg=";
echo $cg = ['cim_template_cg'];
echo $ZPARAM = "&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid=https%3A%2F%2Fwww.capturedimagesofmaine.com%2Fimages%2Fproducts%2Foriginal%2F";
echo $coverimage_iid = ['main_image'];
echo $product_text = "&t_text1_txt=Welcome";
?>
</form>
</div>
// new file (select_zproduct.php) added to same path as create_zproduct.php
// contents of select_zproduct.php below:
<?php
if( isset($_POST['selection']) )
{
$selecterData=$_POST['selection'];
$selecterArrayData=explode(':', $selecterData);
$cg=$selecterArrayData[0];
$coverimage_iid=$selecterArrayData[1];
$url='https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg='.$cg.'&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid='.$coverimage_iid.'';
?>
<script>
window.location.href=<?php echo $url; ?>;
</script>
<?php
}
?>
The code above is just the beginning of what I've been able to write by myself so far.
My obstacle at the moment is not being able to make the " cg= " parameter display the numeric value of $cg= which was selected by the user from the dropdown list. The current code returns the word "Array" in the URL instead of the selected value. (eg. cg=Array instead of cg=196215449301144739)
I believe I need to use AJAX and Javascript to accomplish this action but I don't know enough to write it by myself yet.
The Code I Need to Write will accomplish the following tasks:
Assign proper $variables to URL fragments ($ZAPI, $cg, etc) to be used for concatenation
Assign proper $variables to database dropdown SELECTION Result to be used in the URL above
Concatenate all $variables
Parse all $variables
Embed final encoded URL into button
Use thumbnail of active page main_image as button image src
What I need to know right now is how do I insert the numeric value of 'cim_template_cg' into the " cg= " parameter in the final URL so the final URL will output " &cg=196215449301144739 " when the user selects the 'cim_template_cgname' associated with that cg=.
Once I see the solution I can apply it to the other dynamic values I need to create. I've only written one javascript code with help from a snippet so any AJAX or Javascript code that needs to be written will need to be shown to me in an example and describing related files, please.
Thanks for your help in advance!
So if I understood your question properly, you have the necessary data to achieve this, i.e. you have the URL path and ID from the database, as well as the URL string, which needs these database values dynamically added upon selection?
And to answer one of your questions, yes this can be done via AJAX if you wish for the PHP logic to be handled in a seperate file.
What you could do, is concatenate your URL path and ID from the database with a seperator value that you could perform an explode(); on to get the values.
so, your <select> would look something like this instead:
<select name="selectZcategories" id="zCategories">
<?php
while($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['cim_template_cg'].':'.$row['cim_template_cgname'].'">'.$row['cim_template_cgname'].'</option>';
}
?>
</select>
Now to the AJAX function. Personally, I use the jQuery library, simply because it makes things easy and simple. It simplifies a lot of the code, so I am going to go by the jQuery standards in my AJAX example. If you wish to use jQuery AJAX to achieve the same results, you will need to install jQuery into a library that you include like any other normal JS/CSS file etc.
function ajaxFunction() {
var selectedData=$("#zCategories option:selected").val();
$.ajax({
type : "POST",
url: "/path/to/file.php",
data: { selection : selectedData },
success: function (html) {
//Success handling
}
})
}
What this achieves, is that the function will take the selected value of the <select> and parse the data to another file using the POST method. You are able to do a lot of things in the success function if you so desire, but for our purpose, I'll simply perform the redirect in the PHP file.
When the data has been parsed to the other file, you then perform an explode(); on the value to split it up into our two variables that we will parse along in our URL.
The PHP file could look something like this:
<?php
if( isset($_POST['selection']) )
{
$selecterData=$_POST['selection'];
$selecterArrayData=explode(':', $selecterData);
$categoryID=$selecterArrayData[0];
$imagePath=$selecterArrayData[1];
$url='https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg='.$categoryID.'&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid='.$imagePath.'';
?>
<script>
window.location.href=<?php echo $url; ?>;
</script>
<?php
}
?>
How you call the AJAX function initially is up to you. It could be via a button for instance.
<button onclick="ajaxFunction();">Submit</button>
Hope this helped, or pointed you towards the right direction.
For tests as per request by your comment,
Ajax for test:
function ajaxFunction() {
var selectedData=$("#zCategories option:selected").val();
$.ajax({
type : "POST",
url: "/path/to/file.php",
data: { selection : selectedData },
success: function (html) {
//Success handling
alert(html);
}
})
}
PHP:
<?php
if( isset($_POST['selection']) )
{
$selecterData=$_POST['selection'];
$selecterArrayData=explode(':', $selecterData);
$categoryID=$selecterArrayData[0];
$imagePath=$selecterArrayData[1];
$url='https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg='.$categoryID.'&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid='.$imagePath.'';
echo 'cg: '.$categoryID.' img path: '.$imagePath;
?>
<script>
//window.location.href=<?php echo $url; ?>;
</script>
<?php
}
?>
I contacted the developer of J2Store for help with getting the main_image value from the active J2Store product page and embedding my final API URL into my J2Store product pages so he rewrote my code to integrate error-free with both Joomla and J2Store, as follows:
<?php
/**
* #package J2Store
* #copyright Copyright (c)2014-17 Ramesh Elamathi / J2Store.org
* #license GNU GPL v3 or later
*
* Bootstrap 2 layout of product detail
*/
// No direct access
defined('_JEXEC') or die;
$db = JFactory::getDbo();
$query = $db->getQuery(true)->select('*')->from('#__cim_template_categories');
$db->setQuery($query);
$cg_values = $db->loadObjectList();
$image_path = JUri::root();
$main_image = $image_path.$this->product->main_image;
//$zazzle_api = 'https://www.zazzle.com/api/create/at-238500395169782226';
$zazzle_api = 'https://www.zazzle.com/api/create/at-238500395169782226';
?>
<?php if(count($cg_values)): ?>
<div class="cg_values">
<form method="get" class="zazzle_api_form" action="<?php echo $zazzle_api; ?>">
<select name="cg" class="cg">
<?php foreach($cg_values as $cg_value): ?>
<option value="<?php echo $cg_value->cim_template_cg; ?>">
<?php echo $cg_value->cim_template_cgname; ?>
</option>
<?php endforeach; ?>
</select>
<input type="hidden" name="rf" value="238500395169782226" />
<input type="hidden" name="ax" value="DesignBlast" />
<input type="hidden" name="sr" value="250508120301240636" />
<input type="hidden" name="t__useQpc" value="false" />
<input type="hidden" name="ed" value="true" />
<input type="hidden" name="t__smart" value="false" />
<input type="hidden" name="continueUrl" value="<?php echo urlencode('https://www.zazzle.com?www.capturedimagesmaine.com'); ?>" />
<input type="hidden" name="tc" value="" />
<input type="hidden" name="ic" value="" />
<input type="hidden" name="t_text1_txt" value="" />
<input type="hidden" name="t_coverimage_iid" value="<?php echo $main_image; ?>"
/>
<input class="btn btn-primary" type="submit" value="Create Your Own Custom Gifts"
/>
</form>
</div>
<?php endif; ?>
In my code, I am retrieving data from the database using a while loop so i can have all the $FormData['fullname'] in the db.
What i want to do is, have each name display on the page and also have clickable so when someone clicks a name, it gets their user_id and pulls up information about them.
The problem i am having is that I can't figure out a way to make a it so where i can get the user_id when the user clicks a name. I tried putting a "name" in the button attribute and I checked if isset() but that didn't work.
If someone can properly figure out a way for me to basically, display all the fullnames in my database and when someone clicks a name, it pulls up information about them that is stored in the database. Here is my code
$stmtGet = $handler->prepare("SELECT * FROM formdata");
$stmtGet->execute();
while($formData = $stmtGet->fetch()){
echo "<button name='name'>$formData[fullname]</button>";
if($_SERVER['REQUEST_METHOD'] =="POST"){
if(isset($_POST['name'])){
echo "ok";
}else{
echo "bad";
}
}
}
As far i can see you are trying hit a button inside the while loop , i would not say its a bad approach , but i will suggest you not to do that . and from your code i can see you have lack of understanding post and get request learn from here . and other than this you need to know the transition of web url . how its actually works . anyway , i have given a sample code without . i hope it will help you understanding this concept.
$stmtGet = $handler->prepare("SELECT * FROM formdata");
$stmtGet->execute();
while($formData = $stmtGet->fetch(PDO::FETCH_ASSOC)){
$id = $formData['formdataid'];
echo "<a href='somepagename.php?infoid={$id}'>". $formData['fullname']."</a></br>";
}
now in the somepagename.php file or in the same page you can actually show the details information for instance
if(isset($_GET['infoid'])){
$stmt = $handler->prepare("select * from formdata where formdataid='"$_GET['infoid']"'");
$qry = $stmt->execute();
$row = $qry->fetch(PDO::FETCH_ASSOC);
echo "<p>id =".$row['formdataid']."</p></br>";
echo "<p>id =".$row['name']."</p></br>";
echo "<p>id =".$row['email']."</p></br>";
echo "<p>id =".$row['address']."</p></br>";
code is not executed , it may have semicolon or comma error warning . you have to fix those on your own . this example above shown you only the way it works .
if still you have problem ask , or see the documentation
I should stress that this is not production code and you should totally validate the data input coming in before posting queries to your DB. You can do something like this.
<?php
// Connect
$connection = mysqli_connect('localhost', 'username', 'password', 'database','port');
// Grab all users
$sql = 'SELECT * FROM users';
$users = mysqli_query($connection, $sql);
if (($_SERVER['REQUEST_METHOD'] == 'POST') && !empty($_POST['user_id'])) {
$query = "SELECT * FROM users WHERE user_id = {$_POST['user_id']};";
$user = mysqli_fetch_assoc(mysqli_query($connection, $query));
}
?>
// This only runs if our $user variable is set.
<?php if (isset($user)) : ?>
<?php foreach ($user as $key => $value) : ?>
<span><?= print_r($value) ?></span>
<?php endforeach; ?>
<?php endif; ?>
// Display all users in a dropdown and when the button is clicked
// submit it via post to this page.
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
<select name="user_id">
<?php foreach ($users as $user) : ?>
<option value="<?= $user['user_id'] ?>"><?= $user['name'] ?></option>
<?php endforeach; ?>
</select>
<button type="submit">Submit</button>
</form>
This is going to refresh your page every time. If you want to have an interactive page you are going to need to use JavaScript/AJAX to update the page elements without reloading the page. This example just demonstrates how you can achieve this with PHP and HTML.
you need to know about server-side language(php) and client-side language(javascript).
php runs before page loaded. it cannot runs when click something by itself(with ajax, it can).
most interactions without page move runs with javascript.
in your case, there are two methods.
store all information into hidden input or button's attribute. and get them by user_id via javascript.
use ajax to call another php that can select informations you need by user_id.
both use javascript or jquery. so you must learn about them.
I am creating a page that allows a user to edit a user. The table gives me the row ID which is in the button shown below. It works fine when having it direct to another script. However, I wanted to open the users details dynamically which this program does.
Although I don't understand where to place the $row to have the page be able to access it? My research was more about just passing between both programs when I just need to link it up.
I just want this to when the button is pressed, send the $row['usersid'] variable to the page which I can then use.
EDIT: It seems I've confused both myself and you all. I want to keep this in PHP if possible. All I need is the $row['usersid'] or a variable that stores it which is in PHP currently. To be sent to the page without it refreshing.
echo "<td><a href='javascript:void(0);' onClick=".$row['usersid']."' id='showButton'><span class='glyphicon glyphicon-edit'></span></a></td>";
echo "<td><a href='javascript:void(0);'".$row['usersid']."' id='showButton'><span class='glyphicon glyphicon-edit'></span></a></td>";
There are many ways to pass the information in page to another one, let me list some of them:
approach
echo "<td><a href='/path_to_another_php_page.php?userId=$row['usersid']' onClick= id='showButton'><span class='glyphicon glyphicon-edit'></span></a></td>";
then you can access to this information searching in $_GET['userId'].
If your want to use this userId, only for make ajax request, you could do simply doing:
echo "<td><a href='javascript:void(0);' data-user-id='$row['usersid']' onClick= id='showButton'><span class='glyphicon glyphicon-edit'></span></a></td>";
as you can see I added a data-user-id attribute that contains the real userId from php, so in your Javascript you can do this:
document.getElementById("showButton").addEventListener("click", function(){
var userId = this.getAttribute("data-user-id");
// here you can call your ajax ...
}, false);
I hope this be useful for you.
if you want to check your value then use this code which you get your value
you can also get data using this code
<?php
$row['usersid'] = 10; // fot test case
$row['usersid1'] = 13; // fot test case
?>
<script type="text/javascript">
$(document).on('click', '.getValue', function(){
// send data to PHP
var id = this.getAttribute("userId");
alert(id)
});
</script>
<?php
echo "<td><a href='javascript:void(0);' class = 'getValue' userId = ".$row['usersid']." id='showButton'>Button</a></td>";
echo "<br>";
echo "<td><a href='javascript:void(0);' class = 'getValue' userId = ".$row['usersid1']." id='showButton'>Button</a></td>";
this is second option
<script type="text/javascript">
function getValue(value){
alert(value)
}
</script>
<?php
echo "<td><a href='javascript:void(0);' onClick=getValue(".$row['usersid'].") id='showButton'>Button</a></td>";
Thanks for taking the time to look at this post.
So I have managed to do my task to a point.
I am pulling data from a database called posts with the following fields: id, account_name, data, heading, subheading, videos, voice_notes, music, images, post_date, date_for_post.
So This is the process:
1 - Pull data from db and put into array
2 - Make unordered list from array with links
3 - when link is clicked, fill content div with that posts data.
Now it will load the specific posts data on odd numbered links, but on even numbered links it wont load the data into the container? using the same method? I have re-ordered the lists and still, even numbered list items just wont work. Am I doing something wrong?
I have also tried putting in a blank list item in between the posts to see if it were the list items themselves that were not calling the function, but it seems that it is only the even links.
I don't know how else to explain it, here is my code:
<?php
$connection=mysql_connect('localhost', 'username', 'password');
if (!$connection) { die('Not connected : ' . mysql_error());}
// Set the active MySQL database
$db_selected = mysql_select_db('dbname', $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
$query = "SELECT * FROM posts";
$result = mysql_query($query);
if(!$result){
die('Invalid query' . mysql_error());
}
$posts = array();
while($line = mysql_fetch_array($result, MYSQL_ASSOC)){
$posts[] = $line;
}
?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="js/ajax.js"></script>
<script type="text/javascript" src="js/content.js"></script>
</head>
<body>
<div id="content">some data</div>
<div id="links">
<ul>
<?php
foreach ($posts as $post) {
$data = "'".$post['data']."'";
echo '<li>'. $post['date_for_post'] .'</li>';
}
?>
</ul>
</div>
</body>
and the getContent function:
function getContent(element, data){
$(element).text(data);
}
I cannot figure out why. here is a graphical representation of whats happening:
I have tried inserting black list items to see if it was the actual even list items not calling the function, but it is the even list items with the content inside that wont work, if that makes sense?
Please help as I have no clue what is going on and how to fix it.
Thanks in advance!
UPDATE
it seems to be that the longer posts dont display, the shorter do. I have the data type in the database set to text, not varchar. So where is the issue with size? Is there a maximum size I am allowed to put through the JQuery function? Or in the database? Because it shows in the database, but not on the post
I think the problem is with quotes and double quotes here in your code:
$data = "'".$post['data']."'";
echo '<li>'.$post['date_for_post'] .'</li>';
Check the source of generated HTML page. There should be incorrect 'li' tags. I suggest change your code to this:
$data = $post['data'];
echo '<li>'.$post['date_for_post'] .'</li>';
Hope it helps.
Also, check if the quotes in text from database are causing this problem.
It's hard to see what's going on, try to provide a jsfiddle. Even though you are using php, you can create a manual feed of json data and test out the javascript. To make it less confusing, have the data stored in a ...
<script>
$(document).ready(function () {
var dbObj = <?php $post ?> // $post object to be formatted in json
var render;
for (obj in dbObj) {
render = render + '<li><a href="#" onclick=getContent("#content", ' + obj.data + '");>' +obj.date+ '</a></li>'
$('#links ul').append(render);
});
</script>
If that works and you really want to have the php print out the list, then you can replace it with the php foreach; these days, developers are allowing the client-side to render templates/html and at least you'll know the js works this way! :-)
<?php
foreach ($posts as $post) {
echo '<li><a href="#" onclick=getContent("#content", "'. $post["data"] .'");>'. $post['date_for_post'] .'</a></li>';
}
?>
I don't know if this is possible so I'm very open to trying other methods to achieve similar results.
Basically I have a website and a certain div
<div id="mainContent">Content here...</div>
What I want to do with this, is be able to send an email to a certain address or something similar and the body of the email will define the "innerHTML" of this div.
I can imagine it would look something like this in Javascript:
document.getElementbyId("mainConetent").innerHTML = emailBody;
With obviously "emailBody" being a pre-defined variable.
I am almost certain nothing like this could work but is there any way to achieve a similar thing?
I also know that 'innerHTML' in javascript becomes restored when a page is refreshed. I would like it to be there permenantly on the original document, until a new email is recieved with the new content. This method with javascript is probably not the way to do is. I just used it to explain bettter
Store email body in input hidden field and then using javascript you can retrieve them based on id and store them in respective div.Try this:
html:
<div id="mainContent">Content here...</div>
<input type="hidden" value="<?php echo $inputbody;?>" id="emailbody">
javascript:
var emailBody = document.getElementbyId("emailbody").value;
document.getElementbyId("mainContent").innerHTML = emailBody;
Updated Example:
<?php
$to = "someone#example.com";
$subject = "Test mail";
$inputbody = "Hello! This is a simple email message."; // insert this into hidden field
$from = "someonelse#example.com";
$headers = "From:" . $from;
?>
In your index.php file add the following piece of code for database connection
<?php
// Create connection
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_fetch_array(mysqli_query($con,"SELECT * FROM table_name Where type='mail'"));
//Inside your mainContent div
<div id="mainContent"><?php echo $result['innerhtml'] ?></div>
?>
In your js file
If your email is being sent on button click perform this
$('#button').on('click',function(){
emailBody = document.getElementbyId("mainConetent").innerHTML;
$.ajax({
type: "POST",
url: "update_mail content.php",
data: "emailBody="+ emailBody,
success: function(){
}
});
})
//Updates the content in the databse table usinganother php file named update_mail content.php .This flow might help u mate.. :)