Jump to content

How to retrieve clicked button name and form values after ajax form submission


Federico
 Share

Recommended Posts

Hi there,

how to get the name of the clicked button after form submission, a form that contains a repeater inputfield. This is the tracy results after form submission, where I have to get the following:

- how to get the name of the button clicked to submit the form (green selected slot)?

- convert this $this->input->post->button_form_repeater_item_2398 into something like $this->input->post->$repeaterName, where $repeaterName should be the repeater name to get fields from (multiple repeaters with multiple submit button with unique ids) - taken from the button name

all the above is possible via javascript, with a simple (jquery) var buttonClickedID = this.id;

5a87f3de4e260_ScreenShot2018-02-17at1_42_20AM.png.b98d9484d9cbf8f4c7db9be7a76ac3e7.png

 

my implementation looks like this now:

public function init() {
  if($this->input->post->button_form_repeater_item_2398) {
    $this->exportBrochure2pdf();
  }
}

public function exportBrochure2pdf($event) {      
    foreach($this->input->post->book_selector_repeater2398 as $key => $value){ // book_selector_repeater2398 should be a variable instead, reflecting the clicked button name corresponding to the related repeater name
        $p = $this->pages->get($value);
        echo htmlentities("ID: $p->id" . " - Title: $p->title") . "<br />";
        $pageArray[] = $this->pages->get($value);
    }
}

 

I can't find any proper solution for this 

Thank you in advance

 

 

Link to comment
Share on other sites

All, 

there are many post already in the forum that describes how to deal with form submission trough ajax post in the same module page.

However, I cannot retrieve POST data after ajax submission - here is my jquery:

$( document ).ready(function() {
    $('.button_export2pdf').on('click', function (e) {
        var buttonClickedID = this.id;
        if (buttonClickedID) {
		var completeData = buttonClickedID + $("form").serialize();
        	$.ajax({
            		type: 'post',
            		url: "", // empty as it is the same page
            		data: completeData,
            		success: function(data){
				//alert(buttonClickedID);
			}
       		});
        }
    });
});	

 and this is the php code inside the same process .module file:

// relevant section of the form code
$form = $this->modules->get("InputfieldForm");
$form->method = 'post';
$form->action = './';

// relevant section - the button to submit the form trough ajax
$repeaterBtn = wire('modules')->get("InputfieldSubmit"); // leave as submit button for export in new tab
$repeaterBtn->attr("value", "Generate Brochure in tab");
$repeaterBtn->attr("id+name", "button_form_$field->name");
$repeaterBtn->addClass("ui-priority-secondary button_export2pdfTab");
$repeaterBtn->addClass('class-here');
$repeaterBtn->attr("target", "_blank"); // leave this, but the "open new tab" job is made by jquery
$form->append($repeaterBtn);

// relevant section - the function to fires after button click
public function ___executeTesta() { // OK, THIS FUNCTION ACTUALLY FIRES WHEN USER CLICK THE ABOVE BUTTON 
	//include("./includes/test.php");
	return $this->input->post->completeData; // WHY THIS IS ALWAYS EMPTY???
	echo isset($_POST['data']) ?  $_POST['data'] :''; // NOT WORKING
}

And this is the results from the Tracy Ajax call, which actually displays the correct POST values..

5a8eb65db1783_ScreenShot2018-02-22at1_23_14PM.png.8217927b7462ec4d5a06be9403ed8c82.png

 

Can you please give me an hint why I cannot retrieve any info from the ajax submitted data?

Thanks a lot!

 

Link to comment
Share on other sites

1 hour ago, Federico said:

Can you please give me an hint why I cannot retrieve any info from the ajax submitted data?

Listen to ajax calls like this:

$sanitizer = $this->wire('sanitizer');
if ($this->wire('config')->ajax) {
	// ajax sent, process inputs
	$input = $this->wire('input')->post;
	$someID = (int) $input->someID;
	$showOptions = (int) $input->show_options;
	$name = $sanitizer->name($input->name);
	$someTextArray = $sanitizer->array($input->someTextArray, 'text');

	// blah blah
	$data = array('message' => 'error');
	if(1 == $someVar) $data['message'] = 'success';
	echo  json_encode($data);
	exit;// or the halt() thingy...
}
// no ajax
else {
}

 

Edited by kongondo
typos
Link to comment
Share on other sites

@kongondo I've tried also your code into the function (this function lies in the same .module file)

public function ___executeTesta() {  
	$sanitizer = $this->wire('sanitizer');
	if ($this->wire('config')->ajax) {
		// ajax sent, process inputs
		$input = $this->wire('input')->post;
		return $input;
	}
}

to test if any variable is taken from PHP after ajax submission, but no luck.

I see POST variable in Tracy, but I cannot retrieve them. Maybe is because I am opening the ajax call in the pw-panel? or maybe because the "url" in $ajax POST is set to none ("")?

Link to comment
Share on other sites

  1. On which page do you have the form being submitted? Do you have it in /your-module-page/testa-page/ ?
  2. I'm not sure what the implications of url: "" (empty string) are. To post to self you can do url: "./"
  3. If you echo something inside the check for $config->ajax, e.g. echo 'I got that' and check that in the (chrome) console xhr panel, would do you see?
  4. I'm not sure if return $input will work. I.e., I don't know how long the $input->post variables will be alive for.
Edited by kongondo
more stuff
Link to comment
Share on other sites

49 minutes ago, kongondo said:
  • On which page do you have the form being submitted? Do you have it in /your-module-page/testa-page/ ?
  • I'm not sure what the implications of url: "" (empty string) are. To post to self you can do url: "./"
  • If you echo something inside the check for $config->ajax, e.g. echo 'I got that' and check that in the (chrome) console xhr panel, would do you see?
  • I'm not sure if return $input will work. I.e., I don't know how long the $input->post variables will be alive for.

1 - the form is submitted via ajax on the same page (It is an admin process module), therefore the path should be log-in/ProcessModuleName/

2 - I've tried both version, I didn't recognized any difference. But I agree that url:"./" should be better than just url:""

3- If I echo something within the executeTesta() function, I will see it in the panel (pw-panel). Actually in the panel I see all php code, excluding the possibility to retrieve any ajax POST variable

4- that' was just to see if it was empty or containing something, just a test for development purpose.

 

Link to comment
Share on other sites

21 minutes ago, Federico said:

3- If I echo something within the executeTesta() function, I will see it in the panel (pw-panel). Actually in the panel I see all php code, excluding the possibility to retrieve any ajax POST variable

I meant what you see in Chrome (or Firefox) Dev console (not Tracy, although Tracy can show you responses [not just calls] to Ajax calls).

Add the following code to the place (in your module) you are expecting to receive the Ajax request. Then, open the Chrome console ( still viewing your page with the form), head over to the Network menu item and  onto the XHR tab then execute your Ajax call. 

if ($this->wire('config')->ajax) {
	echo  "Ajax post received";
	exit;
}

In the XHR tab, inspect the response of the Ajax request sent to  /log-in/moduleName/. Do you see the message "Ajax post received" as the response? I suspect you will not, because I think, you have your ajax response code in executeTesta() which is a different page within your Process Module. Its URL is  /log-in/moduleName/testa/. I think that is what is happening. You are posting to the main page of your Process Module but checking for the ajax response in another page (Testa)...or the other way round :-)

  • Like 1
Link to comment
Share on other sites

26 minutes ago, kongondo said:

You are posting to the main page of your Process Module but checking for the ajax response in another page (testa)...or the other way round :-)

You're right - After some tests, I've move the code into execute() and now I see the message "Ajax post received" in Response.

Now I better understand the function executeTesta() linking to another page (a page that doesn't even exist actually..), so I was likely trowing away the ajax submitted POST.

Is the execute() the correct location for this code? thanks!

Link to comment
Share on other sites

1 hour ago, Federico said:

Now I better understand the function executeTesta() linking to another page (a page that doesn't even exist actually..), so I was likely trowing away the ajax submitted POST.

Anything in a Process Module tagged executeXXX is a page (not a physical one though, but a URLSegment). So, if you have executeTesta, and visit /log-in/module-name/testa/, if there is nothing being returned there (a string output), you will see the error, Process Returned No Content.

1 hour ago, Federico said:

Is the execute() the correct location for this code?

Not really. There is no correct location. You can have the form in execute() but handle the Ajax request in executeTesta() or wherever you wish. These virtual pages (executeXXX()) offer a lot of power and versatility. All you need to tell the Ajax call in jQuery is where url is. So, you can do url:/log-in/module-name/testa/ and you will be able to handle the Ajax request in executeTesta() :-). You can even have executeTesta() do nothing but handle Ajax requests (maybe rename it to executeAjax(). If the page is accessed directly (i.e. non-ajax request), you can have it redirect to execute(), otherwise (if Ajax sent), process it.

In a nutshell, you make the decision about what works for you. ProcessWire doesn't really mind :-)

Edited by kongondo
clarity
  • Like 2
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...