In prestashop I am doing a small module. In that module in smarty I have a form. I want to submit those values using ajax. So for that I have made my ajax as $.post like this
jQuery(document).ready(function($) {
$('.module-form').submit(function(e) {
e.preventDefault();
msg = '';
$form = $(this);
$.post(
baseDir + "modules/mymodule/mymodule.php",
{ name: 'myname', action: 'form_subscribe' },
function(data) {
var response = jQuery.parseJSON(data);
console.log(response);
}
);
return false;
});
});
In the module file (mymodule.php) I have my code like this
class MyModule extends Module {
public function __construct() {
-----
----
--
}
function form_subscribe() {
$name = $_POST['name'];
echo json_encode($name);
exit;
}
}
But when I am doing submit the form it is showing the response as null. Can someone tell me how to solve this issue? Any help and suggestions will be really appreciable. Thanks.
You can't access a class or a method directly like you are trying to do.
To perform your action you have to first instantiate the Class and then call the function.
Particularly in a prestashop environment, follow this step:
Create another php page inside your module folder, lets call the page mymodule_ajax.php.
Then inside of it retrieve the configuration, the initialization of the prestashop context and then instantiate the module and perform the call management.
mymodule_ajax.php:
include(dirname(__FILE__). '/../../config/config.inc.php');
include(dirname(__FILE__). '/../../init.php');
/* will include module file */
include(dirname(__FILE__). '/mymodule.php');
/* will instantiate the class MyModule so that you can access the method */
$my_mod = new MyModule;
/* using Prestashop Tools Class we ensure that the call is made from the form with action "form_subscribe */
if(Tools::isSubmit('action') && Tools::getValue('action') == 'form_subscribe')
$my_mod->form_subscribe(); //call the method
Then change your ajax code to point that url so:
$.post(
baseDir + "modules/mymodule/mymodule_ajax.php", //new url
{ name: 'myname', action: 'form_subscribe' }
You should now retrieve the json value in your console.log.
Related
Am apology for my bad english. Am new to prestashop. Please anybody help. How to send AJAX request to custom php file in prestashop
//My js file
$.ajax({
url : baseUrl + "modules/<myModule>/ajaxfunc.php",
type: "POST",
cache: false,
data : {form_data: 1 , action:'imageuploadAction'},
beforeSend: function() {
$('body').append('<div class="loading_popup">Loading...</div>');},
success: function(data){
console.log(data);
}
});
// php file
// modules/<myModule>/ajaxfanc.php
<?php
include_once('../../config/config.inc.php');
include_once('../../init.php');
class ajaxfuncAjaxModuleFrontController extends ModuleFrontController
{
public function imageuploadAction() {
die('here');
}
}
?>
I didn't know its be correct or not. please guide me.
You can use an ajax front controller in your module and generate the URL you need for the Ajax request in the module itself with a hook.
See Make an ajax request from a Prestashop module
I have found the solution to get the proper Ajax request in prestashop 1.7
//In tpl file
<script>
var url= {url entity='module' name='<myModuleName>' controller='<MyControllerName>' params = ['var1' => 1,'var2' => 2,action => 'MyControllerAction']}
</script>
//In Js file
$.ajax({
url : url,
type: "POST",
data : 'var3='3,
success : function(response){
console.log(response);
}
});
//In Controller Php file
<?php
require_once(dirname(__FILE__).'../../../../config/config.inc.php');
require_once(dirname(__FILE__).'../../../../init.php');
class <MyModule><MyController>ModuleFrontController extends ModuleFrontController
{
public function initContent()
{
$this->ajax = true;
parent::initContent();
}
// displayAjax for FrontEnd Invoke the ajax action
// ajaxProcess for BackEnd Invoke the ajax action
public function displayAjaxMyControllerAction()
{
$var1 = Tools::getValue('var1');
$var2 = Tools::getValue('var2');
$var3 = Tools::getValue('var3');
header('Content-Type: application/json');
die(Tools::jsonEncode(['var1'=> $var3]);
}
}
I have a function that adds social buttons to my blog posts , but once i load more posts using ajax I cant figure out how can I call add_social_buttons() and pass the data to div.
I'm not really familiar with ajax , i tried this method :
$.ajax({
type:"POST",
url:"functions.php",
data: "social_sharing_buttons()",
success: function(data){
$('.pp').html(data);
}
but it seems that it tries to invoke some totally other function Fatal error: Call to undefined function add_action().
As far as I am aware, you can't. What you can do is have a handler file for your classes, so for example say we have this PHP class,
<?php
class Car {
function getCarType() {
return "Super Car";
}
}
?>
Then in your handler file,
<?php
require_once 'Car.php';
if(isset($_POST['getCarType'])) {
$car = new Car();
$result = $car->getCarType();
echo $result;
}
?>
You'd post your AJAX request to the handler, you could make specific handlers for each request or you could have a generic AJAX handler, however that file could get quite big and hard to maintain.
In your case you'd have in that data,
"getSocialButtons" : true
Then in your AJAX handler file,
if (isset($_POST['getSocialButtons'])) {
// Echo your function here.
}
Then you'd echo out the function within that if statement and using the success callback in your AJAX request do something like this.
document.getElementById("yourDivId").innerHTML = data
That is assuming you're using an ID. Adjust the JS function to suit you.
Try to call that function social_sharing_buttons() like this in function.php:
$.ajax({
type:"POST",
url:"functions.php",
data: {action: 'add'},
success: function(data){
$('.pp').html(data);
}
in functions.php
if(isset($_POST['action']) && !empty($_POST['action'])) {
if($_POST['action'] == 'add') {
echo social_sharing_buttons();
}
}
I have question about call to my module action via ajax.
I'd like call to class in my module via ajax. But best solution for me is call to clean class. Not extends Module.
I don't know hot can I make url without add article to database and add module to him.
I use JQuery instead mooTools but js framework is not important. Most important is call to php class by ajax.
I have ajax module. But if I call to ajax.php required is module id from tl_module table. I don't want use this table. (Ajax will be very often calling, I prefer to don't load all contao mechanism. It should be very fast).
Thanks in advance for answers.
I found the answer for Contao >3.x in a GitHub issuse(german)
At first do in your Front-end Template:
<script type="text/javascript">
var data = {};
data["REQUEST_TOKEN"] = "<?php echo REQUEST_TOKEN ?>";
$(document).ready(function(){
$("#trigger").click(function(event){
$.post(
'<?php echo \Contao\Environment::get('requestUri')?>',
data,
function(responseText) {
alert(responseText);
}
).fail(function( jqXhr, textStatus, errorThrown ){ console.log( errorThrown )});
event.preventDefault();
});
});</script>
Important is the
- data["REQUEST_TOKEN"] -> if you do not add it, the POST-request will not reach your module:
public function generate()
{
if ($_SERVER['REQUEST_METHOD']=="POST" && \Environment::get('isAjaxRequest')) {
$this->myGenerateAjax();
exit;
}
return parent::generate();
}
//do in frontend
protected function compile()
{
...
}
public function myGenerateAjax()
{
// Ajax Requests verarbeiten
if(\Environment::get('isAjaxRequest')) {
header('Content-Type: application/json; charset=UTF-8');
echo json_encode(array(1, 2, 3));
exit;
}
}
If you want to do the ajax via GET you do not need the reqest token but the jquery funktion $get();
I would suggest you to use Simple_Ajax extension.
In this case you dont need to use Database and you can do pretty much anything you can do normally with Jquery ajax calls.
It works with Contao 2.11 and you can call your php class with it.
I find it much easier to use than ajax.php .
You can get it from : https://contao.org/de/extension-list/view/simple_ajax.de.html
Copy SimpleAjax.php to Contao's root folder.
Go to [CONTAO ROOT FOLDER]/system/modules and create a php file like following :
class AjaxRequestClass extends System
{
public function AjaxRequestMethod()
{
if ($this->Input->post('type') == 'ajaxsimple' )
{
// DO YOUR STUFF HERE
exit; // YOU SHOULD exit; OTHERWISE YOU GET ERRORS
}
}
}
Create a folder called config with a php file like following ( You can hook you class to TL_HOOKS with class name - class method, simple_ajax will execute you method whenever a ajax call is made ):
$GLOBALS['TL_HOOKS']['simpleAjax'][] = array('AjaxRequestClass','AjaxRequestMethod'); // Klassenname - Methodenname
Now you can easily make ajax calls with simply posting data to SimpleAjax.php:
$.ajax({
type: "POST",
url: "SimpleAjax.php",
data: { type: "ajaxsimple" },
success: function(result)
{
//DO YOUR STUFF HERE
}
I'm creating a module for the shopping cart PrestaShop so I have to follow a set framework of rules when creating a module that will work in their system, and I want to submit forms via AJAX without reloading the page.
Here is a trimmed version of the module page which builds and determines what is displayed:
<?php
class mymodule extends Module
{
private $_html = '';
// Module information
function __construct()
{
// Get shop version
$versionMask = explode('.', _PS_VERSION_, 3);
$versionTest = $versionMask[0] > 0 && $versionMask[1] > 3;
// Module info
$this->name = 'MyModule';
$this->tab = $versionTest ? 'administration' : 'Administration';
if ($versionTest) { $this->author = 'JD'; }
$this->version = '0';
parent::__construct();
$this->displayName = $this->l('MyModule');
$this->description = $this->l('Description...');
}
// Display content
public function getContent()
{
$this->_displayForm();
return $this->_html;
}
// Build the display
private function _displayForm()
{
$this->_html .= '<script src="../modules/mymodule/scripts.js" type="text/javascript"></script>
<form name="formName" id="formName" method="get">
<input type="submit" name="submitModule" value="Continue" />
</form>';
}
}
?>
Normally there is a private _postProcess function which processes form data which then calls the function getContent on page reload where you can then check to see if it should show the form or the results etc.
But since I want to do this with AJAX, I've removed the _postProcess function as it's not needed, linked to my scripts.js which has the following:
$(document).ready(function() {
$('#formName').submit(function(e)
{
e.preventDefault();
$.ajax({
url: "ajax.php",
type: "GET",
dataType: "json",
success: function(data)
{
if (data.response == 1)
{
alert('true');
}
else
{
alert('false');
}
}
});
});
});
And the ajax.php file itself which I've really trimmed down so it's forced to show a result:
<?php
$json['response'] = 1;
echo json_encode($json);
exit();
?>
But I always get the error Uncaught TypeError: Cannot read property 'response' of null, which is obviously telling me the data.response isn't being sent through properly as it doesn't know what response is.
If I test the pages manually, everything works fine, so it leads me to believe either it has something to with the fact it could be in a class perhaps? And that I have to do something different to usual to get it to send the data through?
Or PrestaShop doesn't allow modules to run via AJAX, yet the only thing I can find on their site which relates to this is someone asking the same question in their forum and it has no replies/fixes.
I'd also like to note the AJAX is working to an extent, that if in the success function I put alert("hello"); the alert popup is shown.
Does anyone have any ideas where I might be going wrong?
Uncaught TypeError: Cannot read property 'response' of null scripts.js:132
$.ajax.success scripts.js:132
o jquery-1.7.2.min.js:2
p.fireWith jquery-1.7.2.min.js:2
w jquery-1.7.2.min.js:4
d
scripts.js:132 refers to the line: if (data.response == 1)
Also I've taken it out of the class and put it on a normal page/seperate directory and have the same code, just not inside the class/functions:
index.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="scripts.js" type="text/javascript"></script>
<form name="formName" id="formName" method="get">
<input type="submit" name="submitModule" value="Continue" />
</form>
scripts.js
$(document).ready(function() {
$('#formName').submit(function(e)
{
e.preventDefault();
$.ajax({
url: "ajax.php",
type: "GET",
dataType: "json",
success: function(data)
{
if (data.response == 1)
{
alert('true');
}
else
{
alert('false');
}
}
});
});
});
ajax.php
<?php
$json['response'] = 1;
echo json_encode($json);
exit();
?>
And when I submit the page I get the alert true and if I view ajax.php I get {"response":1}. So that code itself is ok, it's just integrating it with their class/functions.
It appears the path to the ajax.php file in the scripts.js file was causing the problem.
It's to do with the structure of the folders in prestashop, all modules are placed in /prestashop/modules/ directory but the modules are viewed from /prestashop/admin/. So changing them to the full paths fixed the problem.
Thanks to the guys that helped on here though, it's still appreciated!
I think your result is being sent ok, but not interpreted as JSON, a bit of the jquerys fault - I dare to say.
header('Content-Type: text/javascript; charset=utf8');
Putting this in the PHP script should do the trick and force the correct interpretation of the json the data.
If the previous suggestion didn't get you anywhere also try using $.parseJson(); as in jQuery docs:
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
I am using a class to do some CRUD stuff on a database, this one (http://net.tutsplus.com/tutorials/php/real-world-oop-with-php-and-mysql) I am going to use jquery to check the if the username has been registered already.
I could just create a php file specifically for that task, but would just like to extend the class and create a method callled checkname().
How can I call this in jquery?
You can use jQuery to make ajax call to a php file following:
PHP [suppose, test.php]
<?php
class ABC extends XYZ {
public function checkname() {
if(isset($_POST) && !empty($_POST['name'])) {
echo json_encode(array('status' => 'done'));
}
}
}
$ins = new ABC();
$ins->checkname(); // calling the function checkname
?>
jQuery:
$.ajax({
url: 'test.php', // write the url correctly
type: 'post',
data: "name=XYZ&location=PQR"
}).done(function(response) {
console.log(response.status); // will log done
}).fail(function(jqXHR, textStatus) {
console.log("Failed: " + textStatus);
});
It is just an example.
You'll need to use jQuery's Ajax functionality to access a PHP page that calls that function. You can't directly call a PHP function via Ajax, something on the backend has to be set up.