Hello am implementing a jquery site and i dont want the user to wait for page reloading after every click so a use #p2 to navigate between pages. I use ajax to prevent page reloading and i get my parameter from a response.php page with $_GET method...after this i store the $_GET['value'] in a session in order to use it to the page2...but this work only if i refresh the page. Otherwise the session variable has the previous value before page reloading.
My question is simple...how to get the session latest value without page reloading...?
Or is there any way to pass parameters from page 1 to page 2 without reloading?
Thanks in advance
The code is shown below:
function send_an_article_id_to_php(an_article_id)
{alert(an_article_id);
$(document).on
(
"click", "#" + an_article_id ,function()
{
$.ajax(
{
type: "GET",
url: "../get_an_article_id.php",
data: { cmd2 : $(this).attr("id") },
success: function(response)
{
$("#response3").html(response);
}
} /*end of ajax }*/
);/*end of ajax );*/
}/*end of click event*/
);/*end of document*/
}/*end of function katigoria*/
Sessions have server side processing. You can simply sent request to server using ajax and modify or change session info there. After your desired result you can get print these values and send them back to client side.
You can print value in form of json and make html from these values on client side or simply you can make HTML in you ajax file, sent it to your client and place in your desired location using client side scripting.
Related
I have a page that has tabs on it. each of the tabs have a few forms on it. On the form, a user can set a filter. for example "Show me (10,25,100) result"
The when user enters a value, i fire off an ajax call to a php script that sets session variables
$_SESSION['filter'] = $_POST['filter'];
The success of the ajax call triggers the tab click to get to the form the user is on:
$.ajax({
type:"POST",
data:"filter="+filter,
url:"actions/Tickets/filters.php",
success:function(result){
$('#someTab').trigger('click');
}
});
The problem I am running into is if I
print_r($_SESSION);
on the page that the form is on, i do not see any changes to the $_SESSION['filter'] value.
What i think is happening is the ajax isnt waiting for the script to finish, so the SESSION var never gets set. asynch isnt an option. how can i acheive this?
How can i use an ajax script to call a php file to set SESSION variables then trigger a click event on nav tabs.
As you have stated in the comment that you set the session using:
$_SESSION['filter'] = $_POST['filter'];
Than, I think the issue is, when you set the session in php uisng an ajax call, than you can only get the updated session by using an another ajax call or after page refresh. So make an another ajax call and see what happens.
You cann't assign session in javascript because javascript occurs on client side and session stored at server side.
So , It's not possible you can use php variables in js like.
<?php
$_SESSION['filter'] = "foo";
?>
Then you can use this session variable in js. But you can't do vice versa. You can't assign session from js to php.
You can set value from js to html using jquery but this scenario isn't possible.
Edit :-
So, set session variable in filter.php.
$_SESSION['filter'] = "foo";
After then when result is retured reload the page. Because Page must be reload for session set. I'm not sure for it but may be it works.
$.ajax({
type:"POST",
data:"filter="+filter,
url:"actions/Tickets/filters.php",
success:function(result){
$('#someTab').trigger('click');
location.reload(); // reload the page
}
});
Ofcourse you cant assign like that because js is client side script & php is server side, you can assign php variable to js variable but not vice versa
You need to use this:
$_SESSION['filter'] = $_POST["filter"];
This post may help you:
Set php session via ajax
I have three different parts to my page. The first is a button, the second is a JS function (AJAX request) and the last one is a PHP script that is called by the AJAX request.
The PHP script is supposed to call a web service to process the data. Here is the content of the PHP script:
<?php
if(isset($_POST['forminfos'])){
$client = new SoapClient('URL');
$client->Function();
header('Location: localhost/page.php');
}
?>
The page is not redirected but when I check the console I can see that there is a GET with the localhost/page.php content.
//on button sumbit
var data=$('#forminfos').serializeArray();
$.ajax({
url: '../func.php',
data:data,
type: 'POST',
dataType: 'json',
success: function () {
},
error: function(){
}
});
I expected the page with the AJAX request to be redirected to 'localhost/page.php' but it is not.
The problem is that the file you are doing the redirect in is being called by AJAX. That means that although you are redirecting that request page, the actual page you made the ajax request from is not being redirected. The end of your ajax request results in the script you called being redirect not the page it is requested on.
If you only goal is to get to your destination in the header (localhost/page.php) then you could wait for the AJAX request to finish and do:
window.location.href = "localhost/page.php"
This uses javascript instead to redirect the page on the successful completion of your AJAX request.
Further reading:
Basic JS docs about window
Difference between window location and window replace
I'm trying to develop a plugin for the wordpress and i'm having a small issue with the session. I have created my own login page for my plugin and when user puts his username/password and press the login button an ajax request sends the data to a function to check if user details are correct or not. The function that the ajax is calling is stored inside my index.php of my plugin. Using the $_SESSION in the function that ajax is calling, i can print the variable that I want,which has been set inside another file. Then if the data are correct the ajax reloads the page. When the page is been reloaded the session no more exist. Does anyone knows how i can solve this problem? I implemented the plugin on a localserver which was working fine, but when i uploaded the project on a subdomain on a server, it stopped to working.
AJAX code
success: function(data) {
console.log(data);
if (data !='')
{
var obj = $.parseJSON(data);
if (obj.status == "ok")
{
location.reload();
}
}
Thank you
Have you tried using the .RememberState function with your ajax call? Typically this might be applied to a form (so if the form is partially filled out and a user refreshes the page their changes are preserved), but in theory I don't see why you couldnt use it on the document itself. Check out this link it might explain it more clearly
http://shaneriley.com/jquery/remember_state/
You'd want to do this before the call, and in the success callback, you should be able to use this RememberState to return to the active session you had before. If this isn't what you're referring to I apologize for misinterpreting your question.
I have a main page where you fill in some data. After you click on a link "create" it will call ajax to insert new record into mysql database (with data from main page). The mysql table where I'm inserting this new record has an auto_increment primary key and I need to know this key on page where the "create" link is redirecting. So to show it in a short simplified example I have something like this:
index.php has a link Create
index.php has also this jquery $("#create").click($.ajax({ url: "create.php", cache: false, data: { ... some data from index.php ... } }));
create.php inserts record into database and after that does this $_SESSION["id"] = mysql_insert_id();
new.php needs to get this id from $_SESSION["id"]
When I tried to call ajax (insert record) outside of click event (so immediately after the main page has loaded) before I actually clicked the link it worked perfectly. However this way it works kind of randomly. Sometimes it does sometimes it doesn't and it never ever worked in Google Chrome this way...
I'm using session_start() properly in the beginning of the documents so there's no problem in this.
Thank you very much for any help I'm struggling many days with this and at last I located that the problem comes from this ajax call position in click event but I have no idea how to fix it. I guess that I'm missing some knowledge about how exactly do page redirecting and click event work together with ajax.
First your session has to be started in the index.php page so new.php and create.php will receive the session ID in the session cookie. You could theoretically call $.ajax then change the window location right after it. However this doesn't guaranty you that create.php as finished execution (ie. created the line you want and insert the data you want into the session which should be stored in your database). This can result in a race condition which you are experiencing.
To fix this, you simply have to change your window URL in a function on Ajax call success like :
$("#create").click($.ajax({ url: "create.php", cache: false, data: { ... some data from index.php ... }, success: function() { window.location = 'new.php'; } }));
I have an index.html file which I want to run some jQuery when it is loaded. Essentially, I want to check to see if a user is already logged in based on some session variables.
So index.html will contain some jQuery which uses $(document).ready(function(){ });
In this function I want to just fire autheticate.php which checks to see if $_SESSION['user'] is set, if it is then it will redirect to home page otherwise it will redirect to login page...
how can I post in jQuery without having a html form? I just want to post to a url...
EDIT:
Based on #jondavidjohn's answer I changed my web app so that it uses index.php to check sessions:
<?php
session_start();
if(isset($_SESSION['username'])){
//go to home page
header('Location: ...home.html');
}else{
//go to login page
header('Location: ...login.html');
}
?>
It is surely possible doing this with javascript, but it is not secure at all...
You need to be checking at the server level for $_SESSION['user'] before you even send the content to the browser...
My answer would be to do the checking / redirecting with PHP before anything gets sent to the browser, it will be less complicated and more secure...
The reason a javascript solution is insecure is that you are relying on a technology that resides and is controlled by the client to control access to protected areas.
You can use $.post(url, params), where url is a string and params is a hash with your post data.
$.post("/authenticate.php",null,function(data){
// do something based on response returned
if($data){alert("authenticated");}
else
alert("not authenticated");
});
in your php file
if(isset($_SESSION['user']))
{
echo true;
}
else
return false;
Use $.post() to post data via AJAX to a page. Doing it this way won't allow the PHP script to redirect the user, you'll have to java JavaScript redirect them.
$.post('/path/to/page.php', {userID: 5}, function(data){
// Use window.location to redirect
});
Or, you can create a "fake" <form> element, and post that.
var $form = $('<form/>').attr({
method: 'post',
action: '/path/to/page.php'
});
var $input = $('<input/>').attr({
name: 'userID',
type: 'text'
}).val('5');
$input.appendTo($form);
$form.submit();
I suggest you take #jondavidjohn's advice, and have PHP redirect the user before the page is sent to the browser. That's much more secure.
Why bother with the AJAX request? Since you're building the page with PHP, just have PHP embed some variables in a JavaScript block:
<script type="text/javascript">
var is_logged_in = <?php echo $_SESSION['logged_in'] ? 'true' : 'false' ?>;
</script>
This'd save you an HTTP round-trip to retrieve data you already had available.