cancel
Showing results for 
Search instead for 
Did you mean: 

Best practice validating extension admin settings via ajax

Best practice validating extension admin settings via ajax

Hello,
I have inherited a magento 2 extension. I am a complete noob to magento
In my extension under admin->stores->Configuration->My extension->Settings i need to validate  a username and password via an ajax call to my server.

I have found the fields needed in etc/adminhtml/system.xml
Do i add a backend_model(currently i do not have anything like that) ?::

What type of class is extended for something like this backend_model Class?

 

<field id="username" translate="label comment" type="text" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<label>User Name</label>
<comment>Use {{username}} as API Username placeholder</comment>
<backend_model>VendorMe\OnlinePayment\Model\Config\Source\Admin</backend_model>

</field>


Then in that class do i do something like a before_save???
How does this work when you need to validate 2 fields dependent on each other? These appear to be per field.

As you can tell i am completely lost. If anyone can point me to an example that would be the best. But any help would be greatly appreciated 



1 REPLY 1

Re: Best practice validating extension admin settings via ajax

This short example uses PHP to write our JavaScript in the footer of the page. This script then triggers the AJAX request when the page is fully loaded:

<?php
add_action( 'admin_footer', 'my_action_javascript' ); // Write our JS below here

function my_action_javascript() { ?>
	<script type="text/javascript" >
	jQuery(document).ready(function($) {

		var data = {
			'action': 'my_action',
			'whatever': 1234
		};

		// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
		jQuery.post(ajaxurl, data, function(response) {
			alert('Got this from the server: ' + response);
		});
	});
	</script> <?php
}

Or visit Dunkin Runs on You