Jump to content

Do selectors work in AJAX file ?


bombemedia
 Share

Recommended Posts

Hi guys !

First real project with ProcessWire, and I can say I adopted the platform. It's incredibly fun to work with !

I'm currently making a Google Maps interface, in which I can add branch offices in the backend as pages.

Each pages have data : title, latitude longitude etc. and compare it with the user geoloc or a geocoded address.

At first, I fetch the childrens ID, latitude and longitude, json_encode them in an array.

Then, I find the 3 nearest offices and play with data until I need to get the rest of the data matching the IDs, so I can show detailed profiles of the 3 nearest offices.

I'm currently debugging with static data, and I get a 500 internal server error on MAMP... but I don't know, it seems my setup is not showing PHP errors properly.

Here is my Javascript function (executed on dom ready elsewhere) :

File main.js :

function fetchOfficeData() {
    $.ajax({
        url: 'http://127.0.0.1:8888/site/ajax/fetchoffice.php',
        type: "POST",
        dataType:'json',
            data: ({id: 1013}),
            success: function(data){
                console.log(data);
            }
        
    });
    
}

File fetchoffice.php :

    //Format to fetch the office with the ID

    $sel_id = 'id=' . (string)$_POST[id];

    $result = $page->child($sel_id)->title;

    echo json_encode($result);

But I get an error and I suspect it's because I cannot use selectors in my AJAX page because it's not in my template.

I'm able to output $sel_id, or anything else for that matter, but using $page->child... doesn't work.

Is it possible to put this code inside my template so the selectors work ?

Another solution could be to fetch all the data of all the offices and put them in the json_encode array at the beginning... there will be 30 offices max... but I don't feel like it's the right thing to do.

Thank you very much in advance :)

Link to comment
Share on other sites

If you'll put the ajax stuff in a template you can use this: http://cheatsheet.processwire.com/config/runtime-configuration/config-ajax/ Otherwise have a look at this: http://processwire.com/api/include/ The recommended way would be the first one.

Ultra quick reply, I thank you very much !!

I saw config-ajax in another post on stackoverflow but ignored it. Whoops !

Edit I read documentation and came back with something that looks like code that should work...

I replaced my code with this :

At the top of my template file called map.php (which is included in my home page)

if($config->ajax) {
    
    $sel_id = 'id=' . (string)$_POST['id'];
    
    $json = array(
        'title' => $page->child($sel_id)->title,
        'desc' => $page->child($sel_id)->branch_desc
    );

    echo json_encode($json);    
} 

//continue with page rendering

and in my main.js file :

var url = 'http://127.0.0.1:8888/site/templates/map.php';

function fetchOfficeData(){
    
    $.post(url, {id:1013}, function(data) {
        
        console.log('post ran!');
        
        $.each(data, function(key, value) {
            console.log("Keys : " + key + " " + value);
        });

    }, "json");

}

Take note that I coded the variables manually to debug and it will be dynamic...

But nothing outputs !! I don't even get the message that console.log('post ran!'); should give.

Any ideas ?

Link to comment
Share on other sites

Now the url is the problem. You're calling only the template.php, while you need to call a url from your site, which uses this template. Something like "http://127.0.0.1:8888/map/". This way ProcessWire is called, which then includes your template file, but with all the necessary environmental variables.

You're console.log() probably didn't log, because the function is the success handler of jQuery. It's only called if the request is a success. But it isn't, as your template.php is full of errors as long as the variables like $config, $page, $pages ... are not set.

  • Like 1
Link to comment
Share on other sites

I think I found the problem.

If I use a normal $.ajax function, I get the error :

Error: SyntaxError: Unexpected token <

So that means it's trying to parse my whole page instead of staying inside of my if($config->ajax){} .

I edited it to :

if(!$config->ajax) {}

And it parses all the characters of my template file in console.log()...

I think I'm lost because I read the explanations here in the forums and my code should work... but instead it jumps out of if($config->ajax){} and crashes.

Should I create an ELSE for the rest of the page ? EDIT : Even in an else, it parses the whole template file.

Link to comment
Share on other sites

Put "die();" after "echo json_encode($json);"?

Dude, your avatar is pretty accurate, I did the same face when it worked !!!!!

Thank you very much gents, I love you all, I love ProcessWire and I will come back and try to help if I can.

Very nice I'm really happy !!

  • Like 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

×
×
  • Create New...