I have built a calendar appointment script and want to display the results for any given day on a google map and a table below without having to refresh the whole page. Currently, using ajax, the map refreshes perfectly but the table doesn't.
When the date is clicked in the calendar it is written via javascript to a hidden form field, then when the update button (submit) is clicked, ajax in the head submits the form in the background to overwrite the $updatedate variable, refresh the map div and the table div.
Currently the variable gets updated in the session, a script runs to update an xml file and the calendar successfully refreshes showing this xml data. However the table div does not refresh. If I manually refresh the whole page the new results are shown successfully so it is picking up the updated variable but not refreshing via the ajax.
I realise this is probably due to ajax being client side and php server side so the php queries are not being ran but I have also tried to use file_get_contents (which works for the xml generating script) inside the div to run these queries without loading the whole page but this just shows nothing so I think I'm missing something fundamental and possibly very simple!
--------- ajax in head to run update script and reload divs --------
<!-- silently submit the updatedate form to update the session variable.
Then reload the map and table divs using this new variable -->
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('#update').on('submit', function (e) {
// stop the page from reloading
e.preventDefault();
// but submit the form
$.ajax({
type: 'post',
url: 'actions/updatedate.php',
data: $('#update').serialize(),
success: function () {
$("#map-outer").load("../map.php");
$("#tbl-outer").load("../table.php");
}
});
});
});
</script>
--------- main page --------
<div>calendar content here</div>
<div>customer details form here</div>
<div class="clear" style="text-align: left;">
<!-- set default then let script overwrite -->
<?php $updatedate = date('Y-m-d'); ?>
<!-- run form (via ajax in head) to update variable and write to session -->
<form id="update" method="post">
<input type="hidden" name="updatedate" id="updatedate" />
<input type="submit" name="submit" value="update map and table" />
</form>
<!-- update variable form session -->
<?php $updatedate = $_SESSION['updatedate']; ?>
<br />
</div>
<div id="map-outer" class="twocol1">
<?php include "../map.php" ?> <!-- this page runs a script to pull the db values and write them to xml, then displays google map code -->
<br /><br />
</div>
<div id="tbl-outer" class="twocol2">
<?php include "../table.php" ?> <!-- this page pulls the db values and display them in a table -->
</div>
--------- map.php page --------
<?php
// silently run the db to xml script before loading the map //
file_get_contents("admin/actions/dbtoxml.php");
?>
<div id="map"></div>
<script> ..... script to show google map with custom markers ..... </script>
--------- table.php page --------
<h2>Morning</h2>
<?php
$sql = "SELECT * FROM wasps_appointments WHERE date = '$updatedate' AND time = 'Morning' AND block = 0 AND completed = 0 ORDER BY date ASC";
$result = $connection->query($sql);
?>
<?php include 'admin/includes/view-table-today.php'; ?>
<br /><br />
<h2>Afternoon</h2>
<?php
$sql = "SELECT * FROM wasps_appointments WHERE date = '$updatedate' AND time = 'Afternoon' AND block = 0 AND completed = 0 ORDER BY date ASC";
$result = $connection->query($sql);
?>
<?php include 'admin/includes/view-table-today.php'; ?>
Can anyone point me in the right direction?
Many thanks, Helen
I have fixed this now. The table.php page wasn't loading using the existing mysql db connection so I had to use a different one.
Can anyone tell me the difference between using
$connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
and
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASS);
$db_selected = mysqli_select_db($connection, DB_NAME);
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; ?>
I understand that for a login / register system to work within Phonegap, you have to use aJax with your php. I've got a sucessful php login and register page working but I'm unsure where to begin with jQuery / aJax a.k.a where I'm meant to put it, and what exactly I should be putting in. I was wondering if someone would know how to point me into the right direction.
jQuery
jQuery is a framework built on Javascript. Javascript is a client-side (browser) language . It runs on your device, unlike PHP that gets executed on the server.
You need to include jQuery in the HTML of your login page using script tags:
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
jQuery provides a way to target any html element within your document and perform certain functions on that element. You specify what element by using the following syntax:
$(element).doSomething();
You can select classes or IDs:
<p id="myparagraph">A paragraph of text</p>
<p class="myparagraphclass">A paragraph of text</p>
$('#myparagraph').doSomething();
$('.myparagraphclass').doSomething();
AJAX
AJAX is a method introduced with Javascript that allows a page to request another url along with the result of that request. You will need to use AJAX login with Cordova/Phonegap because the "app" you're building is based on Javascript.
Thankfully, jQuery provides some really nice and easy to use AJAX methods.
Putting it together
I notice from a previous question that you have already created a PHP script that checks the login credentials are correct. Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in /public_html/access/login.php on line 15
I have edited slightly the code within that question (/access/login.php):
require_once($_SERVER['DOCUMENT_ROOT'] . "/html5up-aerial/access/functions.php");
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if ($username&&$password) {
session_start();
require_once($_SERVER['DOCUMENT ROOT'] . "db_connect.php");
mysqli_select_db($db_server, $db_database) or
die("Couldn't find db");
$username = clean_string($db_server, $username);
$password = clean_string($db_server, $password);
$query = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query($db_server, $query);
*if($row = mysqli_fetch_array($result)){*
$db_username = $row['username'];
$db_password = $row['password'];
if($username==$db_username&&salt($password)==$db_password){
$_SESSION['username']=$username;
$_SESSION['logged']="logged";
//header('Location: home.php'); // Have commented this out
$message = "YOU ARE NOW LOGGED IN!"; // <- ADDED THIS
}else{
$message = "<h1>Incorrect password!</h1>";
}
}else{
$message = "<h1>That user does not exist!</h1>" .
"Please <a href='index.php'>try again</a>";
}
mysqli_free_result($result);
require_once("db_close.php");
}else{
$message = "<h1>Please enter a valid username/password</h1>";
}
//header/footer only required if submitting to a seperate page
echo $message; // ADDED THIS
die(); // ADDED THIS
This will be the PHP script that AJAX requests.
Now we create the HTML document with a login form and include jQuery and write our ajax code:
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<form class="login-form" method="post">
Username: <input name="username" /><br />
Password: <input name="password" type="password" /><br />
<input type="submit" value="Login" />
</form>
<script>
$('.login-form').on('submit', function(e) { // Listen for submit
e.preventDefault(); // Don't actually submit the form
var data = $(this); // Put the form in a variable
$.ajax({
type: "POST",
url: '/access/login.php',
data: $(data).serialize(), // Make form data into correct format
success: function(response) {
alert(response); // Alert with the response from /access/login.php
}
});
});
</script>
To debug this code you will need to use Chrome development toolbar or Firefox Firebug. Hope this helps.
I have a simple HTML5 login page that requests a username and a password. The information is passed via POST to PHP for comparison with data in MySQL. I am trying to echo a simple "YES" if data was successfully validated and a "NO" otherwise. I want to take the text value of the response and manipulate it using Javascript. Everything seems to be working properly, but when the $response variable is echoed it is shown by itself on a blank HTML document and the JavaScript never gets executed. Following is the code I am using :
<ul>
<li>
<form action="login_submit.php" id="loginTest" method="post">
<span class="un"><i class="fa fa-user"></i></span><input type="text" id="maindata_email" name="maindata_email" value="" maxlength="40" required class="text" placeholder="Usuario"/></li>
<li>
<span class="un"><i class="fa fa-lock"></i></span><input type="password" id="maindata_password" name="maindata_password" value="" maxlength="10" required class="text" placeholder="Password"/></li>
<li>
<input type="hidden" name="form_token" value="<?php echo $form_token; ?>">
<div class="up">
<input type="submit" id ='ingresar' value="ingresar" class="btn">
<!--window.alert(5 + 6);-->
</form>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript">
var myData = <?php echo json_encode($response); ?>;
window.alert(myData);
if (myData == "YES") {
alert("Usuario aceptado!");
var href = 'http://index2.html';
window.location=href;
} else {
alert("Usuario invalido!");
var href = 'http://index.html';
window.location=href;
}
</script>
<input type="submit" id = 'editar' value="editar" class="btn">
</form>
</div>
</li>
</ul>
And here is the PHP section :
/*** bind the parameters ***/
$stmt->bindParam(':maindata_email', $maindata_email, PDO::PARAM_STR);
$stmt->bindParam(':maindata_password', $maindata_password, PDO::PARAM_STR, 40);
/*** execute the prepared statement ***/
$stmt->execute();
/*** check for a result ***/
$user_id = $stmt->fetchColumn();
/*** if we have no result then fail boat ***/
if ($user_id == false)
{
echo $response = "NO";
}
/*** if we do have a result, all is well ***/
else
{
/*** set the session user_id variable ***/
$_SESSION['user_id'] = $user_id;
/*** tell the user we are logged in ***/
echo $response = "YES";
}
}
catch(Exception $e)
{
/*** if we are here, something has gone wrong with the database ***/
$message = 'No se puede procesar su ingreso. Favor de intentar mas tarde.'."<br />\r\n";
}
}
After I click on ingresar in the HTML the username and password are properly sent and received by PHP, the information is properly processed and compared to the values contained in the MySQL database and I get the proper response upon validation. Could anyone please explain why I get the blank page with the $response and the JavaScript code is never executed??? Thanx
Your code seems to be behaving as expected. Your form, upon submission makes a POST request to the servar at login_submit.php, and the browser displays the response from the server, which is where you've echoed the value of $response. There is no javascript or HTML printed on the PHP page, so no javascript is going to be run, and no HTML is going to be displayed... the browser is merely displaying the raw contents of the POST response from the form action since it's just interpreting it as a text response with no markup.
Now, what you're actually wanting is to get the data from the response on a web-page and run some javascript using that response data. There are a couple ways you could tackle this problem:
Avoid a page reload by using AJAX techniques to asynchronously request data back from the server through login_submit.php. When the data arrives back from the server after some indeterminate period of time, a javascript callback is called on the page which involves an action on the incoming response data.
Your login_submit.php page prints a full HTML page with the javascript embedded on that page, and you populate the variables in the resulting javascript from the PHP code that runs the MySQL query.
Take a page from ASP.NET forms and POST back to the page itself rather than a separate page, and use PHP to detect when a POST-back has taken place. So all the code for the form, MySQL query, etc. exists in the same PHP document, and you POST to the page itself. When the page reloads from the POST, it will populate the necessary javascript variables on the page with the correctly values.
When update button is submitted a function edit_page() is called. This function alter the database table row with new data entered.
This works fine table altered correctly entries are ok.
But problem is that when update button is submitted
1. Entries is database inserted or altered correctly.
2. But when page reloads content of this updated page remains as it is as previous or like before updation on front end or just after submission.
My code:
<?php
function edit_page()
{
add_cat();
global $page_id;
?>
<?php
if (isset($_GET['page_action']) && ($_GET['page_action'] == 'edit'))
{
$page_id = $_GET['post'];
}
?>
<?php
$page_id = $_GET['post'];
$result = mysql_query("SELECT * FROM pages WHERE page_id = '$page_id'"); //execute the SQL query and return records
$row = mysql_fetch_array($result);
$page_title = $row['page_title'];
$page_content = $row['page_content'];
?>
<form method="post" action="" name="edit_page" class="edit_page">
<h4>Page Title:</h4> <input type="text" name="title" class="title" placeholder="Add title of the Page" required value="<?php echo $page_title;?>"/><br/>
<h4>Page Content:</h4><br/>
<textarea cols="80" id="content" name="content" rows="10"><?php echo $page_content;?></textarea>
<input type="hidden" name="page_edits" value="yes" />
<input type="submit" name="edit_page" class="button" value="Update"/>
<?php
save_edits(); }
function save_edits()
{
if (isset($_POST['edit_page']) && $_POST['page_edits'])
{
$page_id = $_GET['post'];
$page_id = $_GET['post'];
$page_title = $_POST['title'];
$page_content = $_POST['content'];
$date = date('Y-m-d h:i');
$query = "UPDATE pages SET page_title='$page_title', page_content='$page_content', date_gmt='$date' WHERE page_id = '$page_id'";
$result = mysql_query($query) or die("Unable to create Page: " . mysql_error());
}
}
?>
<div class="right_sidebar">
<?php edit_page();?></div>
Finally, my mean is that i just want functionality like wordpress in which when update button is clicked just after that we see updated data.
You're doing PHP the procedural way here. That means the statements are executed one after another so the problem lies in the way you place your statements.
In your code, you are displaying the form first and only then updating it, so that's why the previous values get fetched although update is happening only later.
Solution: The function save_edits() and its call should come first followed by edit_page().
Another important thing in terms of security, you are directly inserting the value you get from the address bar. Right now the way it is, someone can drop your whole table by writing in a piece of code. You could use mysql_real_escape_string() to prevent it (although not totally) or better yet:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Lastly, you are not closing your <form> tag.
I am trying to understand the process of implementing AJAX Query into my CodeIgniter application. The goal is to a have a clickable division (button) in a view. When this div is clicked the AJAX query is called and retrieves 5 movies from my DB and displays them in the view. Right now I have a main page with search button, this search button orders my DB by ID and then retrieves the 1st 5 movies from the DB and displays them on a new page. The function I am trying to implement should retrieve the next 5 movies and replace the 1st 5 movies without reloading the page.
Below is all the code I assume you should take a look at, due to its necessity. Under each part of the code a short summary is provided. And at the end I try to explain what I don't understand and what I am asking you to help with.
Main Page - Controller xampInstallFolder/htdocs/application/obs/controllers/main.php
public function generate_suggestions() {
$this->db->order_by("id","desc");
$pages = $this->db->query('SELECT * FROM movies LIMIT 5');
$data['pages'] = $pages;
$this->load->view('results_v', $data);
}
This function is called when my Search button on the main page is clicked. Right now it doesn't accept any criteria for the query it only retrieves the first 5 movies in the db. Then I take the movies and store them in the pages array and load the new view with the array provided in data
Results Page - View *xampInstallFolder/htdocs/application/obs/views/results_v*
<div id="listA">
<table>
<!-- Function that splits the array in $pages into the first 5 movie suggestions -->
<?php foreach ($pages->result() as $row): ?>
<a style="display:block" href="<?php echo base_url('core/detail/'.$row->id) ?>">
<div id="suggested" onmouseover="" style="cursor: pointer;">
<div id="info">
<p><b><?php echo $row->name ?></b></p>
</div>
<div class="details">
<p><?php echo $row->summary ?></p>
</div>
</div
</a>
<?php endforeach; ?>
</table>
</div>
<div id="next_btn" style="display: block;">
<p>Click here to display next 5 movies</p>
</div>
I have a div listA where I display the 5 movies using a for each loop on the pages array. I have much more div and information, but I was trying to keep it simple.
Javascript xampInstallFolder/htdocs/ASSETS/obs/js/myscripts.js
$( "#next_btn" ).click(function() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("listA").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getnext5.php?q="true);
xmlhttp.send();
});
In the head of my results view I link the javascript with this function. It triggers when the next_btndiv is clicked. I got the code from w3schools and from what I understood you need to provide the element in which the result is displayed (listA) and the file where the query is stored (getnext5.php)
getnext5.php Where do I put this file?
$con = mysqli_connect('localhost','root','root','obs2');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"obs2");
$sql="SELECT * FROM user WHERE id > 5";
$result = mysqli_query($con,$sql);
echo "<table>";
while($row = mysqli_fetch_array($result))
{
<a style="display:block" href="<?php echo base_url('core/detail/'.$row->id) ?>">
<div id="suggested" onmouseover="" style="cursor: pointer;">
<div id="info">
<p><b><?php echo $row->name ?></b></p>
</div>
<div class="details">
<p><?php echo $row->summary ?></p>
</div>
</div
}
echo "</table>";
Here is the core function. I tried to adjust the code from w3schools, but I am not sure if it is correct. My DB is called obs2, but I am not sure if I should have it in both mysqli_connect and mysqli_select_db statements. I also know that I have to figure out how to make it always load the next 5 movies in the list, but right now I just force it on id>5. And then I have the style for the $result. I think the table and `while loop are coded properly, but I don't know how to turn the divs, anchors and original php echoes into the same syntax.
If you made this is far thank you very much for reading through. I'd say the only part I need help with is the getnext5.php. Mostly the syntax. And location, where should the getnext5.php file be stored? I don not think that the other parts of the code are wrong. But obviously if you spot anything in there please let me know as well. Again thanks for reading. I'm looking forward to your replies. If you'd need any other information just ask for it Ill add it.
I only read through the last script, and I corrected some mistakes you made. You can put that file anywhere pretty much. You can copy the code and paste it into a controller class or a views page.
<?php // I just decided to start here
mysqli_select_db($con,"obs2");
$sql="SELECT * FROM user WHERE id > 5"; # This is an integer, no quotes necessary.
$result = mysqli_query($con,$sql);
echo "<table>";
while($row = mysqli_fetch_array($result))
{
?> <!-- Note how we stop php right before we start printing html, since you have nested php tags throughout this block of markup -->
<a style="display:block" href="<?=base_url('core/detail/'.$row->id)?>">
<div id="suggested" onmouseover="" style="cursor: pointer;">
<div id="info">
<p><b><?=$row->name?></b></p>
</div>
<div class="details">
<p><?=$row->summary?></p> <!-- Protip, you may use <? and ?> instead of <?php and ?>. You may also use <?= as a shortcut to the "echo" function -->
</div>
</div>
<?php
} // We are opening up our PHP tags again
echo "</table>";
?>
It seems that you're kindof all over the place with your code. Instead of answering your question specifically, I'm going to give you some advice as to how you can use AJAX with codeigniter much easier. I'm not saying this is the best solution, but it's much more organized and clean that what you have going on. Hopefully it will point you on the right direction.
Let's start from the backend and then move towards the front.
First, a method in a controller which queries the movies in the database. Notice the parameters which allow us to ask for any subset of movies, and not just the first 5. (And yes, I'm only including the important lines of code instead of everything.)
public function generate_suggestions($start = 0, $count = 5) {
$pages = $this->db->query('SELECT * FROM movies LIMIT ' . $start . ',' . $count);
// send back the view as a simple HTML snippet (the <table>, perhaps?)
}
Now we need some Javascript that can call this function on the server. Since the function sends back an HTML snippet, we can just stick that snippet of html code into the page. JQuery makes all of this very easy, so you can avoid the complicated XMLHttpRequest stuff.
<script type="text/javascript">
var nextstart = 6;
var movies_per_page = 5;
$( "#next_btn" ).click(function() {
// this next line makes the ajax call for us, and the inline function
// is called when the response comes back from the server
$.get("controller/generate_suggestions/"+nextstart+"/" + movies_per_page,
function(data) {
// data is what comes back from the ajax call
// here it is the snippet of html, so let's display it as is
$( "#listA" ).html(data);
nextstart += movies_per_page; // so that the next click will load the next group of movies
});
});
</script>
Now we just need to populate the table when the page first loads, and you can do that by calling the same ajax call on page load with a similar $.get ajax call.
Once you understand all of this and have it working, then you should look into JSON, as it is a much better way of transferring data with ajax. And jQuery makes working with JSON much easier, too.