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 .
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 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;
})
I may have misunderstood the purpose of PHP here. But I want to do the following:
I have a PHP function, and I call it from HTML, e.g.
<BODY>
<DIV id='A'>
<?php emit("hello1"); ?>
</DIV>
<DIV id='B'>
<?php emit("hello2"); ?>
</DIV>
</BODY>
And I want to know, within the function, which DIV it was called from.
e.g.
<?php function emit($txt){
echo "$txt";
echo "from DIV id $DIVID"
}
?>
And I want it, obviously, to print
hello1 from DIV id A
hello2 from DIV id B
Is there any way of finding the "current" DIV's ID?
Yes, you have misunderstood the purpose of PHP.
PHP is a server side programming language, it does not run on the HTML page, but before the HTML gets loaded on to the browser.
The task that you are trying to do can be done from JavaScript if interested. I will give an example of jQuery:
var emit = function(el, txt) {
var id = el.attr('id');
el.html(txt+" from DIV id "+id);
}
Now call using
emit($("#a"), "hello1");
Same can be done from JS in the following way
var emit = function(el, txt) {
el = document.getElementById("el");
id = el.getAttribute('id');
el.innerHTML(txt+" from DIV id "+id);
};
Use like:
emit("a", "hello1");
how i can i change the content of a page without refreshing.I know we need to use hidden frames for this but all the tutorials i have come across teach this only for HTML files what if the content is returned from a PHP file how do i do it in such a case? what should the php file echo or return?
You will have to use Ajax for that, have a look at this tutorial:
AJAX Tutorial
If you use a hidden frame, the content won't be displayed (hence "hidden"), I think you just mean to use an iframe. But this doesn't fit your description of "without refreshing", since you have to refresh the frame.
When loading the PHP file inside the frame, your PHP file just needs to generate HTML the same way you would generate a normal page. It's the same whether the PHP file is loaded inside a frame or not.
I use this method for a lot of my websites and so does Google. If you want to get data from a PHP file and then dynamically update the page you need to "import" the PHP file somehow without the entire page being redirected, or using iframes (which works too but is a lot messier). The way you do this is to import the file as a "javascript" file.
The following code demonstrates a form called "testform" and a text input called "userpost".
When you submit the form, it will import a file, and then update div "outputText" with whatever you entered... and wait for it... all without the page being redirected at all or refreshed!
I have included a lot of extra functions to show how you can access all of your functions on the same DOM unlike if you use frames where you have to use "top.object" or what not
index.html
<html>
<head>
// Get objects by their id. We will use this in the PHP imported file
Get = function(id) {
return (!id) ? null : (typeof id == "object") ? id :
(document.getElementById) ? document.getElementById(id) :
(document.all) ? document.all[id] :
(document.layers) ? document.layers[id] : null;
}
// Formats a string so it does not break in a URL
String.prototype.formatForURL = function() {
var str = escape(this.replace(/ /gi, "%20"));
str = str.replace(/\&/gi, "%26").replace(/\=/gi, "%3D");
str = str.replace(/\//gi, "%2F")
return str;
}
String.prototype.contains = function(str) {
return (!str) ? false : (this.indexOf(str) > -1);
}
Object.prototype.killself = function() {
this.offsetParent.removeChild(this);
}
// Import the script
ImportScript = function(js) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("language", "JavaScript");
script.setAttribute("charset", "utf-8");
// we add the is tag so can delete the "js" file as soon as it executes
script.setAttribute("id", "import_" + head.children.length);
script.setAttribute("src", js + (js.contains("?") ? "" : "?") + "&is=" + head.children.length);
head.appendChild(script);
}
// Get and send value to php file
sendInfo = function() {
var file = "js/myFile.php?userpost=";
file += document.testform.userpost.value.formatForURL();
ImportScript(file);
}
</head>
<body>
<div>
<form name=testform onsubmit="sendInfo(); return false">
<input type=TEXT name=userpost />
<input type=SUBMIT value=Go />
</form>
</div>
<div id=ouputText>
This text will be replaced by what you type
and submit into the form above
</div>
</body>
<html>
js/myFile.php
<?php
// Here you can now use functions like mysql_connect() etc. even exec()
// ANYTHING! Save them into variables and output them as text which goes
// Straight into the javascript! e.g. :
// $con = mysql_connect("localhost", "username", "password");
// if($con) {
// ... code to retrieve data and save into $variable
// }
// print "alert(\"$variable\");"; // this alerts the value in variable
if(isset($_GET['userpost'])) {
$userpost = $_GET['userpost'];
?>
Get("outputText").innerHTML = "<?=$userpost; ?>";
<?php
}
?>
// Clear text area
document.testform.userpost.setAttribute("value", "");
// Remove the file from header after info is changed
Get("import_<?=$_GET['is']; ?>").killself();
If I had typed in "Hello World" into text input "userpost" then
div "outputText" would be filled with the words "Hello World"
deleting what was previously there, and the text input will be cleared
Hidden frames is one design pattern that is a part of the overall AJAX design pattern. This is an extreme high-level overview, but this is essentially how it works:
Javascript in your HTML page makes a request to your PHP script by using an XMLHTTPRequest object, or a hidden frame or iframe. This is usually done asynchronously, so you can continue to work with your HTML page while the request is being made.
The data is returned to your Javascript. At this point, you can then manipulate the page, and update data on the page using various DOM methods.
my most trusted programmers and thank for all the help!
I grab rss-feed by jquery-ajax using php curl. It's loading very nicely directly on the page. However, I would like to translate the text, that is now html, title within h2 and text within p, wrapped by a div-container.
Google's api-script for translation doesn't seem to run after the content was put into the div. Really nothing happens. I tried both putting the script in the ajax-url-file and the file that the content is displayed on.
I used .live(), but no result.
Any idea?
Thanks!
--
In one of the methods I create a table i mysql and put in title, link and text. After that I echo the table.
$query3 = mysql_query("SELECT * FROM temp_rss_$id") or die("$error_msg");
while ($row3 = mysql_fetch_array($query3)) {
$title = htmlentities($row3['title']);
$text = htmlentities($row3['text']);
$link = $row3['link'];
echo "
$titel
$text
";
}
The title is within in a h2 and an anchor, and the text is within a p.
Using simple jquery, this method without ajax, to grab this:
$('a.rss-links').live('click', function() {
$('#media').load(php_file);
});
Works like a charm. Then there's the google-api-script:
function initialize() {
var text = document.getElementById('media').innerHTML;
google.language.detect(text, function(result) {
if (!result.error && result.language) {
google.language.translate(text, result.language, "en", function(result) {
var translated = document.getElementById("media");
if (result.translation) {
translated.innerHTML = result.translation;
}
});
}
});
}
google.setOnLoadCallback(initialize);
It doesn't load the google-script. What can be done? Of course it does work if I put the text directly on the page, without loading another file. Using ajax and append(result) instead of .load doesn't make a difference. Any idea?
Thanks!
You can call that function after the .load() runs, as it's callback, like this:
$('a.rss-links').live('click', function() {
$('#media').load(php_file, initialize);
});
This will call the initialize function once the .load() has completed and the new content in the #media element is there and ready to translate.