Jump to content
ryan

How to work with AJAX driven content in ProcessWire

Recommended Posts

when i change the menu links to target='_self' its working, is there any way to load without target='_self'.

Share this post


Link to post
Share on other sites

Check your javascript error console. There is a 404. Your AJAX is trying to load the URL with a period "." appended to it. I'm guessing you've got an extra period somewhere in your javascript. I'd also suggest adding an extra slash to the end (to avoid an unnecessary 301), unless you've specifically disabled slashes in the template's URLs tab. 

GET http://webking.gr/web_design/website-web-design-web-development. 404 (Page Not Found)  

Note the period at the end of the URL above.

Share this post


Link to post
Share on other sites

Thank you Ryan! i will look for the error you mention.

Share this post


Link to post
Share on other sites

Just to be on the safe side I would need to know whether AJAX page load can lead to problems with multilingual sites and a language switcher.

Haven't done a lot of AJAX so far and just wanted to clarify if this is possible on a multilingual setup without too much of a hassle.

Thank you

gerhard

Share this post


Link to post
Share on other sites

As far as I have noticed with my projects there are no problems with that. I store the choosen language in session and at the beginning of a respond in (head.inc or _init.php or something that like) I do a language check. So this is called with all requests, regardless of GET, POST, AJAX or whatever. It is no difference.

EDIT:

And regardless if you store it with a session or not, the urls you call in your ajax request will point (or should point) to the urls of the actually choosen language variation: if en is default your url could be "/parentpage/subpage/" and if you have a language de it would/should be "/de/parentpage/subpage/". Only the homepage "/" is different, that's why I use session and language checking.

Edited by horst

Share this post


Link to post
Share on other sites

Hello @ all,

I use a login form which can be loaded via ajax from every page in a bootstrap modal or it can be reached directly with a link to a login page.

My problem ist that the login and the redirect doesnt work in the modal, but it works on the login page (with the same code). Is there a special way necessary to login from an ajax loaded login form.

MQMS2hj7qN.gif MQMS2hj7qN

As you can see the user will not be logged in and not redirected to the profile page.

Maybe someone has done something similar and struggled with this problem too.

Best regards

Share this post


Link to post
Share on other sites

I guess you need to reload the page you're actually on and not the one you call with ajax. If so, send back a 'success' message (json) from the login page (from ajax) and if you got this on the login page, do the redirect with js (location.reload() or location.href).

  • Like 3

Share this post


Link to post
Share on other sites

Hello tpr,

if I press the login submit button from the ajax loaded page the page I am actually on will be reloaded (not the page inside the modal). Its my first attempt with ajax and login so I dont know how to get a success message from the ajax loaded login form.:-X

Share this post


Link to post
Share on other sites

If I get it right these pages are in one applicaton (and not on a remote server). You would need to identify what causes the page reload, I guess there's (PHP) redirect somewhere. Instead of that you should do something else.

Using an iframe wouldn't do here? The iframe won't close in a modal unless the user clicks to close.

  • Like 1

Share this post


Link to post
Share on other sites
1 hour ago, tpr said:

If I get it right these pages are in one applicaton (and not on a remote server).

Yes you are right. Now I understand it a little bit better. The page reload takes place after pressing the submit button of the login form - this is the reason for the page reload. But it seems that the the form will not be validated on the serverside, because the login process doesnt work. I will take a closer look at what happens after pressing the button.

 

2 hours ago, tpr said:

Using an iframe wouldn't do here? The iframe won't close in a modal unless the user clicks to close.

Thats what i do not want - I will dive more into Ajax because I start loving it^-^

Share this post


Link to post
Share on other sites

Then start with catching the submit event wth Js, and start the Ajax call manually. But I guess you are already there. :)

  • Like 2

Share this post


Link to post
Share on other sites

Hello tpr,

thanks for your help! I got it working with this code:

<script>
$("#mainlogin-form").on('submit', function(e){
    e.preventDefault();    
    $.ajax({
  type: "POST",
  url: "<?php echo $pages->get('template=login')->url;?>",
  data: $("#mainlogin-form").serialize(),
  success: function(data){
                    window.location.href = "<?php echo $pages->get("template=profile")->url;?>";
                }
});
    
    return false;
    });
</script>

For all others who are interested in:

First step: I prevent the page reload with e.preventDefault() - this is necessary to prevent the reload, otherwise you will not get logged in

Second step: I made a Ajax request to my login template, where the form will be processed (validation stuff, login process,...)

url: the url to my login page

data : serialize all the form inputs that should be sent with the Ajax request.

success: if all is alright then force a redirect to the profile page

Best regards

 

  • Like 4

Share this post


Link to post
Share on other sites

Looks fine, though perhaps you can add an error checking too (not only success). I would perhaps use httpUrl() instead the relative url, especially for the js location.href - some browsers may choke on that.

  • Like 1

Share this post


Link to post
Share on other sites

Thats true! I havent added it because username and password will be checked first in real time with an ajax request and it is only possible to click the submit button if everything is fine. If username and password dont match it is not possible to click the button and proceed.

The second validation (not really necessary) takes place on the server with the form data submitted via Ajax

 

Share this post


Link to post
Share on other sites

Sh*t happens! You can't make for sure that there will be no errors, even if there was no error getting the username/password a second ago.

Share this post


Link to post
Share on other sites

I have added it after success

  error: function(data){
                    alert('error');//or whatever you want
                }

 

Share this post


Link to post
Share on other sites

Now everything works fine :)

Here is a small video to demonstrate the ajax login process for others who are also interested in creating an similar login process. Finally I have decided to redirect to the same page instead to the profile page because I think it is much more comfortable for the user.

The form will be loaded via ajax. All inputs (username, password) will be checked in real time against the database. If everything is correct, the user is able to click the button and the login process starts. After finishing the login process I use a get parameter in the url to show a success message.

Best regards

IdnLDoD0CT.gif

  • Like 3

Share this post


Link to post
Share on other sites

hi form i have this problem

when i post in ajax in https://www.ramcom.be/beveiliging/bewakingscamera-camerabewaking/

function menucard_AddToBasket(formId) {
  $.post(window.location.hostname + "/xHttp/Basket.php", $('#'+formId).serialize())
    .done(function( data ) {
      $('#ibasket').html(data)
      updateUtilitybarBasketBtn();
	});

ajax page is www.ramcom.be/xHttp/Basket.php

is this to good way code above?

thanks by advance.

<a href="https://www.ramcom.be/beveiliging/bewakingscamera-camerabewaking/" rel="" target="_blank">camerabewaking</a>

Share this post


Link to post
Share on other sites

Has anyone built an autocomplete / autosuggest search in the frontend with PW? I found a few threads, but they're mainly focussing on PageAutocomplete.

I got a search form already which is working fine (regular HTML), but how do I build an index that I could use as JSON source? Would it be wise to create a cron job to re-build the index (performance)? The system would be used by a small number of users (max. 1-2 dozen at the same time). There are about 1200 pages and 4 dozen fields I search through.

I'd appreciate suggestions / links.

Share this post


Link to post
Share on other sites

Hello @dragan,

here is a tutorial by me about this topic:

Regards, Andreas

  • Like 3

Share this post


Link to post
Share on other sites

Thanks @AndZyk

Thanks for your tutorial!

I actually found your thread too, shortly after posting here. I think I did everything right, but strangely, the JSON never returned anything. No JS or PW errors either.

Today I realized I had an old version of Pages2JSON installed, so I updated it. Unfortunately the update didn't keep my fields in the settings. When I get some time to try it again, I'll post back here.

 

Share this post


Link to post
Share on other sites

Actually, I tried it again, and now get at least some output... but not really what I expected:

<br /><b>Warning</b>:  Missing argument 1 for Pages2JSON::___getFields(), called in /home/xxxx/www/xxxx/xxxxxx/site/assets/cache/FileCompiler/site/modules/Pages2JSON/Pages2JSON.module on line 182 and defined in <b>/home/xxx/www/xxx/xxxxx/site/assets/cache/FileCompiler/site/modules/Pages2JSON/Pages2JSON.module</b> on line <b>185</b><br />

o_O

Share this post


Link to post
Share on other sites

Hello @dragan,

happy to hear that you find this tutorial useful. At the time of writing this tutorial I didn't knew how easy you can output your own JSON without a module.

Currently I don't need the Pages2JSON module anymore, but instead output the JSON inside my search template like this:

<?php
if ($config->ajax) {

	$selector = [
	"title|and|more|fields%=" => "",
	"template!=" => ["templates", "to", "exclude"],
	"has_parent!=" => 2
	];

	$matches = $pages->find($selector);

	$results = array();

	foreach ($matches as $match) {
		$result = array(
			"title" => htmlspecialchars_decode($match->title),
			"url" => $match->url
			);
		$results[] = $result;
	}

	header("Content-Type: application/json");
	echo json_encode($results);

	return $this->halt();

} else {

	// Your regular template

This way you build your own array with all necessary keys and then encode them as JSON. ;)

Regards, Andreas

  • Like 2

Share this post


Link to post
Share on other sites

Thanks for your help. I now removed the Pages2JSON module altogether.

If I allow display in the browser, i.e. remove if ($config->ajax) I can see the JSON neatly and quickly displayed in the browser.

However, When using it in my search-form, it's not doing anything. It calls my autocomplete page, but when I check the contents in Google Chrome > Network > XHR, it's always empty. Status code 200, but no content.

My JS looks like this:

	var actionURL = '<?=$autompleteURL?>'; // Save form action url in variable
	
	$.typeahead({
		input: '#q',
		hint: true,
	    dynamic: true,
	    debug: true,
		display: ["title", "project_desc_short"],
		source: {
			url: actionURL // Ajax request to get JSON from the action url
		},
		callback: {
			// Redirect to url after clicking or pressing enter
			onClickAfter: function (node, a, item, event) {
	//          window.location.href = item.url; // Set window location to site url
	//					console.log(item.url);
			}
		}
	});

I've added dynamic: true + debug: true hoping it would give me some hints, but I don't get JS errors either. Do you have any idea what I've been missing?

Share this post


Link to post
Share on other sites

I have tested your JS it is working fine for me. The fact that your input makes an Ajax request (even if it is empty) is also a good sign. With the debug option set to true I also don't get any informations inside the console, probably because it is working.

You could try to make an regular Ajax request and echo a static response first to test. Also you could try to exactly copy & paste my example from the tutorial mentioned above. ;)

Lastly I hope you didn't have exactly copied & pasted my Ajax example, because the selector in there is just an example and doesn't really work. :lol:

If you don't get any further, you can PM me more of your code or an link, in case your site is online.

  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...