How can I make a button-link, as Like in Facebook? - php

Firstly, sorry for my bad English (I'm Italian).
Anyway, I'm making a web-site project for school, so I'm using HTML, CSS and PHP languages.
I'd like to put a sort of button-link (for example the "Like" one, as in Facebook) but how can I do it?
In Facebook, when I click on "Like", I won't be redirected to another page, so it can't be something like:
Like
In fact, I want the user to be in the same page at the same position
I thought I could write something like this (I'll call this file home.php):
<a name="5">
<a href="like.php?position=5&user=Paul>Like</a>
So, I will write in PHP something like:
<?php
// Database connection
// Adding a like in database. The user who liked the object is in $_GET['user']
// ...
header("location:home.php#$_GET[position]");
?>
But I don't want the user to be redirected to a page call like.php which redirect, in turn, the user at the beginning page...
How can I do it? And how can I connect to database?
Thanks in advance ^^

I can't provide code because what you're asking is too much. All I can do is steer you the right way to get your answers.
You're asking how to do at least 3 different things here that all require an explanation. So look up the following, and how they function:
AJAX. This will let your page send a message (like a button click to a PHP page).
PHP. You will need this to intercept the message and return the result.
MySQL. You will need this to create a table, hold your data, modify your data, and retrieve data to respond back to your main page.
Here is a simple example:
HTML graphic for buttonbutton
<img src="button.png" alt="playButton" border="0" onclick="countClick('1','Google')">
Javascript for the AJAX
function countClick(id,host) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "/includes/appCounter.php?appid="+ id +"&hostIs="+ host, true);
xhttp.send();
}
What this does is, when the user clicks the button, it goes to whatever link is there. But it also triggers the "onclick". This fires the Javascript.
The Javascript function makes a simple AJAX call to the server, passing in an ID and a Host. The PHP page knows what to do with those parameters.
In this case, there isn't any need for the page to even care about the response.
It happens in the background. In the end, a counter in my database is updated to let me know they clicked that button.
In the real world, it looks like this: http://android.dpoisn.com/

Related

When I exit a screen, I should be asked: “Do you want to save?” codeigniter

I want to do something like this: If I am viewing a record and edit it or add a new record and then exit that screen, I should be asked, “Do you want to save?”
How can I develop this thing in php? I haven't done this type of development before..
Any suggestions?
use jquery onbeforeunload function it will be execute when page refresh or
closing browser tab or closing browser .
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
You need to look for changes in javascript. Make a global variable, lets call it changed . Set it to false on page load. Whenever record is edited make it true and whenever it is saved , set it to false. When the user is closing his tab, again which needs to be detected in JS, look for changed variable. If it is true give him a prompt else he can close without any issues.
You will need to javascipt/jquery to listen for the unload event on the window.
I believe you could do something along the lines of:
<script>
function saveAlert() {
var confirm = confirm('You haven\'t saved your form! Do you want to save?');
if (confirm) {
$('form').submit();
}
return confirm;
}
$(function() {
var formSaved = <?=($formSaved) ? 'true' : 'false'?>;
if (!formSaved) {
$( window ).unload(saveAlert());
}
});
All you will need to do is pass a boolean in the $formSaved variable to determine whether the alert needs to be shown or not.
If you wanted to attempt a solution to this question in PHP, you would need to use AJAX to store field data in the database on change/update of fields, without committing the change to the table - you could store it in a cookie or session variable, or in an 'unsaved_records' table of some sort.
If your user navigates to an off-site domain there's nothing you can do in PHP but if they come back to your site, you can alert "you have unsaved data, do you want to continue where you left off?".
You could also wait till they return to the page where they had unsaved data, and restore it to the state it was in, as though they had never left. This would require some careful planning, but it's possible.
Only client side scripting can pause the window or tab being directed to a new location, as is evident in the other answers here.

How to refresh a div everytime a database is updated?

I am trying to make a chat room on my website, I am using php and mysql to store the messages and all the info. How could I automatically refresh the page every time someone updates the database? example:
If I am on my site, the messages show up on my screen but I can only see more recent messages after I refresh the page. Is there a way to make it real-time?
Also I do not know much javascript/ajax/jquery or any of that. Any help is appreciated!
There will be low amount of traffic on my site. Probably around 10-15 people at a time, if that even.
Your best bet is to make an AJAX request every sec or so and see if there are new messages.
You probably do not want to be reloading the page every time. My recommendation, and there are many ways to do this, is to make a ajax call every so often and check/pull the new information from the database.
I would research AJAX and do a tutorial.
This would be accomplished through ajax by calling a function and updating the div. I would not suggest making people refresh a page everytime they send a message it would get ugly. Another option would be using HTML5 web workers
http://msdn.microsoft.com/en-us/hh549259.aspx
You are going to need to learn AJAX in order to make this work well, and jQuery is probably the easiest way to do it. If we can assume that the DIV you want to update has the ID PonyRides, you would want to do:
$("#PonyRides").ajax({url: "/chat.php?getupdates=true"});
This will get the contents of chat.php and stick it into the #PonyRides DIV. This assumes that chat.php will get the contents of the database and format them into HTML.
The remaining challenge is to make it update whenever your database does, but the simplest way is just to reload the whole chat regardless of whether an update has been made or not.
That will impact performance, but if you have less than a hundred chatters you'll probably be fine. If you have more than that, you'd do well to sense inactivity and decrease the checking period, or only send updates instead of the whole chat. Those are more complicated topics, though, and you can build them in as needed once you get these basic concepts down.
To do this, simply wrap the ajax() call in an interval like so:
setInterval(function(){ //the following code runs repeatedly
$("#PonyRides").ajax({url: "/chat.php?getupdates=true"}); //update our chat div
},5000); //repeat every five seconds
The other, awful method would be to load chat in an iFrame, set to reload periodically using the meta refresh technique. This would be dreadful, and can only be recommended if you are trying for some reason to support incredibly old browsers.
You can use AJAX request to update the values
<script type='text/javascript'>
// function for making an object for making AJAX request
function getXMLHTTPRequest() {
try {
req = new XMLHttpRequest();
} catch(err1) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (err2) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (err3) {
req = false;
}
}
}
return req;
}
var http899 = getXMLHTTPRequest();
function searchFabIndia() {
var myurl = "http://my2nddomain.com/yebhi.php";
myRand = parseInt(Math.random()*999999999999999);
var modurl = myurl+"?rand="+myRand;
http899.open("GET", modurl, true);
http899.onreadystatechange = useHttpResponse899;
http899.send(null);
}
function useHttpResponse899() {
if (http899.readyState == 4) {
if(http899.status == 200) {
// do all processings with the obtained values / response here
// after doing the stuff, call fn again after 30 s say
setTimeout("searchFabIndia()", 30000);
}
}
}
</script>
<body onload='searchFabIndia();'>
I would suggest making an AJAX request to a file on your server which will update the database. If the update to the database is successful then return the message which was updated. Back on the client side you wait for the response and if you get one then append the message to the end of the content. This way you're loading all the messages every time (which would be expensive), you're only loading new messages.
There must be something similar to SignalR(.net) for php. It lets you add code when an event occurs, I think that is what you are looking for.

PHP redirect to pdf then navigate to another page?

I am using php and an apache server. My application gathers data from the user, put's it in a database, then uses PDFLib to display the formatted data back to the user as a pdf. My problem is, I would like the pdf to display as a new page, this works. But, I also have a blank page left up with the URL containing the variables used to display the pdf. I would like this page to show a different summary page, in HTML, without the variables in the URL, but I don't know how to do that. In the code that follows, I am going to the summary page if the medical flag is false. What I would like is to go to BOTH pages if the medical flag is true. Is this possible?
if($medical_flag) {
header("Location: {$_SERVER['PHP_SELF']}/./index.php?step=wc_pdf&id={$event_id}");
} else {
header("Location: {$_SERVER['PHP_SELF']}?step=success&id={$event_id}");
}
exit;
OK, I understand how this is impossible, but I still haven't figured out how to solve the problem. I thought I could toss the opening of the PDF back at jQuery with something like this:
jQuery(document).ready(function ()
{
function display_pdf_page(data, textStatus) {
var current_record = data || {};
//somehow display the pdf now
}
function show_pdf(eventid){
jQuery.getJSON(
'./inc/get_current_record_data_json.php',
{'id': eventid},
display_pdf_page
);
}
...
});
Then after I process the data in php "call" the above using:
echo '<script type="text/javascript">'
, 'show_pdf($event_id);'
, '</script>';
But that doesn't work either, php doesn't know where to find show_pdf. My lack of understanding of client/server side events is killing me here. Call be obtuse... I don't get it.
This solution will not work as designed.
First, if you want to hide the data, you should switch to POST rather than GET. This way, the data is included in the HTTP payload instead of the URI.
Secondly, you should either include a hidden iframe for javascript to access the page for which generate the PDF. On successful execution of the AJAX call (or whatever method you use), you can then redirect the page to your desired destination.
As suggested by sixeightzero, POST should be used instead of GET in such cases.
However, maybe you could accomplish the desired effect with a big iframe spaning the window (100% width and height)?

Ajax request with Javascript

I have a page on which I want to show a couple of MySQL tables.
There is one table on the right that may only change when a different person is selected.
De second table is the main table in the center. I have a dropdown box with contains every person. The results from the selected person is showed in the middle table. There are multiple results for each person so there is a second dropdown box to choose which of these results you want to show. This is al done by a Ajax XMLHTTP request.
The problem is that the right table uses some javascript. I know this is not possible with Ajax in combination with a XMLHTTP-request. But without the javascript I can't make what I want. Is there a way, to show the right table after the javascript is finished doing his work?
I now use frames. This is not very nice. Because I have to style both pages to look nice together, and that's not so easy as said. But this way it is doing as I want it to be.
So I searched the internet (a long time) and just a few minutes before I wanted to give up i found this piece of code (coming from http://www.javascriptkit.com/dhtmltutors/ajaxincludes.shtml):
function HttpRequest(url){
var pageRequest = false //variable to hold ajax object
/*#cc_on
#if (#_jscript_version >= 5)
try {
pageRequest = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try {
pageRequest = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e2){
pageRequest = false
}
}
#end
#*/
if (!pageRequest && typeof XMLHttpRequest != 'undefined')
pageRequest = new XMLHttpRequest()
if (pageRequest){ //if pageRequest is not false
pageRequest.open('GET', url, false) //get page synchronously
pageRequest.send(null)
embedpage(pageRequest)
}
}
function embedpage(request){
//if viewing page offline or the document was successfully retrieved online (status code=2000)
if (window.location.href.indexOf("http")==-1 || request.status==200)
document.write(request.responseText)
}
}
HttpRequest("external.htm") //include "external.htm" onto current page
This code works perfectly... The first time. As soon as you change the person the whole page disappears and only the table shows up and firefox keeps "loading" the page (you see that circle going round). I do know how to edit the code above to fit my needs but I have no understanding of Ajax or how to fix this problem. Hopefully someone can help me and give me a good solution! And tell me why the code above isn't working properly?
Thanks in advance!
Milaan
document.write only works when the page is loading for the first time, Once the page rendering is done, calling document.write will clear the page first.
https://developer.mozilla.org/en/document.write
What you might want to do instead is:
if (window.location.href.indexOf("http")==-1 || request.status==200) {
var elm = document.createElement('div');
elm.innerHTML = request.responseText;
document.getElementsByTagName('body')[0].appendChild(elm);
}
It´s been a long time since I´ve seen code like this, but one problem I can see, is that you don´t include any kind of variable in your XMLHttpRequest; no user ID or anything. Is it just supposed to load a static page?
And is there any reason you can´t use a library like jQuery? It´s no magic bullet but it will make your life and ajax requests a lot easier.
You might want to use dom functions to add your downloaded content to the existing document, like:
document.getElementById('mypanel').innerHTML = '<html code goes here>';
The best idea probably would be to use a slim javascript framework lie jquery which helps you with browser compatibility.
jQuery should make things easier for you. Your code should look something like this.
$.post("somepage.php", function(data){
$("#divID").html(data);
});
<div id="divID"></div>
And somepage.php could be something like this:
<?php
// get table content
echo "<table>...</table>";
?>

Initiate POST Request, Perform Action, Then Complete Post request - how?

When a user clicks a submit button I want the form to be submitted. However, just before this happens, I want a window to pop open and for them to fill in some data. Once they do this and they close that child window, I want the POST request to be made.
Is this possible, if so how? I just need help after the window closes, how can I make that POST request continue?
Thanks all
Couldn't you just add a
onunload=parent.form.submit()?
http://www.w3schools.com/jsref/jsref_onunload.asp
You can do something like this.. (note the code is simplified and you can probably structure it better)
This is in your main document with the form:
var childFilled = false;
myForm.onsubmit = function() {
if(!childFilled) {
window.open(...);
return false;
}
};
function submitFormFromChild() {
childFilled = true;
myForm.submit();
}
And in the window's code you have something like this:
window.onunload = parent.submitFormFromChild;
Untested, unproven, but the general concept is something like this =)
To be clear: you meant to ask (and asked in the question) how to intercept form-submission in the browser.
The title of your post implies that you are asking how to perform an asynchronous HTTP POST operation, do something else, and subsequently wait for that HTTP POST operation to complete. That whole process is not necessarily related to user interaction and is not necessarily related to HTML form submission, and it is not the same thing at all as what you meant to ask (and asked in the question).

Categories