Jump to content

Recommended Posts

I'm trying to call an ajax function for an inputfield using Soma's method below by intercepting the call in the module init function but for some reason $this->input is always NULL.

 

public function init() {
		parent::init();
		$dir = dirname(__FILE__);
		require_once("$dir/Location.php");
		require_once("$dir/LocationArray.php");

		$this->wire('config')->js('InputfieldLocations', array(
			'url' => "/admin/locationmodule/ajax"
		));

		if ($this->config->ajax && $this->input->ajaxfunction == 'getcities') {
			header('Content-Type: application/json');
			echo $this->get_cities();
			exit;
		}
	}

 

Share this post


Link to post
Share on other sites

$this->input->post is not populated for AJAX requests (caused by PHP, see this). I use something like this.

<?php
$raw = file_get_contents('php://input');

// optionally check for Content-Type headers
if(is_array($parsed = json_decode($raw, true))) {
    $this->wire->input->post->setArray($parsed);
    $this->config->ajax = true;
}

// use $this->input->post->varName as usual

 

Edited by abdus
added stackoverflow link
  • Like 1

Share this post


Link to post
Share on other sites

Thanks, i'm actually sending a get request.

I've tried $this->input, $this->wire->input, $this->wire('input') all return NULL.

Share this post


Link to post
Share on other sites

How do you make the AJAX request, can you post the relevant JS code? Are you using jQuery/Zepto etc

Share this post


Link to post
Share on other sites

jquery

 

$.ajax({
            type: 'get',
            url: config.InputfieldLocations.url,
            data: {
                id: $(this).val(),
                ajaxfunction: 'getcities'
            },
            success: function(data) {
                console.log(data);
            }
        });

 

Share this post


Link to post
Share on other sites

@neonwired when I use 

$.ajax({
    url: '/endpoint/',
    type: 'GET',
    data: {
        id: 4,
        ajaxfunction: 'someaction'
    },
    success: function(data) {
        console.log(data);
    }
})

where endpoint just echoes the request back

<?php
header('Content-Type: application/json');
echo json_encode(input()->get->ajaxfunction);
return;

and it works (I get my request back, and can access $input->get->ajaxfunction just fine)

Long shot, but can you try using capital GET as ajax type (instead of get)?

Share this post


Link to post
Share on other sites
3 hours ago, abdus said:

$this->input->post is not populated for AJAX requests

That's not correct. It's not populated by json data – which by the way is not really a standard or alike – but only by data formatted in application/x-www-form-urlencoded or multipart/form-data. Both is what a <form> can send, but ajax can also send data in that format. It's just that ajax libs nowadays favor json (, it's not like it's name would include xml :D).

Share this post


Link to post
Share on other sites
2 minutes ago, LostKobrakai said:

only by data formatted in application/x-www-form-urlencoded or multipart/form-data

You're absolutely correct. If the request (AJAX or plain HTTP) is made with a query string (x-www-form-urlencoded) or file input (multipart/form-data) $_POST is populated as usual, but not when it's anything else.

http://php.net/manual/en/reserved.variables.post.php

Share this post


Link to post
Share on other sites

i'm still getting a blank $input->post() not just with ajax calls but regular calls also. $input just doesn't seem to ever be populated at all. Any idea what's going wrong?

Share this post


Link to post
Share on other sites

Do you have redirects? Check the developer console on your browser for double requests and 301 responses.

If you have redirects, make sure you're specifying exact URL of the endpoint (with or without trailing slash) 

Share this post


Link to post
Share on other sites
20 hours ago, abdus said:

Do you have redirects? Check the developer console on your browser for double requests and 301 responses.

If you have redirects, make sure you're specifying exact URL of the endpoint (with or without trailing slash) 

Doesn't look like there's any redirects. $_POST is fine as well. It seems i can iterate through it or call a variable directly but if i dump or print_r $input->post() i get an empty object. Weird.

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.

  • Similar Content

    • By ICF Church
      Hi 👋
      Anyone else having this problem?
      Requirements:
      - Repeater (matrix & normal) with mutlilanguage fields (text, textarea…) 
      - Backend language set to something other than default (ie. German) 
      Reproduce:
      - Add a new repeater Item (ajax, I found no way to possible to disable it with matrix)

      (Notice how the default language tab is active instead of the backend language…)
      - Write something into the (default language) field
      - Try to save, if field is required, this will not work. If not required, then when reloading, the content will be inside the backend language field, instead of the default language field who was (presumably) active
      Analysis:
      When  loading  a new repeater element with ajax, the default langue tab is active, but the backend language inputfield is visible (with no visual indication). When writing into the field, it will populate the backend language. When manually clicking on the default language tab (which is already active), the field will switch to the actual default language field (which is [now] empty) (that can now be populated…)
      Also Notice, the labels of the elements to be added are in default language as well instead of the translated label (images instead of Bilder)…
      ProcessWire 3.0.148, Profields 0.0.5…
      Is it my system configuration, or does anyone else have the same issue? This is a screen recording of the problem:
      Issue: https://github.com/processwire/processwire-issues/issues/1179

      Screen Recording 2020-02-25 at 14.18.31.mov
    • By Pip
      Hi, Everyone! 
      I'm currently working on a page reference field and set it for multiple pages (AsmSelect) for the input. Is there a way for me to add an image field (aka Avatar) and the title of page in the radio button? 
      I used the field name enclosed in the { }. Didn't work. It appeared a text instead. 
      Thanks in advance and hope to hear from you soon!
    • By EyeDentify
      Hello dear PW gurus.

      I have stumbled over a strange error that i all of sudden got when trying to upload an image to a images field on a page.
      There where images allready stored in the field that i wanted to keep, but during the upload the error apear and after that all images are gone from the field and i can´t upload any, i just get the error every time.
      I am running ProcessWire 3.0.153 dev.
      Update:
      After looking in the assets folder i find the folder for the page and the image files seems to be there including the ones i tried to upload when the error occured.
      But they don´t show up in the images field in the page editor.
       
      The error reported:
       
      SQLSTATE[01000]: Warning: 1265 Data truncated for column 'ratio' at row 1 And here is a screenshot of the event:

      The TracyDebugger Error reporting:

      I hope you fine folks could point me in a direction.
      But it seems our old pal set_time_limit() is back.

      Regards, EyeDentify
    • By DV-JF
      Hey all, hope you're feeling well these days!
      Short question: Under "Setup > Templates" it's possible to sort the templates by last modified. Is this possible for fields view to?
      Long explanation:
      Currently I am in the process of programming a reusable template and often have to copy several fields & templates from different PW installations into my "master version".
      Therefore it would be good to see already in the field list when the last modification has taken place.
      Stay healthy & don't forget to wash you hands - many greets!
    • By Robin S
      This module is inspired by and similar to the Template Stubs module. The author of that module has not been active in the PW community for several years now and parts of the code for that module didn't make sense to me, so I decided to create my own module. Auto Template Stubs has only been tested with PhpStorm because that is the IDE that I use.
      Auto Template Stubs
      Automatically creates stub files for templates when fields or fieldgroups are saved.
      Stub files are useful if you are using an IDE (e.g. PhpStorm) that provides code assistance - the stub files let the IDE know what fields exist in each template and what data type each field returns. Depending on your IDE's features you get benefits such as code completion for field names as you type, type inference, inspection, documentation, etc.
      Installation
      Install the Auto Template Stubs module.
      Configuration
      You can change the class name prefix setting in the module config if you like. It's good to use a class name prefix because it reduces the chance that the class name will clash with an existing class name.
      The directory path used to store the stub files is configurable.
      There is a checkbox to manually trigger the regeneration of all stub files if needed.
      Usage
      Add a line near the top of each of your template files to tell your IDE what stub class name to associate with the $page variable within the template file. For example, with the default class name prefix you would add the following line at the top of the home.php template file:
      /** @var tpl_home $page */ Now enjoy code completion, etc, in your IDE.

      Adding data types for non-core Fieldtype modules
      The module includes the data types returned by all the core Fieldtype modules. If you want to add data types returned by one or more non-core Fieldtype modules then you can hook the AutoTemplateStubs::getReturnTypes() method. For example, in /site/ready.php:
      // Add data types for some non-core Fieldtype modules $wire->addHookAfter('AutoTemplateStubs::getReturnTypes', function(HookEvent $event) { $extra_types = [ 'FieldtypeDecimal' => 'string', 'FieldtypeLeafletMapMarker' => 'LeafletMapMarker', 'FieldtypeRepeaterMatrix' => 'RepeaterMatrixPageArray', 'FieldtypeTable' => 'TableRows', ]; $event->return = $event->return + $extra_types; }); Credits
      Inspired by and much credit to the Template Stubs module by mindplay.dk.
       
      https://github.com/Toutouwai/AutoTemplateStubs
      https://modules.processwire.com/modules/auto-template-stubs/
×
×
  • Create New...