Jump to content
celfred

$session variable disappeares when Ajax loaded ?

Recommended Posts

Hello,

I'm facing a weird issue here. I have a page loaded with this code inside (my comments in line ends) :

if ($session->allPlayers) { // Set in a head.inc file. I have also a $session->set('allTeams', $allTeams); in my head.inc
  $allPlayers = $session->allPlayers;
} else {
  $allPlayers = getAllPlayers($user, false);
  $session->set('allPlayers', $allPlayers);
}
bd($session->getAll()); // HERE, I get a number of 11 variables which is what I expect

In the same page, I have a link pointing to ajaxContent.php that loads stuff via Ajax.

I just write this in my ajaxContent.php to test :

bd($session->getAll()); // HERE, I get only 9 variables. All my newly set $session variables ($allTeams and $allPlayers) are not conveyed to ajaxContent.php ???

Would you have any idea why is that ??? Another thing : I have a $session->headMenu set in my head.inc, and this one works fine. I can retrieve it in my ajaxContent.php page.

I've tried cleaning all caches but it doesn't change anything 😞 

At first, I expected it to be a 15-minute update to my site... It turns out to be a 2-hour issue and I'm still  stuck.

Thanks for your ideas ! 

Share this post


Link to post
Share on other sites

What does getAllPlayers() do? Does this contain a selector with permission access? Perhaps checking in a incognito screen to check if you get both scenarios the same variables.

Share this post


Link to post
Share on other sites

Thanks for your concern @arjen. I appreciate your help.

35 minutes ago, arjen said:

What does getAllPlayers() do? Does this contain a selector with permission access?

It doesn't do much except a $pages->find("template=player, team=$selectedTeam") according to the logged in user.

But your comment made me think of another test. I simplified by wroting :

 $session->set('allPlayers', 'test');

But I get nothing on my ajaxContent.php page... $session->getAll() lists previously set variables only.

So I kept trying things and went on delogging my user and trying to re-log and noticed it didn't work as expected any longer. So I switched to my dev branch and logging in functionality came back. So I started inspecting my code and here's what I noticed :

  • If I put this in my head.inc :

$session->set('allTeams', 'test');

Everything works as expected. No more issue anywhere.

  • If i put this instead :

$session->set('allTeams, $allTeams);

$allTeams being a pageArray that the actual logged-in user receives from a $pages request (actually the different classes for the logged-in teacher), my logging-in system doesn't work any longer and I get my initial issue. Actually, I interpret this as an impossibility to update in any way my $session...

 

So I'm slowly stepping forward, but I still don't understand anything about this behavior...

You also mentionned :

52 minutes ago, arjen said:

Perhaps checking in a incognito screen to check if you get both scenarios the same variables.

And I have no idea of what that means, sorry... If incognito screen is a 'guest' view, for the moment, I just want a specific role to have this functionality.

I stay tuned for explanations 🙂 

Share this post


Link to post
Share on other sites

Oh, I've just re-re-re-re-read the API documentation, and maybe I've seen something :

Does $session->set($key, $value) only work with strings for $value ? Maybe this is my issue trying to pass a PageArray ???

And then, how would you do that, then, passing a 'big' pageArray without having to do the DB request again ? I thought I could do it through $session ?

Share this post


Link to post
Share on other sites

You are safe to store a regular array in the session variable. See this old thread: 

I would worry to much about performance since only looking up ID's is very fast since you are not joining.

  • Like 2

Share this post


Link to post
Share on other sites

@arjen : Thank you so much. This old thread gave me the explanation I needed. That's cool.

For the moment, I did how @ryan suggested in the above-mentionned thread and it works just fine 🙂 

So again : thanks a lot !

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Brian Scramlin
      I just wanted to share that I added an AJAX-powered gallery to an artist website that I developed and host: https://jackpinecreations.com/gallery/

      There were two things that frustrated me about creating this. Perhaps you can show me a better way.
      1. After creating my processing script, which I placed under /templates/scripts/get-items.php, I realized that I would get a 403, due to ProcessWire's routing and security. This forced me to have to create a template and page for this little script. This was frustrating simply because it seemed unnecessarily confusing. But worse, see #2.
      2. I usually use config.php to prepend and append each of my templates with a head.inc and foot.inc, which keeps my templates easy to use and I don't have to go and use the GUI to do so on each template separately. However, since I realized I needed to create a new template and page so as to access it, whenever I sent POST params to it, I would get the header and footer along with it!!! I could find no workarounds and had to remove the pre/append calls in config.php and use the GUI on each template individually.  
      Code Below if you're interested:
      HTML and JavaScript (forgive my sad JavaScript skills, I know this can be tightened up)
      <!-- Begin Grid --> <div class="container mt-4"> <div id="gallery" class="row"> <?php foreach ($page->children("limit=9") as $child): ?> <div class="col-6 col-md-4 gallery-item"> <a href="<?= $child->url ?>" title="View <?= $child->title ?>"> <img class="gallery-item" src="<?= $child->item_featured_image->size(640, 640)->url ?>" alt="<?= $child->title ?> Image"> </a> </div> <?php endforeach; ?> </div> </div> <!-- End Grid --> <div class="center-block text-center"> <button id="get-more-items" type="button" name="get-more-items" class="btn-vintage">Load More</button> </div> <script type="text/javascript"> var buttonGetItems = document.getElementById("get-more-items"); var indexStart = 0; buttonGetItems.addEventListener("click", function() { indexStart += 9; $.ajax({ url: '<?= $pages->get(1186)->url ?>', type: "POST", dataType:'json', // add json datatype to get json data: ({page_id: <?= $page->id ?>, index_start: indexStart}), success: function(data){ console.log(data); if (data[1]) { //for each element, append it. $.each(data, function(key, value) { $("#gallery").append(value); }); } else { $("#get-more-items").after('<p class="center-block text-center">There are no more items to load.</p>'); $("#get-more-items").remove(); } } }); }); </script> Processing Script
      <?php $items_array = []; $i = 0; foreach ($pages->get($input->post->page_id)->children->slice($input->post->index_start, 9) as $child) { $i++; $items_array[$i] = "<div class='col-6 col-md-4 gallery-item'> <a href='$child->url' title='View $child->title'> <img src='{$child->item_featured_image->size(640,640)->url}' alt='$child->title Image'> </a> </div>"; } echo json_encode($items_array); I love ProcessWire for hundreds of reasons, but I've been using AJAX more and more, and I'm not liking having to create templates to access scripts. 
      Any advice?
    • By louisstephens
      So I have a template called "development" where I am testing out a few ideas etc set up on a local mamp server. I also have a page called "ajax" using a template called ajax. From my development template, I am posting a form using ajax and all is working quite well:
      $('.test').click(function(event) { event.preventDefault(); redirectUrl = $(this).data('redirect'); var data = { firstName: $("#firstname").val(), lastName: $("#lastname").val(), email: $("#email").val(), phone: $("#phone").val(), redirectUrl: redirectUrl }; $.ajax({ type: "POST", url: "localhost:8888/sandbox/ajax/form/", data: data, success: function() { console.log(this.data); top.window.location = redirectUrl; }, failure: function() { console.log(this.data); } }); And in my ajax template:
      if($input->urlSegment == 'form'){ if ($_POST) { //handle the post } } The redirectUrl is a data attribute I added in to the button (that launches the form in a modal) that pulls in from a field in processwire. Everything works just fine locally, but when I export everything to a live site it fails. It will work 1 time and redirect, but if you go back to resubmit, it submits the data but won't redirect. Can anyone see any glaring issue here, or have a better way around this?
      ------------------------------
      So, it turns out the request to /ajax/form/ was being canceled. It still handled the POST request, but never sent back a 200 to show "success". Adding in 
      return false; at the end of my .onclick solved the issue. It is strange though as I have never had this issue before.
    • By rushy
      Hello. I have recently adopted PW markup regions and really like this way of working. However, I am also trying to learn how to use Ajax and I am not sure of a good way to use the two together. Has anyone got any experience, tips or hints on using them together? For ajax -  I've used a simple scheme where I have a "webservice" template and page that handles Ajax requests and returns the appropriate content wrapped with some markup for the requesting page. I have markup regions enabled and all my pages (bar webservice) include a _main.php which brings in the headers, a default body and the footer. My javascript intercepts the page links and does my ajax call to webservice and that sends back the appropriate markup which is then placed by in the div #body defined in _main.php.  Does this seem a reasonable way to work? I guess I am looking for some advice before I invest too much time going the wrong way!
      Any guidance, remarks,  comments, or a nudge in the right direction greatly appreciated.
      Paul
    • By gerald
      In my frontend I would like to implement a small AJAX-solution, but it does´nt work. For example:
      template/js/ajax.js: contains jquery-ajax-snippet with click-function like this: $.post('ajax.inc', function(e) {});
      template/ajax.inc: contains db-query with HTML-output
      template/home.php: contains div-element for the ajax-response, e.g. <div id='result'>...ajax-response...</div>
      It seems, PW does´nt allow database-requests via AJAX (jquery). I know the post from Ryan "How to work with AJAX driven content in ProcessWire". But this solution requires a completely new template-concept. I only need a simple solution for a small ajax-db-request.
      Thanks to all
    • By Peter Knight
      I have a demo site which I moved to a new VPS for client testing
      We noticed that leaving a page open and then revisiting the site can result in a 25 second(ish) to load time and will then throw a 500 Error.
      The hosting guys had a look and confirmed that the server is fine but the issue could be related to authentication or sessions.
      We are running Page Protector and ProCache so I wondered if there were any known bugs here and any recommended actions.
      My actual PW log doesn't show anything but the server log has plenty of these
       
      2018-12-06 08:14:00 Error xxx.141.1x.101 500 POST /who-we-are/ HTTP/1.0     1.58 K Apache access 2018-12-06 08:14:45 Warning xxx.141.1x.131   mod_fcgid: read data timeout in 45 seconds, referer: http://demo.abc.not/who-we-are/       Apache error 2018-12-06 08:14:45 Error xxx.141.1x.131   End of script output before headers: index.php, referer: http://demo.abc.not/who-we-are/       Apache error 2018-12-06 09:03:18 Error xxx.141.1x.131   2614#0: *667 recv() failed (104: Connection reset by peer) while reading response header from upstream       nginx error Thanks
      P
×
×
  • Create New...