Jump to content

anybody could show an example of how to use $config->ajax ?


adrianmak
 Share

Recommended Posts

On 10/29/2018 at 8:00 PM, modifiedcontent said:

it only gives one part and assumes that the rest is obvious.

Really?

On 10/29/2018 at 2:01 AM, kongondo said:

It sounds to me as if your struggle is not with ProcessWire, but with JavaScript, specifically, JavaScript + Ajax, rather than ProcessWire + Ajax.

Does this ring a bell?

On 10/29/2018 at 8:00 PM, modifiedcontent said:

An 'author' var was sent by the Ajax call. How? I still don't see how it all works together.

.....

On 10/29/2018 at 2:01 AM, kongondo said:

I know you said you are frustrated by the 'Google-about-Ajax' suggestions, but I will tell you the same. A good tutorial/intro to Ajax would probably cost you about 30 minutes of your time :-).

What about this one?

  • Like 1
Link to comment
Share on other sites

This is a self-contained basic example of how to use $config->ajax:

Spoiler

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

	$variable = $input->get( 'variable' ); 
	
	echo 'I feel triggered by '. $variable;
	
	return $this->halt();

} else {

include 'inc/head.php'; ?>

<body>

<h2 id=demo>Let jQuery AJAX Change This Text</h2>

<form id=demoform>
<input name=something></input>
<input type=submit value='Replace text by ajax call to same page'></input>
</form>

<?php include 'inc/footer.php'; 
}
?>

<script>
var jAjax = jQuery.noConflict(); 

jAjax(document).ready(function(){

    jAjax('#demoform').on('submit', function(e) { 
        e.preventDefault();  //prevent form from submitting
	
		var sometext = jAjax("input[name='something']").val();

        jAjax('#demo').load( '?variable='+encodeURIComponent(sometext) );
    });
});
</script>

 

Anyone can put this little demo in a template file and it works. Hopefully it helps other people who don't know Javascript or/and PHP well to understand how to work with Ajax in PW. Something like this is all I needed.

Getting the variable(s) ($_GET) and doing something with it - in this basic example just echo it - can also be done in a separate php file in your templates folder that you can include after if($config->ajax)

Here is a better example - mainly for my own reference...:

Spoiler

<?php 

if($config->ajax) {

echo $input->post('fieldone');
echo $input->post('fieldtwo');
    
	return $this->halt();

} else {
    
include 'inc/head.php';

?>

<body>

  	<form>
    <input type=text name=fieldone>
    <input type=text name=fieldtwo>        
    <input type=submit value=submit>
    </form>
    <div id=result></div>
    
</body>
    
<?php } ?>

<script>
var jAx = jQuery.noConflict();
    
jAx(document).ready(function(){
    jAx("form").on("submit", function(event){
        event.preventDefault();
 
        var formValues= jAx(this).serialize();
 
        jAx.post('', formValues, function(data){
            // Display the returned data in browser
            jAx("#result").html(data);
        });
    });
});
</script>

 

 

  • Like 1
Link to comment
Share on other sites

1 hour ago, modifiedcontent said:

Hopefully it helps other people who don't know Javascript or/and PHP well to understand how to work with Ajax in PW. Something like this is all I needed.

Great that you got it sorted 🙂. Your solution is a bit ironical though since you previously stated this:

On 10/28/2018 at 10:39 PM, modifiedcontent said:

Typically you'd want to send the call with parameters/variables (?) to a php script that does something with the vars and then returns something

 

...yet your example does not really do anything with the variables sent (except echo it back verbatim) ;

Since you've posted this in the forums with the aim of helping other people who may not be well-versed with JavaScript and/or PHP, I feel inclined to point out two things, lest  newbies pick up approaches that may not be best practice (some of which may potentially break their sites):

1 hour ago, modifiedcontent said:

$variable = $_GET ['variable'];

ProcessWire has an $input->get() method (and related ones) which has some advantages over using PHP $_GET. 

 

1 hour ago, modifiedcontent said:

echo 'I feel triggered by '. $variable;

There's two problems here:

One, you are not sanitizing your $variable and secondly, you are echoing it back directly to the browser as received by the input. As I pointed out earlier, we have $sanitizer->entities() for such uses. 

Edited by kongondo
  • Like 1
Link to comment
Share on other sites

  • 3 years later...

I'm doing

if ($config->ajax) {
	echo "THIS IS AJAX";
	$this->halt();
} else { 
	echo '<div id="content">';
	echo 'THIS IS MY REGULAR CONTENT';
	…
	echo '</div>';
}

and I use 

$config->prependTemplateFile = '_init.php';
$config->appendTemplateFile = '_main.php';
$config->useMarkupRegions = true;
$config->useFunctionsAPI = true; 

in the config.php

However, the site stills loads the entire page in the ajax response, which is not what I want of course, I get the header and menu etc where I render the response (result.innerHTML = response);

suggestions?

Link to comment
Share on other sites

16 minutes ago, dotnetic said:

do a `die()` instead of halt

Worth noting: https://processwire.com/blog/posts/processwire-2.6.8-brings-new-version-of-reno-admin-theme-and-more/#new-this-gt-halt-method-for-use-in-template-files

quote: "Now you can call return $this->halt(); from within any template file, and it will prevent further output from that template file (and anything that comes after it, like an appendTemplateFile). This enables output to stop, but PW's normal execution and shutdown process to proceed normally. Please note that return $this->halt(); must be called from directly within the template file, outside of any function or class scope."

  • Like 2
  • Thanks 1
Link to comment
Share on other sites

17 minutes ago, szabesz said:

Worth noting: https://processwire.com/blog/posts/processwire-2.6.8-brings-new-version-of-reno-admin-theme-and-more/#new-this-gt-halt-method-for-use-in-template-files

quote: "Now you can call return $this->halt(); from within any template file, and it will prevent further output from that template file (and anything that comes after it, like an appendTemplateFile). This enables output to stop, but PW's normal execution and shutdown process to proceed normally. Please note that return $this->halt(); must be called from directly within the template file, outside of any function or class scope."

Well, @fruid stated, that he already used halt and it did not work. I experienced the same (but I am also using Smarty Template Engine), thats why I use die() instead.

  • Like 1
Link to comment
Share on other sites

9 minutes ago, dotnetic said:

Well, @fruid stated, that he already used halt and it did not work.

What about the "X-Requested-With: XMLHttpRequest" header? The $config->ajax call requires that to be sent.

  • Like 4
Link to comment
Share on other sites

7 hours ago, fruid said:
$config->prependTemplateFile = '_init.php';
$config->appendTemplateFile = '_main.php';

However, the site stills loads the entire page in the ajax response, which is not what I want of course, I get the header and menu etc

In addition to the other very valid comments, this is what’s causing the problem as I understand it. ProcessWire will still prepend _init.php for Ajax requests unless you tell it not to. One way might be to wrap these two lines in an if-block in config.php. That will disable the prepend/append files for all Ajax requests, which seems reasonable:

if ($config->ajax) {
	$config->prependTemplateFile = '_init.php';
	$config->appendTemplateFile = '_main.php';
}

A more flexible approach may be to forego auto-append and just call those files explicitly when you want them.

To expand on @szabeszs comment, $config->ajax works by detecting the header “X-Requested-With”, which browsers don’t send by default. If you’re using XMLHttpRequest, you need to add it like this:

var request = new XMLHttpRequest();
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

If you use the Fetch API, there is a Headers() object you can pass: https://developer.mozilla.org/en-US/docs/Web/API/Headers

Jquery sends the header automatically, which is. I believe, why ProcessWire expects it.

  • Like 4
Link to comment
Share on other sites

@fruid I'm sorry for providing only small bits of help only but you can also consider using URL hooks instead of putting both "normal page rendering" and AJAX responses into the same template file. See: https://processwire.com/blog/posts/pw-3.0.173/ In one way it is cleaner and more flexible than putting both responses into the very same file, but of course, you have to "manage" the two different responses in different files in this way.

Another way of separating AJAX request/responses from the page request is to use URL segments, but with URL hooks available since PW 3.0.173, I would not use that technique anymore.

  • Like 5
Link to comment
Share on other sites

On 4/29/2022 at 10:27 PM, szabesz said:

What about the "X-Requested-With: XMLHttpRequest" header? The $config->ajax call requires that to be sent.

yes that's the one. I had the issue before a long time ago. still recovering from racking my brain back then

  • Haha 1
Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...