This question already has answers here:
Update data on a page without refreshing
(4 answers)
Closed 6 years ago.
I have some post and like button with code:
Like
Now In the likes.php I have some Get coding for userid and postid to find which user liked which post and to store it into database. It works good but it reload page. It goes to likes.php and if it is successful it header back to home page or any other I want to. Now my question is how can I do it without reloading a page should I include likes.php code into page where are the posts and like buttons. And use a <a ref=""></a> if it is possible that way? Or if somebody have a better explanation he can post it as well.
Yes because you used the code ahref tag and this is how it is supposed to work.If you dont want it to reload try using AJAX.This is not the complete answer but you need to make that work through ajax only.You will find a lot of videos and demos regarding it.
Check this Example:
http://www.w3schools.com/ajax/ajax_php.asp
Update:
Mainfile.php
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<?php
session_start();
$userid=$_SESSION['userid'];
?>
<div id="like">
Like
<!-- here id should be different for every post .I would prefer using post id to this ahref id because i would use that to detect what post it is actually. -->
</div>
</html>
<script type="text/javascript">
function likeclick(element)
{
var postid=element.id;
var userid=<?php echo json_encode($userid);?>;
//You can use different methods to pass variable to javascript.I used this one because it is easy to implement
//it has some cons to it .Do check for that on google also.
//http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript
//Check this link for more.
$.ajax({
type:'POST',
url:'getlike.php',
data:{"userid":userid,"postid":postid},
success : function(content)
{
$('#like').html(content);
//This gets the html content from the getlike page and displays in the div on this page.
//Note:I have used .html which replaces any previous content inside the 'like' div.
})
}
</script>
getlike.php
<?php
require 'connect.inc.php'; //This make a connection to the database
$userid=$_POST['userid'];
$postid=$_POST['postid'];
$statement=$mysqli->prepare("select `likes` from `posts` where `postid`=?");
$statement->bind_param("s",$postid);
$statement->execute();
$result=$statement->get_result();
while($row=$result->fetch_assoc())
{
$likes_on_this_post=$row['likes'];
}
$likes_on_this_post=$likes_on_this_post+1; //Added one like more.
$statement=$mysqli->prepare("update `posts` set `likes`=?");
$statement->bind_param("s",$likes_on_this_post);
$statement->execute();
echo "+".$likes_on_this_post;
//This echo is actually the main thing.When this page runs through ajax the response is given back to the calling object
//What goes with response are the html contents on this page as well as whatever i echo on this page.
//Considering this example i have only echoed the no of likes and it doesn't contain any sort of html content so only the echoed element goes.
?>
Related
I am installing Disqus Comment system on my website. I understand that I can dynamically call the page url or id via php and thus do not need to hardcode the URL or page ID everytime I have a Discus comment box.
This question asked 7 years ago this answer was provided by #Yogus but I couldn't get it to work.
<HTML>
<title>HTML with PHP</title>
<body>
<h1>My Example</h1>
<?php
include 'testConnection.php';
?>
<b>Here is some more HTML</b>
<?php
//more php code
?>
</body>
</HTML>
I've hear that to use PHP I must change my website pages to end in .php rather than .html. I don't want to do this for every page as it would probably affect SEO and I've currently 325 pages.
I'd like to do a call to a PHP file, have it return a variable with the URL or Page ID and then I can plug this into the Discus. I've read there is a dedicated variable maybe $_SERVER which returns the page URL or ID.
Any help would be appreciated! Oh, a link to one page where I've Discus installed is here {go to bottom}. This page is hard coded in.
coinsandhistory.com/countries/Ancients_Rome/Ancients_48_Rome_Empire_Tetrarchy-Constantine.html
You can still keep your pages as HTML in this case.
You can make a call to the PHP page with Javascript, get the result via AJAX, and then use that result in a URL. In this example, I will feed the php a parameter that will determine what the URL will be. The HTML page will use javascript to populate the link in the anchor tag with the data coming from the php file.
example
the PHP code would look something like:
<?php
$p = $_REQUEST['p'];
if($p == 'one')
echo 'http://urlone.php';
if($p == 'two')
echo 'http://urltwo.php';
?>
the HTML code would look something like:
<html>
<script>
function populateURL(param){
//get the anchor tag
var link = document.getElementById('dlink');
//call the php file to return the url as a string,
//then set the url of the anchor to that string
fetch('url.php')
.then(response => (response){dlink.href = response});
}
//get the url if the value is 'one'
populateURL('one');
</script>
<body>
<a id="dlink">CLICK HERE </a>
</body>
</html>
I found a working answer on SO from ~10 years ago.
Get current URL with jQuery?
The solution was to use javascript from within the HTML which has queries for such things.
// Returns path only (/path/example.html)
var pathname = window.location.pathname;
// Returns full URL (https://example.com/path/example.html)
var url = window.location.href;
// Returns base URL (https://example.com)
var origin = window.location.origin;
To look at the results I just use the javascript to write out the answer, i.e
<p>JavaScript variables<br><br>
page url:
<script type="text/javascript"> document.write(page_url)
</script>
Thus php nor an external file wasn't needed. A note the javascript variable assigns MUST be done before the print commands, otherwise Chrome reports an error & nothing is displayed.
I'm quite new to PHP and I'm dealing with a problem I have no idea how to solve. I'm generating a table of users (name, username, e-mail) from a MySQL database. There is an edit link in each row. This links displays a pop-up DIV (made using jQuery) that contains three form fields (name, username, e-mail) that can be used to edit (update) the particular row.
I would like to pre-load the current values from the database into these form fields to make it more convenient to edit them.
The problem is that the DIV is displayed without refreshing the web page, meaning that I'm unable to pass any parameters from the edit link and therefore I cannot tell the server which values to pre-load.
Is there any solution to this?
Thanks!
You can pass them using this way:
Note : when u generate the values(name,username,email) in Server (using PHP)..do it as follows :
<a class='editBtn' data-x="the username info" data-y="the email info" data-z="name">Edit</a>
then at Client side catch them using on click events:
jQuery('.editBtn').each(function(i,v){
jQuery(v).click(function(eve){
eve.preventDefault();
eve.stopPropagation();
var username= jQuery(v).attr('data-x');
var email= jQuery(v).attr('data-y');
var name= jQuery(v).attr('data-z');
/*
display ur Modal Box here
Happy Coding :) ,
*/
});
});
try this:
$(your var in JS) = <?PHP echo $(your rowname in the prepaired statement)['(your ID tablevariable)'];?>
that could work but i hadn't seen the code so, this is the only thing i could give tou to try
if you want to refresh the data in realtime about your html with your new values, you must use AJAX. JQuery give us a simple api about this: https://api.jquery.com/jQuery.ajax/
I like to use a hidden <iframe> at the bottom of all my pages. I can load a php script into that, which than can be used to update the parent frame by using javascript.
<iframe name="hidden" id="hidden" style="display:none"></iframe>
To call the script, just use a link or button to call it.
Click to load script!
Once you get the data from mysql, use javascript to change the variables.
<script language="javascript">
parent.document.getElementById('name').value = '<?PHP= $sqlResults['name']; ?>';
parent.document.getElementById('username').value = '<?PHP= $sqlResults['username']; ?>';
parent.document.getElementById('email').value = '<?PHP= $sqlResults['email']; ?>';
</script>
I am not sure if what I am trying to do is possible but here it is.
I have a header, inside that header is a php include for "login.php"
On "login.php" is a link that takes the user to "forgot.php".
What I would like to do is, instead of the user being taken to "forgot.php" is to just refresh the page with "login.php" include replaced with "forgot.php" or do some sort of content switch out, sort of like using an Iframe.
I dont want to bring the user to a new page, I just want to switch out the content displayed inside my header.
Thanks for any help you can provide, code samples appreciated.
If you are trying to accomplish this without reloading the page you will need to use AJAX.
If you want to just keep the login.php you can perhaps do something like:
link
with php something like
<?
if ( isset($_GET['p']) && $_GET['p']=="forgot") {
include('forgot.php');
} else {
include('login.php');
}
PHP is parsed in it's entirety before the page is displayed in a user's browser, therefore, things such as onclick() or onsubmit() that are featured in JavaScript (a client-side language) are not available in PHP.
There would be a few solutions possible:
1) Use AJAX to submit a query to the server and replace the HTML content on the page with the result.
2) As you mentioned, use iFrames.
3) Have a hidden <div> on your login.php page that contains the HTML for forgot.php, and use a simple JavaScript onclick() method to swap the page contents. In this case, both "pages" would actually all be in the same file of login.php.
I can think of two things:
What I would do, assuming that the differences between your login.php and forgot.php aren't too different because you don't to change the page, is to put the html for the forgot.php just below the html for the login.php and hide the login.php html and show the forgot.php content.
example:
<div id = "login">
<!-- Login HTML -->
</div>
<div id = "forgot" style = "display:none" >
<!-- forgot password HTML -->
</div>
<input type="button" value="Forgot Password?" onclick="forgot()" />
Javascript:
function forgot(){
document.getElementById('login').style.display='none';
document.getElementById('forgot').style.display='block';
}
Otherwise, you could use an ajax call to the page and insert the necessary elements. This would create a noticeable pause.
You can't change the include statement from javascript because the script was already executed by the time you see your page in the browser.
Use ajax to dinamically change the content of the page without refreshing.
If you're using jquery the code would be pretty simple:
<script type="text/javascript">
$(document).ready(function() {
$('#link').click(function() {
$.get('script.php', function(data) {
$('#divOfContainer').html(data);
});
});
});
</script>
<div id="divOfContainer"><!-- the content to be fetched with ajax will be put here --></div>
Link
I have many tags. I want click each tag, then post/get the tag's value to another page.
In another page, received the values and make a mysql query. Then return the resalt data to the first page(do not make an iframe).
I think jquery post and load may be can do that (but have no idea how to combine two functiton). Or maybe there have any other way. Thanks.
here is my code
products.php
model:hml03
model:hml04
model:hml05<!--post value from products.php-->
data.php
<div id="data">
<?php
$result = mysql_query("SELECT id,name,details,add_date,model FROM ctw_products WHERE (MATCH (name,details,model) AGAINST ('+$_GET['get']' IN BOOLEAN MODE) Order By add_date DESC LIMIT 20 "); // get value with a mysql query
while ($row = mysql_fetch_array($result))
{
echo '<div class="name">'.$row['name'].'</div>';
echo '<div class="model">'.$row['model'].'</div>';
echo '<div class="details">'.$row['details'].'</div>';// how to return this part of datas back to products.php
}
?>
</div>
...<!--many other tags -->
<div class="show_data"></div><!-- get the data back show in here without refresh the page.
First you need AJAX to be able to do this. The simplest way to achieve this is use a library like jQuery
You can either download the library and include it locally or link to it directly from the jQuery site. the following code should allow you fetch data from data.php without a page refresh
<!--include the jQuery library -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.js"></script>
<script type="text/javascript">
function get_data(get){
$.get('data.php?get='+get, function(data) {
$('.show_data').html(data);
});
}
</script>
Next, modify your links to call get_data onclick like this:
model:hml03
Notice how we pass the id of the product to get_data, you need to do this for every link.
I would recommend you read up on Ajax and JQuery to really get the idea.
This question already has an answer here:
how do i write a javascript alert box to give a yes or no question and integrate with php calls?
(1 answer)
Closed 7 years ago.
I'm reposting this post I just posted a while ago.
how do i write a javascript alert box to give a yes or no question and integrate with php calls?
I wasn't getting any more responses, so I figured the post got lost in somewhere out there.
what I tried doing was this
<script type="text/javascript">
if(window.confirm("Are you sure you want to delete that record?")) {
<?php
mysql_query("delete from tbl_payments where id = '$id'") or die(mysql_error());
header("Location: dashboard.php");
?>
}
</script>
and it didn't work. the record just got deleted once I pressed the link to delete.
what am I doing wrong? thanks
ps: I cant do ajax yet I'm looking for a simple way of doing it so I can comprehend how it works
thanks
You cannot use JavaScript to control the flow of PHP code in the way you've provided. The reason the record is always deleted is because the PHP interpreter kicks in as soon as it sees the <?php identifier, so the statement will always be executed.
I would try something like this:
Use a standard form and the post method to submit the id of the record to be deleted
Use JavaScript to enhance the form; bind to the submit event and then you can ask for confirmation, only allowing the form to submit if they say okay.
In this way, the JavaScript enhances functionality and it will degrade gracefully. You'll still have to implement all the business logic of deleting the row from the PHP script that handles the form submission.
From what I can gather you are failing to understand that PHP runs on the server while Javascript runs on the client. Follow #Peter's advice, also read and learn more before diving head first into it and coming up with weirdness like that. A rudimentary fix would be something like:
<script type="text/javascript">
function deleteRecord(id) {
if(window.confirm("Are you sure you want to delete that record?")) {
window.location.href = 'myScript.php?id=' + id;
}
}
</script>
In your myScript.php:
<?php
$id = $_GET['id'];
mysql_query("delete from tbl_payments where id = '$id'") or die(mysql_error());
header("Location: dashboard.php");
?>
you can use something like this:
<script type="text/javascript">
function askUser() {
return window.confirm("Are you sure you want to delete that record?");
}
</script>
and then in your html:
delete record
of course you need to create a file delete.php which handles all your logic for deleting.
ps. in real life you should avoid inline javascript, i'm just using it here for this short example