I have a div on my page '.php'
<div id="force_id"></div>
This prints an id for each product on the page. Ex: 126500
How do I assign this value of the other PHP variable (not click, on load for example)
I use it here :
$limit = ?????? (Value should be the id value here. For example 126500)
$plans = mysql_fetch_array(mysql_query("select * from motors WHERE prod_id = '$limit'"));
Thank you in advance ...
If you are looking for something on-load then you will need to use Javascript with some sort of Ajax call.
Your javascript would need to grab the id and then pass that to .php as a POST or GET variable.
However, it would probably be better for you to pass the ID with the page request. So your link to .php would look like this:
<a href='page.php?id=126500'>Link</a>
Obviously you can auto generate these. Then in .php you just get the value from GET:
$limit = $_GET['id']
Then you can use it in your SQL query (you should look at PDO rather than mysql_query to protect yourself from SQL injection hacks).
Some more detail on the GET option.
Your initial HTML for the menu choice of products to look at would look like this:
<h1>Select the Product you want to see</h1>
<ul>
<?php
$result = /* SELECT MY PRODUCT CODES */
foreach($result AS $row){
echo "<li><a href='product.php?id=".$row['id']."'>Product ".$row['name']."</a></li>";
}
?>
</ul>
Then your product.php file would have this:
if(isset($_GET['id'])){
$limit=$_GET['id'];
$plans= /* SELECT FROM MOTORS USING $limit */
foreach($plans AS $row){
echo 'Product name:'.$row['name'];
echo "<img src='".$row['img_path']."' />";
...
}
}else{
echo 'Sorry, unrecognised product';
}
You should do further validation on $_GET['id']; for example check that it is a number and within a range that you would expect for your product_id's
More detail on the POST option using Javascript & JQuery.
If you have a specific reason for wanting to do POST, or for some reason you only want to publish the ID code on the one page then you could do it like this:
In your HTML I would use a data attribute in a div:
<div id='product' data-id='12650'></div>
In Javascript (I've assumed JQuery but the approach would be the same with other libraries) you would add to your 'onload' function (i.e. do this after the page has loaded):
$('#product').each(function(){
var id=$(this).data('id');
$.ajax({
type: 'POST',
url: 'product_content.php',
data: {'id':id},
success: function(msg){
$(this).html(msg);
},
error: function(msg, status,err){
$(this).html("Product not Found");
}
});
});
Finally you need a page to respond to the Ajax call product_content.php :
$limit=$_POST['id'];
/* DO SOME VALIDATION ON $limit HERE OR USE PDO AS PROTECTION */
$plans= /* SELECT FROM MOTORS USING $limit*/
foreach($plans AS $row){
echo 'Product name:'.$row['name'];
echo "<img src='".$row['img_path']."' />";
...
}
I should point out I've not tested this code, so keep an eye out for typo's if you copy it directly.
If you're using form, you can put the div's value inside an input[hidden] inside the form. Something like this:
$('#your_form').on('submit', function(){
your_div = $('#your_div').attr('id');
$('#hidden_field_used_on_form').val(your_div);
return true;
})
Related
I'm currently working on a project in school and I'm trying to use php and sql to create a web front end with a database back end. I have tried to research this thoroughly, but I have had no success. I am trying to click on a link and run an SQL query based on the ID of the link that was clicked.
Code is pastebin'd below:
https://pastebin.com/sH6DXtQU
I believe it is something to do with;
$_Post or $_Get
So essentially I'm trying to click on one of the actors names ad it display all the films they have been in, as you can see at the bottom of the page i have made a very basic attempt at showing the films using actorID form (1-6). If possible without any jQuery but if it is necessary i will use it. Any help will be greatly appreciated.
If you don't want to refresh the page you need an XHR request, AJAX request in Jquery. If you don't want to use Jquery it's fine , there is a way to do it in vanilla Javascript but it's way harder to understand.
const req = new XMLHttpRequest();
req.open('GET', 'http://www.mozilla.org/', false);
req.send(null);
if (req.status === 200) {
console.log("Received: %s", req.responseText);
} else {
console.log("Error: %d (%s)", req.status, req.statusText);
}
for a GET request. I suggest you look at the mozilla website for more documentation
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
So your having a anchor link like the following, on click of that you want all the data of the films they have acted
View Page
<!-- I am assuming that your having $row as actor details, so below you store the actor id in a attribute data-actorid and once the user clicks on the link make sure you call the event ONCLICK -->
<a class="actor_movies" href="#" data-actorid = <?php echo $row['actorid']; ?>>
<?php echo $row['actor_name']; ?>
</a>
/* I am assuming you have jQuery running. As the code I am writing needs jQuery Library */
<script type="javascript">
$(.actor_movies).on('click', function(){
actor_id = $(this).attr('data-actorid');
$.ajax({
'url' : 'actor_movies.php'
'type' : 'POST',
'dataType' : 'JSON',
'data' : {actor_id:actor_id},
success : function(retObj){
/* retObj will have the json encoded code which you can loop and do whatever you want here */
$.each();/* Even you can use for loop as per your convenience. */
}
});
});
</script>
actor_movies.php
/* Include your db connection file */
include_once 'db_connect.php';
/* Check if the connection type is of POST */
if($_SERVER['REQUEST_METHOD'] == 'POST'){
/* filter_input get your input from specified HTTP request and even you can add filter validation and other things to it */
$actor_id = filter_input(INPUT_POST, 'actor_id', FILTER_VALIDATE_INT);
$actor_movies_query = mysqli_query('SELECT * FROM movies WHER actor_id = '.$actor_id);
$actor_movies = array();
if(mysqli_num_rows($actor_movies_query) > 0){
while($actor_movie = mysqli_fetch_assoc($actor_movies_query)){
$actor_movies[] = $actor_movie;
}
}
header('Content-Type: application/json');
echo json_encode(['actor_movies' => $actor_movies]);
}
I have a table containing data read from a MySQL database via PHP. The first column holds all item names. Now, on clicking a td element in the first column of the table would link to a page with more detailed information about the item contained in the td.
Now I came up with the following idea:
$(document).ready(function() {
$('#table td:first-child').click(function() {
$('div.main').animate({
height: "50px"
}, 600);
setTimeout(function() {
$('div.data').fadeIn(1000);
}, 600);
});
});
div.main is the div-container that has the table included. What I want to do now is to slide that container up and fade a new div-container in, right below it, the new container include()s a PHP page which holds a dynamic query (pseudocode, no string escaping, simplified version):
SELECT detail FROM items WHERE items.name = $_GET['name'];
What I couldn't figure out is if and how I can tell the PHP file that is included in the in-fading div-container which item name it has to grab details for, off the database.
Right now I can read the item name via JavaScript/jQuery, but I couldn't figure a way out to pass that value to the PHP file without having to reload the page.
Any ideas or suggestions welcome!
I think what you're looking for is asynchronous JavaScript and XML (AJAX). It sounds intimidating, but fortunately jQuery makes it very easy.
You can call $.ajax() directly, but for most cases, you can use one of the convenience wrappers. In this case, I think $.load() will meet your needs.
So, let's say your PHP file is called detail_ajax.php and it returns the HTML you wish to put in your div (with class data). All you would have to do then is this:
$('div.data').load( '/detail_ajax.php', function(data){
$(this).html(data);
});
If you want to pass data TO detail_ajax.php, you can pass it along this way:
$('div.data').load( '/detail_ajax.php', { 'someField' : 'someValue' },
function(data) {
$(this).html(data);
}
});
In detail_ajax.php, if you examine $_POST['someField'], you will see the value passed in.
You can do this by using ajax. Output your query on a separate page in JSON format then fetch it using jquery ajax
you need to use ajax to do the same thing. create an event like onclick and call a
method on click call ajax set variable in js and pass it to and do as you want,
show data in particular div in response. Hope it will help you.
You are looking for $.ajax(). However, 3 things will need to take place for this to happen as you intend.
First, we need a reference held in the HTML that is generated by the table so we can streamline the server request. When you generate the table, add a unique data-name string to the TD.
<td data-name="<?php echo $row['name']; ?>">
If, for instance, the td's were generated in a foreach loop, where we expect an array to be returned.
Now, we need to detect the request on our page so we can properly return the data to the browser, we'll look for $_GET['name'] as per your example.
<?php
if(isset($_GET['name'])):
$mysqli = new mysqli('host', 'user', 'pass', 'db');
$ret;
if($stmt = $mysqli->prepare('SELECT detail FROM items WHERE items.name = ?')):
$stmt ->bind_param('s', $_GET['name']);
$stmt ->execute();
$stmt ->bind_result($details); // we only want one column
$stmt ->fetch(); //get our row
$ret['success'] = TRUE;
$ret['html'] = '<div>'. $details .'</div>';
else:
$ret['success'] = FALSE;
endif;
echo json_encode($ret); //return to the browser
endif;
?>
Now we need to employ ajax to bridge the gap between the server and the browser.
Edit - I forgot to modify the click function.
$('#table td:first-child').click(function() {
$('div.main').animate({
height:'0px'
}, function(){
//once the animation completes
$.ajax({
url: '/',
type: 'GET', //this is default anyway
data:{name: $(this).data('name')}, //send the name from the td clicked
dataType: 'json', //what we expect back from the server
success: function(data){ //will fire when complete. data is the servers response
if(data.success !== false){
$('div').html(data.html);
$('div.main').animate({
height: "50px"
}, 600);
}else{
alert("Something went wrong");
}
}
});
}, 600);
});
What I want to achieve
I have some works I want to show. So, I have thumbnails of these. When a visitor clicks on a thumbnail, I want a div (called slickbox) to open and show the title, the description and a slider about the work clicked.
What I've already done and how
I get my work's datas from a database. Here is the little part of my listing of works:
index.php
<?php
$retour_messages = mysql_query('SELECT 2K13_works.*, 2K13_categories.nom AS nomCAT FROM 2K13_works, 2K13_categories WHERE 2K13_works.cat_id = 2K13_categories.cat_id ORDER BY 2K13_works.record_date DESC') or die(mysql_error());//requete sql pour récupérer les works de la page
?>
<ul id = "creations" class = "step">
<?php
while($donnees_messages=mysql_fetch_assoc($retour_messages)){
echo '<li class = "step '.$donnees_messages['nomCAT'].'" id="'.$donnees_messages['work_id'].'">
<div class = "item"><img src = "'.$donnees_messages['thumbLink'].'" alt = "'.$donnees_messages['titre'].'" title = "" width = "226" height = "147"/>
<div class = "caption">
<h3>'.$donnees_messages['titre'].'</h3>
<p>'.html_entity_decode($donnees_messages['resume'],ENT_QUOTES,'UTF-8').'</p>
<p id = "desc" class = "hidden">'.html_entity_decode($donnees_messages['description'],ENT_QUOTES,'UTF-8').'</p>
<!--<p id = "idw" class = "hidden">'.$donnees_messages['work_id'].'</p>-->
</div>
</div>
</li>';
}
?>
</ul>
As you can see, I have a ul tag containing a li tagfor each work. Each li tag takes the id of the work in database, and each li contains h3 tag and p tag containing the texts I want to show in a slickbox (for the images, I'll see later).
Now, my JavaScript code for the slickbox, appearing and disappearing:
front_functions.js
//_____________SLICKBOX__________________________________
$('#slickbox').hide();
$("#creations li").click(function(e) {
// shows the slickbox on clicking the noted link
$titre = $(e.target).children("h3").text();
$bla = $(e.target).children("#hidden").text();
$("#description").children("h1").text($titre) ;
$("#description").children("p").text($bla);
$('#slickbox').slideDown();
e.preventDefault();
$(e.target).empty();
//return false;
});
This code is not working, because my slickbox is loaded before the works. So that's why I need Ajax and a asynchronous way of sending and executing requests.
I read this sample code here: which is quite helpful.
But, I have a problem: I'm using jQuery and I would like to use $.ajax(). And I just don't really understand how to do this.
Do I have to set an XHMLHTTPRequest object? Where can I write the Ajax call? Can I call a function, instead of an URL?
Like doing (I don't know):
$(#creations li).click(function(e){
$.ajax(){
function : "displayContent(id,desc,title)",
}
}
function displayContent(id,desc,title){
$(#slickBox).children("h1").innerHTML(title);
$(#slickBox).children("p").innerHTML(desc);
$(#slickBox).show();
}
I don't even know if I should use JSON (but, well, because my data is already stored, and I just want to display them, I think I don't need Json).
Please give me your informed opinion and your senior advice.
when you send a request for server (with ajax) this is like that you are submitting a form in a page .
so every thing that you can do with php when a form submitted , you can do that with ajax too .
e.g if you want to call a function in php with ajax , just send a param to php like this :
$.ajax({
type:'POST',
data:{
param:'Hey_php_call_this_function'
},
success:function(data){
alert('hey jquery , php said : ' + data);
}
});
and in server side :
if(isset($_POST['param']) && $_POST['param'] == 'Hey_php_call_this_function'){
echo call_a_function(); /// "output to callback success function" = data
}
hope that helpful .
I've searched the database but haven't really found anything that would answer my question. I'm new with Ajax so I'll try to describe it as good as I can.
I am trying to build a rating system for images with only two options: Accept/Reject.
I have a paginated gallery with 10k images and they all need to be rated (for the competition). There's a special system for rating (accepting/rejecting) and then there's this overview gallery. Every thumbnail that has already been rated should display a clickable text/image, for example "Accepted", depending on the database value. You'd be then able to click on this text/image and it would change to "Rejected" and the mysql database entry would also change at the same time.
Left: initial state of the "Accepted" image. /
Right: changed value of the button (text or image) and updated database.
(source: shrani.si)
So what would be the easiest way to do this? There are hundred images on each paginated site with these buttons below, and you have to be able to change the value back and forth (many times, something like editable star rating system with only two stars, heh).
As you said ajax should be used and I advice you to use jquery functions
Then viewing the images should be simple for you when you loop through the database result
while looping you should test the value of the image is it accpted or rejected in order to link it with the associate JS function that I will talk about later and in that function an ajax request should be made to update that row
function change_status_image(id,status,clicked)
{
$.post("update.php",{image_id:id,image_status:status},function(data){
//your callback to do something like update the value of the button
});
}
This will make an ajax request and sends two variables image_id and image_status in the update.php you should use something like this
$q = mysql_query("UPDATE tbl_name SET column_name = '".mysql_real_escape_string($_POST['image_status'])."' WHERE image_id = '".mysql_real_escape_string($_POST['image_id'])."' ";
about the function make a div or button and link the onclick att to change_status_image
for example
<img onclick="change_status_image(img_id,reverse_current_status)" >
Use jQuery. You need two scripts:
/rate.php
/rate.js
rate.php looks like this:
<?php
// If there are values in $_POST['edits'], then this is an ajax call.
// Otherwise just display the gallery
if ((!empty($_POST['edits']) && (count($_POST['edits']))) {
foreach ($_POST['edits'] as $edit) {
alter_image($edit); // some function to update the database
}
echo "success";
exit;
}
$images = get_images(); // Some function to get the images from the database
?>
<?php foreach ($images as $image): ?>
<div class="gallery-image">
<img src="<?php print $image -> src ?>" />
<button>Accept</button>
<button>Reject</button>
<input name="id" value="<?php print $image -> id ?>"/>
</div>
<?php endforeach; ?>
rate.js looks like this:
$(function() {
// attach click event handler to buttons
$('.gallery-image').on('click', 'button', function() {
var $this = $(this),
ajaxSettings = {
url: '',
type: 'post',
data: {
edits: [
{
id: $this.parent().find('input[name=id]').val(),
action: $this.html()
}
]
},
success: function(response) {
if (response === 'success') {
// something to indicate success
} else {
// something to indicate error
}
}
}
$.ajax(ajaxSettings);
})
})
I am trying to send a php script some content to be stored in a database via ajax. I am using the jQuery framework. I would like to use a link on a page to send the information. I am having trouble writing the function that will send and receive the information, everything that I have tried is asymptotic.
EDIT
The idea is that the user will click the link, and a column called "show_online" (a tiny int) in a table called "listings" will update to either 1 or 0 (**a basic binary toggle!) On success, specific link that was clicked will be updated (if it sent a 1 before, it will be set as 0).
EDIT
There will be 20-30 of these links on a page. I have set each containing div with a unique id ('onlineStatus'). I would rather not have a separate js function for every instance.
Any assistance is much appreciated. The essential code is below.
<script type="text/javascript">
function doAjaxPostOnline( shouldPost, bizID ){
load("ajaxPostOnline.php?b='+bizID+'&p='+shouldPost", jsonData, callbackFunction);
function callbackFunction(responseText, textStatus, XMLHttpRequest)
{
// if you need more functionality than just replacing the contents, do it here
}
}
}
</script>
<!-- the link that submits the info -->:
<div id='onlineStatus<?php echo $b_id ?>'>
<a href='#' onclick="doAjaxPostOnline( 0, <?php echo $b_id ?> ); return false;" >Post Online</a>
</div>
ajaxPostOnline.php
<!-- ajaxPostOnline.php ... the page that the form posts to -->
<?php
$id = mysql_real_escape_string($_GET['b']);
$show = mysql_real_escape_string($_GET['p']);
if( $id && ctype_digit($id) && ($show == 1 || $show == 0) ) {
mysql_query( "UPDATE listing SET show_online = $show
WHERE id = $id LIMIT 1" );
}
if($result) {
if($show == '0'){
$return = "<a class='onlineStatus' href='#' onchange='doAjaxPostOnline( 1, <?php echo $b_id ?> ); return false;' >Post Online</a>";
}
if($show == '1'){
$return = "<a class='onlineStatus' href='#' onchange='doAjaxPostOnline( 0, $b_id ); return false;' >Post Online</a>";
}
print json_encode(array("id" => $id, "return" => $return));
}
?>
The load() function in jQuery is really cool for this sort of thing.
Here's an example. Basically, you have an outer div as a container. You call a script/service which returns html. You have a div in that html with an id that you will refer to later in the ajax call. The replacement div replaces the inner html of the container div. You pass your data as a json object as the second parameter to the load method, and you can pass a reference to a callback function as the third parameter. The callback function will receive every possible piece of information from the response (the full response text for further parsing/processing, the http status code, and the XMLHttpRequest object associated with this ajax call).
$("#id_of_some_outer_div").load("somepage.php #id_of_replacement_div", jsonData, callbackFunction);
function callbackFunction(responseText, textStatus, XMLHttpRequest)
{
// if you need more functionality than just replacing the contents, do it here
}
so, in your case you're talking about replacing links. Put the original link inside of a div on both sides of the operation.
Here's the link to the jQuery api doc for load():
load
EDIT:
In response to your comment about doing multiple replacements in one pass:
You can have the callback function do all the work for you.
Add a unique css class to all divs that need replacing. This will allow you to select all of them in one shot. Remember that html elements can have more than one css class (that's what the "c" in CSS means). So, they'd all be <div id="[some unique id]" class="replace_me"... Then, if you have a variable set to $("div.replace_me"), this will be a collection of all divs with the replace_me style.
Whatever elements that come from the ajax call (whether they're another div container or just a single "a" element) should have a unique id similar to the container they're to be inserted into. For example, div_replace1 would be the id of a container and div_replace1_insert would be the id of the element to be inserted
Inside the callback function, iterate over the replacements using $("div.replace_me").each(function(){ ...
Inside each iteration the "this" keyword refers to the current item. You can grab the id of this item, have a variable like var replacement_id = this.id + "_insert"; (as in the example above) which is now the unique id of the element you'd like to insert. $("#" + replacement_id) will now give you a reference to the element you want to insert. You can do the insertion something like this: this.html( $("#" + replacement_id) );
You may have to edit the code above (it's not tested), but this would be the general idea. You can use naming conventions to relate elements in the ajax return data to elements on the page, iterate the elements on the page with "each", and replace them with this.html()
did you really mean to declare your ajax success return function as
function(html)
? .. i think maybe you mean for the param to be 'data' ?
Since your php script is returning json you should set the dataType to json. Note that in your posted code sample, the success function() was outside of the $.ajax() and it needs to be inside.
$.ajax({
url: "ajaxPostOnline.php?b=" + bizID + "&p=" + shouldPost,
dataType: "json",
success: function(json){
$("#onlineStatus" + bizID).html(json.return);
}
});
You might want to check out the getJSON method since it's more concise for this particular situation.
$.getJSON("ajaxPostOnline.php", {b:bizID, p:shouldPost}, function(json) {
$("#onlineStatus" + bizID).html(json.return);
});
EDIT: Original question was edited and the provided sample changed significantly. I would still recommend the $.getJSON method.
Unless I am mistaken, it seems you have an error mixing AJAX and server-side scripting.
That depends on whether $return is PHP parsed anywhere after assignment snippet in ajaxPostOnline.php (hardly, if it is called from AJAX!).
$return = "<a class='onlineStatus' href='#' onchange='doAjaxPostOnline( 1, <?php echo $b_id ?> ); return false;' >Post Online</a>";
Surely this should be:
$return = "<a class='onlineStatus' href='#' onchange='doAjaxPostOnline( 1, ".$id." ); return false;' >Post Online</a>";