I have a session variable $_SESSION['name']. I set in a php file which is called with ajax inside a keyup event. It works well. Until a user uses the previous page button.
When a user uses this button (or mouse button), the last set session variable value is basically not set. It will return to an older set value (the one before the last one). I wonder how/why and what I can do about it.
I've read quite a lot stackoverflow (and other) solutions, but nothing so far seems to work.
HTML:
if(isset($_SESSION['name'])) {
echo '<input type="text" name="name" value="'.$_SESSION['name'].'">'
}
<script type="text/javascript" defer>
$(function() {
var name = $('input[name="name"]').val();
$('input').on('keyup', function() {
$.ajax({
url: 'example.php?name=' + name,
type: 'GET',
dataType: 'json',
success: function(data) {
// blablabal more code
}
});
});
</script>
example.php:
$_SESSION['name'] = 'test';
Please note I'm starting the session on all of my pages with session_start(); and please note that I also tried to regenerate my session id with any hope that would do the trick.
You cannot achieve this you have to reload your page to see the changes.
although here is a suggestion to do this what you want to achieve.
if(isset($_SESSION['name'])) {
echo '<input type="text" name="name" value="'.$_SESSION['name'].'">'
}
<script type="text/javascript" defer>
$(function() {
var name = $('input[name="name"]').val();
$('input').on('keyup', function() {
$.ajax({
url: 'example.php?name=' + name,
type: 'GET',
dataType: 'json',
success: function(data) {
$("[name='name']").val('Your response');
}
});
});
By doing this you can achieve what you are looking for. also if you load the page it will get the value from session
Related
I'm "fighting" with this for hours now, I hope you could help me with the solution. So I've got a basic form with an empty div that will be then filled:
<form method='post' action='/shoutek.php'>
<input type='text' id='shout_tresc' name='shout_tresc' class='shout_tresc' />
<input type='submit' id='dodaj' value='Dodaj' />
</form>
<div class='shoutboxtresc' id='shout'></div>
<span class='loader'>Please wait...</span>
The shoutek.php contains the queries to do after submission of the form and functions to populate the div.
Here goes my jquery:
$(function() {
$(\"#dodaj\").click(function() {
// getting the values that user typed
var shout_tresc = $(\"#shout_tresc\").val();
// forming the queryString
var data = 'shout_tresc='+ shout_tresc;
// ajax call
$.ajax({
type: \"POST\",
url: \"shoutek.php\",
data: data,
success: function(html){ // this happen after we get result
$(\"#shout\").toggle(500, function(){
$('.loader').show();
$(this).html(html).toggle(500);
$(\"#shout_tresc\").val(\"\");
$('.loader').hide();
});
return false;
}
});
});
});
The problem in that is that it directs me to shoutek.php, so it does not refresh the div in ajax.
As you can see, I used return false; - i also tried the event.preventDefault(); function - it did not help. What is the problem and how to get rid of it? Will be glad if you could provide me with some solutions.
EDIT
Guys, what I came up with actually worked, but let me know if that's a correct solution and will not cause problems in the future. From the previous code (see Luceous' answer) i deleted
$(function() {
(and of course it's closing tags) and I completely got rid of the:
<form method='post' action='/shoutek.php'>
Leaving the input "formless". Please let me know if it is a good solution - it works after all.
$(function() {
$("#dodaj").click(function(e) {
// prevents form submission
e.preventDefault();
// getting the values that user typed
var shout_tresc = $("#shout_tresc").val();
// forming the queryString
var data = 'shout_tresc='+ shout_tresc;
// ajax call
$.ajax({
type: "POST",
url: "shoutek.php",
data: data,
success: function(html){ // this happen after we get result
$("#shout").toggle(500, function(){
$('.loader').show();
$(this).html(html).toggle(500);
$("#shout_tresc").val("");
$('.loader').hide();
});
return false;
}
});
});
});
For readability I removed your escapes. You've missed the preventDefault which prevents the form from being submitted.
You need to prevent the default action on submit button click:
$("#dodaj").click(function(event) {
event.preventDefault();
// your code
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Jquery post, response in new window
i have a table html in a page called results.php that looks like
GenID
ENSMUSG00000098791
ENSMUSG00000023441
ENSMUSG00000047431
results.php have this function
<script>
function contenidoCelda()
{
var table= $('#tabla_results');
cells = $('td');
for (var i=0,len=cells.length; i<len; i++)
{
cells[i].onclick = function()
{
var formData2 = new FormData(document.getElementById("formulario"));
formData2.append("gen_id",(this.innerHTML));
$.ajax({
type: "POST",
url: "test.php",
data: formData2,
cache: false,
processData: false,
contentType: false,
success: function(data)
{
alert(data);
window.open('test.php', '_blank');
}
});
}
}
}
</script>
i whant to use the data i send in the file test.php, not to return this to results.php, use in test.php, to generate the content dinamycally.
this is test.php
<?php
$data = $_POST['gen_id'];
system("mkdir $data");
echo "Hola";
echo $data;
echo '<xmp>';var_dump($data);echo '</xmp>';
?>
<html>
<link href="css/ui-lightness/jquery-ui-1.9.1.custom.css" rel="stylesheet">
<script src="js/jquery-1.8.2.js"></script>
<script src="js/jquery-ui-1.9.1.custom.js"></script>
<body>
<form>
<p id = "testing"> Test page </p>
<?php if($data == "ENSMUSG00000047751") {echo "Good";} else {echo "Bad";} ?>
</form>
</body>
so here in test.php, it must show Good, if i click that genid in the table
but it show Bad, and returns Good to results.php
the test where i create a dir, whit the genid i click works fine
what i must do?
In your $.ajax call, try setting:
$.ajax({
type: "POST",
url: "test.php",
data: "testing123",
cache: false,
processData: false,
contentType: false,
});
And see if dir test123 is created, and echoed back.
If not, then the problem is in these two lines, specifically with your definition of var formData2:
var formData2 = new FormData($('#formulario')[0]);
formData2.append("gen_id",(this.innerHTML));
Check for typing errors, such as the comma in place of the semi-colon:
var table = document.getElementById('tabla_results'), <-- THIS IS A COMMA. TYPO?
cells = table.getElementsByTagName('td');
Also, you have a mix of jQuery and javascript. Why not standardize on jQuery? For example, the two lines above would be written like this in jQuery:
var table = $('#tabla_results');
cells = $('td');
Much less typing, yes?
Also, I'm sure you have, but are you sure you've included a link to the jQuery library? Such as:
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
I think the problem is with the way you define formData2:
var formData2 = new FormData($('#formulario')[0]);
Resulting in formData2 not actually being FormData.
Try switching it to:
var formData2 = new FormData(document.getElementById("formulario"));
This should solve the data problem.
Edit: About the edit to your question, if you want to post the results to another page, there really is no need to use ajax. Just use javascript on form submit to add the additional field with the ID (if you cannot add it like a hidden field...) and use a normal form submit.
I have been researching for the last two days, and have found nothing.
structure:
index.php:
<head>
<script type="text/javascript" src="JS/jquery-1.6.2.js"></script>
<script type="text/javascript" src="function.js"></script>
</head>
<body>
<div>
<div>Show</div> *-->if I click this link data loads into DIV below by function.js without reloading*
<div id="producten"></div> *-->testpage.php loads here perfect,
the code of testpage.php makes by while loop other links.
Here I want to click on a link to load next data in div id=information
without reloading the index.php so the data in the first DIV stay visible
and I dont know how to do that*
<div id="information"></div> *-->testpage2.php have to load data from sql in this DIV*
</div>
</body>
function.js:
$(document).ready(function() {
$(".testcat").click(function() {
var testid = $(this).attr("id");
var datastring = 'id='+ testid ;
$.ajax({
type: "POST",
url: "testpage.php",
data: datastring,
cache: false,
success: function(res) {
$('#producten').html("<div class='loading'><img src='IMG/loading.gif' /></div>")
.hide()
.fadeIn(2000, function() {
$('#producten').html(res);
})
}
});
return false;
});
});
testpage.php and testpage2.php are PDO code for sql data.
You'll want to attach your click handlers with on so that dynamically added content still has the same ajax handlers available to them:
Add whatever information is needed to differentiate one click from the next, ie
<a href='...' data-resultdiv='production'
Then, cleaning up your handler a bit: I assume you want the ajax request to go to the href of the link, and that you want to show "loading" immediately (instead of waiting for the request to complete).
Finally, to cancel the anchor's default behavior of browsing to the page referenced by the href, you can return false;
$(document).on("click", "a", function() {
var href = $(this).attr("href");
var successDiv = $(this).data("resultdiv");
$('#' + successDiv).html("<div class='loading'><img src='IMG/loading.gif' /></div>");
$.ajax({
type: "POST",
url: href,
data: datastring,
cache: false,
success: function(res) {
$('#' + successDiv).hide().html(res).fadeIn(2000);
}
}
return false;
});
And of course if you only want this to run for certain anchors, you can put a selector on your call to on
$(document).on("click", "a.someClass", function() {
Apologies if this has been answered before (I couldn't find the answer when I searched the archives)
I've got a page protected by a password:
<?php
if($_POST['pw'] == 'pw')
{
//Page content
} else
{
//Display password form
}
?>
Within the page content, I've got another form, which I want to submit using jQuery, and have the following code:
<script type='text/javascript'>
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function()
{
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
</script>
<form name='form1' id='form1' action=''>
<fieldset>
<label for='input1' id='input1_label'>Input 1</label>
<input type='text' name='input1' id='input1' size='30' />
<input type='submit' value='Update / reset' id='submit' class='buttons' />
</fieldset>
</form>
<div id='#testResult'></div>;
However, clicking submit then sends the form to p1.php?input1=test (i.e., the data string is being sent to p1.php, not p2.php). If I edit the code and remove dataType:html and the 2 references of data2, then this doesn't happen (infact, nothing happens, so I assume that jQuery is submitting the data to the form). I've also changed the type to 'GET', incase the 2 POST requests on the same page were causing problems, but this didn't change the result.
What am I missing to get the information from p2.php (i.e. data2) and displaying it?!
EDIT
Thanks to a comment pointing out a typo, I've changed dataType: html to dataType: 'html' - this now doesn't cause the page to redirect to p1.php?input1=test, but once again, it doesn't do anything (when it should still be returning the value of data2)
EDIT 2
I've updated the code so dataString is now:
var dataString = $('input#input1').val();
dataString = 'var1='+dataString;
but this hasn't made any difference
For clarification, my p2.php just contains the following:
<?php
echo "<p>HELLO!</p>";
?>
EDIT 3
I made the changes to my code has suggested by Damien below; I get the alert of "works!" but still nothing seems to be returned from p2.php, and nothing is inserted into the #testResult div.
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function(evt)
{
evt.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: "someval="+dataString,
dataType: 'html',
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
$(function() {
$('#submit').click(function()
{
var dataString = $('#form1').serialize();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
success: function(data2) {
alert('works!'); // ADDED AFTER UPDATE
$('#testResult').html(data2);
},
/* ADDED AFTER UPDATE */
error:function(obj,status,error)
{
alert(error);
}
});
return false;
});
});
Edit:
In p2.php:
<?php
var_dump($_POST['pw']);
?>
In p2.php you then need to output ( using echo, for example) what you want to be returned as 'data2' in your ajax success call.
UPDATE:
Since you're Ajax request fires succesfully, that means either your post is not passed correctly, or you're not outputting anything. I've re-looked at your code and I saw this:
<input type='text' name='input1' id='input1' size='30' />
that means you're fetching the wrong $_POST variable!
Do this:
Since you're sending a name="input1", in your p2.php try with:
<?php
if(isset($_POST['input1'])
{
echo $_POST['input1'];
}
else
{
echo 'No post variable!';
}
And in your jquery success:
success: function(data2) {
alert(data2);
$('#testResult').html(data2);
},
That oughta work, if you follow it literally. In the remote possibility it won't work, forget AJAX, remove the javascript and do a normal post submitting with p2.php as an action of your form :)
I think you have to prevent the default action of the form.
Try this:
$('#submit').click(function(e)
{
e.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
The data should be formatted like this:
variable1=value1&variable2=varlue2
I also think you can remove the dataType property.
as part of my time isn't dedicated to PHP dev, I'm having an issue which is probably easy to solve, but having absolutely no logs (PHP logs, browser firebug logs...) I'm pretty stuck.
Here's my code; as I'm testing stuff, it's pretty raw.
The index.php file :
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// You may specify partial version numbers, such as "1" or "1.3",
// with the same result. Doing so will automatically load the
// latest version matching that partial revision pattern
// (e.g. 1.3 would load 1.3.2 today and 1 would load 1.4.2).
google.load("jquery", "1.4.2");
google.setOnLoadCallback(function() {
// Place init code here instead of $(document).ready()
$("#shrelock").submit(function(){
var url = $(this).attr('action');
$.ajax({
url: url,
success: function(data) {
alert(data);
}
});
return false;
});
});
</script>
<form id="shrelock" action='stats.php' method='get'>
<input type="text" name="url"/>
</form>
Now the stats.php file :
include("bitly.php");
if ( isset($_POST["url"]) ){
$urlToCheck = $_POST["url"];
$bitly = new bitly('myLogin', 'myKey');
print $bitly->shorten($urlToCheck);
}
I'm not sure what your question is, but I do see a few problems with your code.
The ajax request you perform uses GET while the serverside code seems to expect a POST
and also you forgot to send the 'url' parameter in the ajax call.
$.ajax({
url: url,
type: 'POST',
data: 'url=' + $('#shrelock input[name="url"]').val(),
success: function(data) {
alert(data);
}
});