I have the message-block in the header of my site. When a user clicks "close msg", the message should disapear and can't be seen during current user session.
So I decided to use jQuery Ajax:
$('#lang-msg .close').on('click', function(event) {
event.preventDefault();
$.ajax({
url:"remlmsg.php",
type:"POST",
data:"id=2,myajaxquery=true ",
success:function(html){
console.log(html);
$('#lang-msg').fadeOut(300,function() {
$(this).remove();
})
}
})
})
And in remlmsg.php I have only code, which defines new session variable:
$_SESSION['langmsg'] = 'hide';
echo $_SESSION['langmsg'];
In the header.php file I check if $_SESSION['langmsg'] is undefined.
if (!isset($_SESSION['langmsg'])) {
if ($sLanguage == 'ru') {
echo '<script type="text/javascript">
$( function() {
showLangMessage("en");
})
</script>';
}
}
And it says always true! But when I print request data in ajax function it displays 'hide'.
Explain to me, please, where I did mistake.
P.S.
Tested on local server (latest WAMP)
You need to have session_start() declared first. Otherwise you'll only edit a local variable that isn't stored anywhere.
Actually the problem you're having is that ajax calls will have a different session id, which has to do with the headers sent/received by both sides.
Try generating some javascript with PHP like:
var phpSessionId='<?=session_id()?>';
then in your remlmsg.php add this to the very top:
if(isset($_POST['session-id'])) session_id($_POST['session-id']);
session_start();
Finally in your ajax call use:
data:"id=2,myajaxquery=true,session-id=" + phpSessionId,
That should solve your problem.
Related
I've started using ajax requests recently. I am making a mobile web application where I am to the request for data on PHP side server script. The javascript function is to automatically execute when the user navigates to the page. But the script seems not to run until I refresh the page, here is my javascript code.
<script>
$( document ).ready(function(){
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString();
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
function requestContent() {
var date = new Date();
$.ajax({
type:'POST',
url:'php/app/adminTimeline.php',
data:{
date: date.yyyymmdd()
},
success: function(data) {
if (data == '') {
alert("No data found!");
} else {
// $("#loading_spinner").css({"display":"none"});
$('#timeline-content').prepend(data);
}
},
error: function(data) {
// $("#loading_spinner").css({"display":"none"});
alert("Something went Wrong!");
}
});
}
window.onload = requestContent();
});
</script>
The document.onready method and window.onload the method seems not to be working too.
Ps: I have the Jquery library linked in the header too.
Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
https://learn.jquery.com/using-jquery-core/document-ready/
Also you're calling requestContent()
window.onload must be function, not returning value.
$(document).ready(function(){
// here you ajax
}
https://jsfiddle.net/cqfq5on5/1/
The code window.onload=requestContent(); will execute when the window loads, not necessarily when the entire document has loaded.
However where you create the date object, uses this, which executes after the document is fully loaded
$(document).ready(function(){
//Code
});
This means, that the POST request will be made once the window loads, which is before the document is fully loaded, thus, that date object will not exist until the page is refreshed, at which point the Javascript was likely cached. Also another answer (#sagid) pointed out, window.onload cannot be a returning value but must be a function.
i.e.
window.onload=function(){
//Code
};
This means, your solution is to change window.onload=requestContent(); to
$(document).ready(function(){
requestContent();
});
Good luck!
i have a page in php to execute query. when i need the parameter from another page with session using jquery. so, how to set session in php from session in jquery. please check my code and give me solution. thanks...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://code.ciphertrick.com/demo/jquerysession/js/jquerysession.js?d56ac9"></script>
<script>
$(document).ready(function(){
var sDecode = $.session.get("sesDecode");
alert(sDecode);
});
</script>
<?php
include('connection.php');
$content= ==> how to get " sDecode " ???
$upd = mysql_query("UPDATE t_modules set content='$content' where id_t_modules='3'") or die(mysql_error());
?>
You can use ajax to send parameter to a php file like this
$.ajax({
url: "connection.php",
data: "Session="+$.session.get("sesDecode"),
type: "POST",
dataType: 'json',
success: function (e) {
console.log(JSON.stringify(e));
},
error:function(e){
console.log(JSON.stringify(e));
}
});
Note that both solutions needs you to check the input since the user could potentially modify it.
Using Ajax
The best way to get sDecode is probably to send it via jQuery.post() (AJAX) to a PHP page that will register the session value (after doing the appropriate checks to it).
$.post('session.php', { d: sDecode }, function (response) {
alert(response);
});
and you get it in PHP via :
$sDecode = $_POST["d"]; // Please test the input here!
You might have to use .serialize() and then unserialize it in PHP depending on the content and how you treat it.
Using Redirection
You can simply redirect to a page and transmit it directly as a GET value:
window.location.href=”session.php?d="+sDecode;
Then on the session.php page you would read it using this code :
$sDecode = $_GET["d"]; // Please test the input here!
You can have PHP fill in the Javascript variable from the session variable.
<?php session_start(); ?>
<html>
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
var sDecode = <?php echo json_encode($_SESSION['sDecode']); ?>;
alert(sDecode);
</script>
PHP execute before Jquery so use ajax after get the parameter from session to do your query
I have a communication problem between home.php page and user.php page.
on Homepage there is link for Log out
<span class="log_out"> <a id="logOut">Log Out</a></span>
When a user click this page ajax call will be started
Here is my ajax call
<script>
$( document ).ready(function() {
$( "#logOut" ).click(function() {
$.ajax({
url: 'class/user.php',
data: "logout=1",
success: function(data) {
$('body').append(data);
}
});
});
});
in user.php I have this
<?php
if(isset($_GET['logout'])){
echo "alert";
$_SESSION['user'] = 0;
}
?>
When I click logout, alert is being appended in body, but session variable was not changed at all.
I dont know what's going on here.
You need to add session_start(); to the top of your user.php file and also debug with the echo after a session is set, otherwise you'll get the warning you're getting at the moment.
if(isset($_GET['logout'])){
if(!isset($_SESSION))
{
session_start();
}
$_SESSION['user'] = 0;
Print_r ($_SESSION);
}
I found solution thanks for helping guys, I just need to add session validation on my if else clause, although I have this validation on top of the page, when I added it inside the function, problem fixed
I am trying to reset a session array in php with a function in jquery using a button. I would use a submit but I don't want the page to refresh. I tried to send a $.post request leaving the variables and return blank, and then sending a variable so I could use $_session[''] = array() but none of it worked. I have searched and can't find much about it just a lot on sending strings.
OK this is very simple to stop the page from refreshing you need to tell js to disable the default event i use jquery for this here is my code
Html & js
<html>
<head>
<title>Reseting a PHP $_SESSIO array with jquery function</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
function sessRest(){
$.post("rest.php", {x: "9845621"}).done(function(data){
alert("States: " + data);
});
}
$(document).ready(function(){
$("#target").click(function(event){
event.preventDefault();
sessRest();
});
});
</script>
</head>
<body>
<div id="main">
Click to rest me
</div>
</body>
</html>
php code rest.php
<?php
session_start();
(string)$data = $_POST['x'];
if($data == "9845621"){
$_SESSION['gx'] = array();
return $_SESSION['gx']; //return the empty array to js
}else(
return "error";
)
?>
I hope this helps .
User below jquery to submit to php code
var requestData = { param: "value"};
$.ajax({
url: your_url/session_change.php,
type: "post",
dataType: "json" or what ever,
data: your_data,
success: function (data) {
}
});
You can end the session successfully on server side with an ajax call, but apart from reloading the page, you're not going to clear what information was loaded already on client side. The session information wont be there once you do reload, but there is no way around that.
You can, however, emulate what you want to do with javascript.
When you load your session information, echo it to the page as javascript variables, then you have full control on client side. Just beware of echoing sensitive information like passwords, obviously.
try this:
your html file should contain this jQuery file:
$('#button').click(function(e){
e.preventDefault();
jQuery.ajax({
url: 'http://yourwebsite.com/session.php'
}).done(function(data){
if(data=='reseted'){
//do anything...
}
else {
//do anything...
}
})
});
and in your session.php file:
<?php
session_start();
session_unset();
if($_SESSION == FALSE){
echo 'reseted';
}
else echo 'no';
?>
the answer was
jquery $.post('reset.php');
in reset.php
$_SESSION['products'] = array();
?>
this reset my session array when the reset button was clicked with no page refresh...
I had done this originally and forgot to include my core.php in the reset.php which contained my start session()..
Thank you all for the help though.... great suggestions
Why doesn't the following pick up the form? All it does is just to do a normal PHP post without throwing any errors...
I'm using blockUi on this as well, hence block/unblock.
$(document).ready(function(){
$("input.update").click(function(){
var str = $(this).parent().serialize();
$(this).parent().parent().block({ message: "<span class=\"loading\"><img src=\"<?php echo $siteUrl ?>/admin/template/images/loading.gif\" alt=\"loading...\" /><p>Updating...</p></span>" });
$.ajax({
type: "POST",
url: "forms/update.php",
data: str,
success: function(){
$("div.edit_box").unblock();
$("div.edit_box").append("<span class=\"success\">This has been updated!</span>");
}
});
return false;
});
});
This is my first attempt at using jQuery's Ajax functionality so please bear with me.
("input.update").click(function(){
should be
$("input.update").click(function(){
Since it seems you're only using the 'success' callback of post you could use the .post method, which is a bit easier on the eyes. Also you can put those block calls inside ajaxStart and ajaxStop. To me it's neater.
The $(this).parent().parent().block seemed wrong to me, I changed it to reference the same element that is used for unblocking. I'd also be checking the output of the PHP script, to make sure that whatever you are 'updating' actually is updated (just echo XML from PHP and you'll see it on your console log).
$(function() {
// Apply click handlers to anchors
$("input.update").click(function(e){
// Stop normal link click
e.preventDefault();
var str = $(this).parent().serialize();
// Send request
var action = "forms/update.php";
$.post(action, {data:str}, function(xml) {
console.log(xml);
$("div.edit_box").append("<span class=\"success\">This has been updated!</span>");
})
});
// Adds a wait indicator to any Ajax requests
$(document.body).ajaxStart(function() {
$("div.edit_box").block({ message: "<span class=\"loading\"><img src=\"<?php echo $siteUrl ?>/admin/template/images/loading.gif\" alt=\"loading...\" /><p>Updating...</p></span>" });
}).ajaxStop(function() {
$("div.edit_box").unblock();
$("div.edit_box").append("<span class=\"success\">This has been updated!</span>");
});
});