I want to set a session variable to 0 when any of a certain set of links are clicked. To do this I have put the following in my javascript file:
$(window).load(function () {
$("#hdr li a").click(function () {
$.ajax({
type: "POST",
url: "clear.php",
data: "width=0"
});
});
});
(Ignore data: "width=0"... I don't use this data in clear.php. I put it there because I thought maybe I had to specify a data field.)
and in the file 'clear.php' I simply have:
<?php session_start();
$_SESSION['name'] = 0;
?>
So, the idea is that when any of the links in #hdr li are clicked, the user should be taken to the page that the link points to, via clear.php, which sets the session variable to 0.
This works in some browsers (Firefox and Chrome) but not in others (e.g., Safari).
Is this the standard/correct way to implement what I want? Also, how does the browser know where to go after visiting clear.php? Somehow it works, but my first thought was that I should pass the final destination URL into clear.php, and then use "header" to move from clear.php to the final destination.
Is Ajax required? If your re-directing the user to another page & you simply want to pass some data to that page then it may be simpler to include that data in your URL.
Link
Now your php would be simple:
$_SESSION['name'] = $_GET['new_session_variable'];
Now you've removed your dependency on JavaScript, does that make sense? :)
I feel it might be worth mentioning that your approach would be appropriate in certain situations, for example: if you wanted the user to be able to mark one of the links on the page as a favourite. Rather than redirecting them to the same page and reloading the majority of the pages content you might:
<a class="favourite" data-linkid="link123" href="mylink.php">My Link</a>
// Ensure your page has finished loading aka: 'ready' (almost always)
$(document).ready(function() {
// Listen for the click event
$('.favourite').on('click', favoriteLink);
// On the click - post the update via ajax and update your interface
function favoriteLink(event) {
event.preventDefault();
// Lets get the link id from our data attribute
var favourite_link = $(this).data('linkid');
// Post that information via ajax
$.post('ajax_handler.html', { link : favourite_link }, function(data) {
// And finally do something with the result!
$('.result').html(data);
});
}
My guess is this has something to do with the asynchronicity of AJAX, some browsers are properly firing the AJAX before the new link is loaded. Others might be canceling the AJAX request because the page is changing. Try preventing the default action of the anchor, and then use window.location to redirect them after the ajax call has returned.
$("#hdr li a").click(function (e) {
var href = $(this).attr('href');
e.preventDefault()
$.post("clear.php", function () {
window.location = href;
});
});
The visitor do not get to clear.php page since you are performing an ajax call.
Instead, what happens is that your browser sends a request underneath via javascript using XMLHTTPRequest object which do not break your browser behavior and as such load the page the a href points to.
As said : the ajax call is usless. You'd better include clear.php on top of your pages and test if whether or not you should set your session var, based on get param for exemple.
If you do want to keep the ajax call before the browser gets to a new page, you may attach an event handler on first common parent of your "resetting" links (event delegation) and test if you should send an ajax request to notify clear.php
I had this problem. I wanted to pass a different sql string to select different rows from a table depending on the link the user clicked on but i did not want to display the sql in a GET.
My solution was to set different session variables for each link and pass the NAME of the session variable from the link. I had several links but I have just included 2 here for the example. My code for the links was:-
<?php $_SESSION["extend_stats_sql_01"] = "";
echo ' View';}?> <br>
and
<?php $_SESSION["extend_stats_sql_02"] = " Where booking_status = 'Cancelled'";
echo ' View';}?> <br>
My code to retrieve the values on my next page to display the list with the correct sql depending on the link was:-
$stats_sql = "SELECT id, name, activity, email, diving_date, arrival_date, checkin_date, create_date, seller FROM guests ";
$sort = $_GET['sort'];
$sent= $_GET['sent'];
$result = $_SESSION["$sent"];
$stats_sql.= "$result";
$stats_sql.= " ORDER BY $sort";
obviously you need to start a session at the beginning of each page :-
session_start();
and when you have finished :-
// remove all session variables
session_unset();
// destroy the session
session_destroy();
Related
I am doing a program in PHP (MVC) in which I need to delete a row from the database when I click on a link on the View side. So, when I click on the link, the following ajax function it is called.
var deleteCar = function(id)
{
$.ajax({
type: "POST",
url: "http://localhost/project/car/deleteCar/" + id,
success: function(response){
}
});
}
but I do not want to send any data so it is the reason why I put it as above.
Then, in the Controller side I have the following method:
public function deleteCar($id)
{
//Here I call the function to delete the Car that I send by id. It works fine.
header('Location: http://localhost/project/car');
}
If I call directly the method deleteCar on the link without Ajax the header works properly but in the same moment I use Ajax to call it, I have to refresh the page to see the content that I have modified, I mean, that the Car have been deleted.
The code works fine, just I do not want to refresh the page after AJAX function had finished.
Thanks in advance!
I am guessing the use case is to allow the app to work when the user does not have JS enabled - so they just click the links and get a non-AJAX experience. In this case you probably want to redirect ONLY if the page was requested via GET, not POST. something like
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
header('Location: http://localhost/project/car');
}
is likely what you are looking for.
You will then have to actually remove the element representing the car from the DOM in your success handler, with something like:
var deleteCar = function(id)
{
$.ajax({
type: "POST",
url: "http://localhost/project/car/deleteCar/" + id,
success: function(response){
$('#car-row-' + id).remove();
}
});
}
(that won't be it exactly, it depends how the HTML of your page is setup how exactly you will do this).
I believe the key thing to understand here is - when your PHP function has completed it has removed the car from the database, but the browser still has the same HTML it got from the page originally. Just sending an AJAX request won't change that. If you want the HTML in the browser to change to reflect the new state of the database, you will NEED to do one of two things:
Refresh the page, so the entire thing is rebuilt by PHP based on the current database state
Use javascript to change the HTML in the browser, to reflect the changes you have made to the database state.
It is wrong on so many levels but it's difficult to put in words. It's subtle.
Long story short - think about jquery.ajax as of another virtual tab of you browser.
When you make ajax-request to the server - you create new virtual tab.
You php header could affect this virtual tab and redirect it where that header defined.
But it will redirect that virtual tab, not your current tab - if that makes sense.
What are your options? On success - make redirect with pure javascript.
success: function(response){
location.href = "http://localhost/project/car";
}
This would be the basic way to solve your problem.
I have asked this question before but I couldn't understand the answer maybe because it didn't work for me.
I have a developed a chat application. Once a user submits using keyup, it works well i.e inserted into database and also selected just fine and the message is even displayed. The page being refreshed by javascript is load.php which has php code doing the selection like this;
SELECT * FROM chat WHERE sender_id=$_SESSION['id']
This is working just fine. But when I change it to
SELECT * FROM chat WHERE sender_id=$_SESSION['id'] AND receipent_id=$_GET['id']
it is not working simply because the $_GET['id'] of a selected member in the home page is not being passed to the load.php which is being refreshed by javascript every .....milliseconds so that online messages of the session id and the selected member should show in the message display.
I refresh the load.php using this code on the home page;
function refresh(){
setTimeout (function(){
$('#message').load('load.php');
refresh();
}, 2000);
}
working just fine.
Now this load.php must select for me messages only for the member selected in the home page. So how can I have this members' id passed on to this load.php on selecting from database?
Will be so grateful for your help programmers.
If you want to pass $_GET['id'] value try to add in your function this value
function refresh(){ setTimeout (function(){
$('#message').load('load.php?id=<?php echo $_GET['id']; ?>');
refresh(); }, 2000);
}
Then load.php will have get value
You need to add get variable in your code:
function refresh(id){ //receive id
setTimeout (function(){
$('#message').load('load.php?id='+id); //add id variable to the url
refresh();
}, 2000);
}
Well, you need to pass the GET value on the query string. Currently you're requesting this:
load('load.php')
If you want an id value, add one:
load('load.php?id=' + someValue)
If you need to get that value from the current query string in JavaScript, there are a number of ways to do that. Though, when you initially load the page, if the value is available then it would be trivial to output it to the page from PHP code in the first place. Something like this:
var someValue = <?php echo $someValue; ?>;
Keep in mind a few things here:
If the value is a string then you need to specify quotes in the JavaScript, not in the PHP.
Don't blindly echo user-submitted values to the page, that's a security vulnerability.
Users can change this value in your load.() call. So your approach may make it trivial for users to "impersonate" other users in your application. Make sure you always validate authorization server-side.
Your example SQL queries look like glaring SQL injection vulnerabilities. You're probably going to want to read up on validating user input and using prepared statements.
I am trying to get the image links from 9gag (what also works) and when I click on a button the image changes to the next one. The basic problem is that it works only once. I can then switch between the 1st and the 2nd image, though. This should be pretty simple, but I ´ve got no clue where the error is, so thanks in advance to anyone bothering to look at this.
<?php
$index = 0
$html = file_get_contents("http://www.9gag.com");
preg_match_all( '|http://d24w6bsrhbeh9d\.cloudfront\.net/photo/.+?\.jpg|', $html, $gags);
?>
<script>
function nextImg(){
<?php $index++;?>
pic.src='<?php echo $gags[0][$index];?>';
}
function prevImg(){
<?php $index--;?>
pic.src='<?php echo $gags[0][$index];?>';
}
</script>
You can't increment your PHP variables after the page has loaded. You are trying to increment them client-side with JavaScript. You are going to need to call that PHP using AJAX if you want to do this without refreshing the page, and even then you'll want to increment a javascript variable to keep track of where you are.
EDIT: I went a little nuts creating an ajax routine using PHP and JavaScript, specifically the jQuery library, which you will need to link to for this to work. You may also need to modify parts of the script to work with what you're trying to accomplish, but this certainly is a guide for running your ajax app as you're hoping to.
Start by making a PHP file with this script:
<?php
// Set content header to json
header('Content-Type: application/json');
// Get the index from the AJAX
$index = $_GET['index'];
// Grab file contents & parse
$html = file_get_contents("http://www.9gag.com");
preg_match_all( '|http://d24w6bsrhbeh9d\.cloudfront\.net/photo/.+?\.jpg|', $html, $gags);
// Send filename back to AJAX script as JSON
echo json_encode(array($gags[0][$index]));
?>
Then, in your HTML, include this jQuery to complete AJAX calls to your PHP script, and update the DOM with the data from the PHP script.
<script>
$(function() {
'use strict';
// Initiate index variable
var index = 0;
// Load initial image
loadImage(index);
// Add click event to a button with class of next-btn
$('.next-btn').click(function(e) {
e.preventDefault();
// Increment index to get next image
index++;
// Run AJAX function to retrieve image
loadImage(index);
});
// Add click event to a button with class prev-btn
$('.prev-btn').click(function(e) {
e.preventDefault();
// Decrement the index if it isn't 0
if (index > 0) {
index--;
}
// Run AJAX function to retrieve image
loadImage(index);
});
});
function loadImage(index) {
'use strict';
$.ajax({
type: 'GET',
url: 'your-php-script.php', // Filepath to your PHP script
data: 'index='+index, // Index is passed through GET request
dataType: 'json', // Return JSON
success: function (data) { // If the php script succeeds
// Change img with class of pic's src
// to the filename retrieved from php
$('.pic').attr('src', data[0]);
}
});
}
</script>
Configuring this for your needs will require some serious PHP and jQuery/JavaScript knowledge, as some debugging will likely be needed. Good luck!
EDIT 2:
I uploaded the working (tested, it works) source files to my website if you want to download. Please accept answer and let me know you grabbed the files...
http://www.wedgewebdesign.com/files/ajax-image-loader.zip
#Eric basically has it right but didn't really go into detail if you aren't familiar with the model...
PHP is a server side language in that it does all its processing on the web host server and once it is complete sends a static result back to the user. This means, whatever you see after the page is loaded within PHP is there to stay, unless you do one of two things:
1) Send a new request -- You provide different parameters, the page re-executes its logic and returns a new result to the user
2) Execute some form of clientside Javascript. Javascript is different from PHP in that it executes on the client (not the server) so you don't necessarily have to send responses back to the server unless you need more information. Javascript and PHP can be combined to create AJAX calls which allow the client to make asynchronous calls to the webserver for more data without reloading the entire page. The Javascript handles re-drawing the new information or updating the page which can appear seamless to the user.
What you therefore need is one of those two options. Either you provide 'next'/'previous' links to the user and the page is loaded differently each time or you create an AJAX call that fetches the url of the next image and then loads it.
Try assigning a variable to $gags[0][$index]. Something like
$imgsrc = $gags[0][$index];
and then
pic.src='<?php echo $imgsrc; ?>';
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. Can any one give me some simple example? Thanks.
update
products.php
model:hml03
model:hml04
model:hml05<!--post value from products.php-->
...<!--many other tags -->
<div class="show_data"></div><!-- get the data back show in here without refresh the page.
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>
If your pages are ALL on the same domain then you can do the following :
Suppose that you have the first page, in which you do not want any iframe, the name of the page is yourPage.php.
And suppose that you have one other page whose name is yourService.php
What I understand from your question is that you just want to perform a simple AJAX request in order to POST/GET some data to a page, and retrieve the response.
With jQuery you can do that.
On yourPage.php you will have :
<html>
[...]
<script type="text/javascript">
function callService() {
$.ajax({
type: "GET", // or "POST",
data: "myLogin=login&myPassword=password",
url: "./yourService.php",
success: function(data){
alert("The service told me : " + data); // data is the response, make something with that like putting your data on your HTML page
}
});
}
</script>
[...]
Call the service
[...]
</html>
And on yourService.php :
<?php
// retrieve the data by looking at $_GET['login'] and $_GET['password'] (or $_POST)
// clean-up the variables if needed
// perform the MySQL query (by using mysql_query() for example)
// retrieve the data from the database
echo 'You are now connected'; // send something to yourPage.php by writing some data with the echo() function for example
?>
I hope my answer will help you.
This solution does not work if yourService.php is not on the same domain name that yourPage.php (the javascript engine of your browser will block that)
With JavaScript You cannot do AJAX calls to other domains. This is a browser "feature" that blocks this calls as prevention to corss-domain scripting...
But still You can do it with PHP. If You also want to get the response regarding to Your post, You can use cURL http://php.net/curl. If You want to use just get, it is much simpler, You only call from Your PHP:
$response = file_get_contents('http://www.domain.com/some_page.php?data=' . $my_get_data);
Depending to the response data format You can output them directly or parse it first.
If You need them to be outputed on another page (that You are now), You can save the data to the $_SESSION and do a redirect...
$_SESSION['response'] = file_get_contents('http://www.domain.com/some_page.php?data=' . $my_get_data);
header('Location: http://www.my_domain.com/my_first_page.php');
and on Your my_first_page.php You can do
var_dump($_SESSION['response']);
When a web form is submitted and takes the user to another page, it is quite often the case that the user will click the Back button in order to submit the form again (the form is an advanced search in my case.)
How can I reliably preserve the form options selected by the user when they click Back (so they don't have to start from scratch with filling the form in again if they are only changing one of many form elements?)
Do I have to go down the route of storing the form options in session data (cookies or server-side) or is there a way to get the browser to handle this for me?
(Environment is PHP/JavaScript - and the site must work on IE6+ and Firefox2+)
I believe you're at the mercy of the browser. When you hit back, the browser does not make a new request to the server for the content, it uses the cache (in nearly every browser I've seen anyway). So anything server-side is out.
I'm wondering if you could do something very complicated like storing the search result in a cookie during the onunload event of the results page, and then reading the cookie in javascript on the search page and filling in the form - but this is just speculation, I don't know if it would work.
I'd put it in the session.
It's going to be the most reliable and even if they don't go straight "back", it'll still have their search options there.
Putting it in the cookie would also work, but wouldn't be recommended unless it's a very small form.
It's up to the browser, but in most cases you don't have to do anything.
IE, Firefox, etc. will happily remember the contents of the form in the previous page, and show it again when Back is clicked... as long as you don't do anything to stop that working, such as making the page no-cache or building the form entirely from script.
(Putting stuff in the session is likely to confuse browsers with two tabs open on the same form. Be very careful when doing anything like that.)
The problem you have is that the browser will return a cached version of the page, and probably not ask the server for it again, meaning using the session would be irrelevant.
You could however use AJAX to load the details of the previously submitted form on the page's load event.
You would basically have to store it on your server in some way (probably in session variables, as suggested) after the POST. You also have to setup Javascript on the form page to execute on load to issue an AJAX call to get the data from your server (in, say, JSON format) and prefill the form fields with the data.
Example jQuery code:
$( document ).ready( function() {
$.getJSON(
"/getformdata.php",
function( data ) {
$.each( data.items, function(i,item) {
$( '#' + item.eid ).val( item.val );
} );
});
} );
Your /getformdata.php might return data like:
{
'items': [
{
'eid': 'formfield1',
'val': 'John',
},
{
'eid': 'formfield2',
'val': 'Doe',
}
]
}
and it would obviously return an empty array if there were nothing saved yet for the session. The above code is rough and untested, but that should give you the basic idea.
As a side note: current versions of Opera and Firefox will preserve form field content when going Back. Your JS code will overwrite this, but that should be safe.
Another ajaxy options (so it's not good for users without javascript) is to submit the form via javascript and then go the confirmation page (or show the message on the form by replacing the button with a message). That way there is no "back" possible.
Why not store the values into a cookie before submitting? You could also include a timestamp or token to indicate when it was filled out. Then when the page loads, you can determine whether you should fill in the fields with data from the cookie, or just leave them blank because this is a new search.
You could also do everything local by javascript. So you store a cookie with the search value and on pageload you check if the cookie exists. Something like this:
$('#formSubmitButton').click( function() {
var value = $('#searchbox').val();
var days = 1;
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
document.cookie = "searchbox="+value+expires+"; path=/";
});
$(document).ready( function() {
var nameEQ = "searchbox=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) var valueC = c.substring(nameEQ.length,c.length);
}
$('#searchbox').val(valueC);
});
Have not tested this but is should work. You will need jQuery for this.
Cookie functions came from: http://www.quirksmode.org/js/cookies.html
I should say btw that both FireFox and IE have this behaviour by default.