Using AJAX in a backoffice PrestaShop module - php

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" );

Related

Calling php function with ajax and passing return value to div

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();
}
}

Contao 2.11 call to module via ajax

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
}

codeigniter view won't show up from passing javascript/ajax parameter

I'm integrating codeigniter with phpgrid, and I'm having a trouble with passing the row values from phpgrid (in VIEW A) to another view (VIEW B) through javascript and codeigniter controllers
I have a virtual column like this in PHPGRID (VIEW A):
$col_formatter = <<<COLFORMATTER
function(cellvalue, options, rowObject, rowid){
var sessid = rowObject[0];
return '<input type="button" value="View" onclick="btnView('+sessid+')">';
}
COLFORMATTER;
and the javascript in VIEW A:
function btnView(sessid){
var dataRow = {
sessid:sessid,
};
$.ajax({
type:"POST",
url: "<?php echo base_url()."index.php/main/tes"; ?>",
data: dataRow,
success: function(msg){
}
});
return false;
}
in the Codeigniter CONTROLLERS:
public function tes(){
$data['sessid'] = $_POST['sessid'];
$this->load->view('view_b', $data);
}
I can't seem to load the view. I used Mozilla's Firebug to know the response, it's true that the response is the code of my view_b view, but how can I switch to that view?
//Your are using ajax for some operation and want to reload the view page the you can test these options:
1) take a div in current view page and assing ajax retrun message to that div
function btnView(sessid){
var dataRow = {
sessid:sessid,
};
$.ajax({
type:"POST",
url: "<?php echo base_url()."index.php/main/tes"; ?>",
data: dataRow,
success: function(msg){
$("#divid").html(msg);
}
});
return false;
}
//Or 2)just redirect to your view page again
function btnView(sessid){
var dataRow = {
sessid:sessid,
};
$.ajax({
type:"POST",
url: "<?php echo base_url()."index.php/main/tes"; ?>",
data: dataRow,
success: function(msg){
window.location.href=path to your view page;//<?php echo base_url()."index.php/controller/function"; ?>
}
});
return false;
}
If I understand correctly you want to go from VIEW A to VIEW B (meaning an actual change in the window location) and pass a value to VIEW B so it can generate some dynamic content. Well, AJAX is not the solution here since it will not trigger a change of page but instead will return the markup/text of the response as a string.
But there are still a number of ways you can achieve what you want, using Codeigniter the simpler way would be to use an argument for your controller method that you can send as part of the uri in a link:
HTML
View
Since you're using Javascript to generate the markup you would need something like this
return 'View';
*Note that you will now have a link instead of a button but you can use CSS to style it any way you want it.
You would now retrieve the value in your controller like this:
PHP
public function tes($sessid){
$data['sessid'] = $sessid;
$this->load->view('view_b', $data);
}
Pretty simple. A second option will be to use a form instead of your button to send the value using either GET or POST, forms do trigger a change in page whenever they are submitted:
HTML
<form action="http://example.com/index.php/main/tes" method="get">
<input type="submit" value="{ssid}" name="sessid" />
</form>
Again using javascript:
return '<form action="<?php echo site_url('main/tes')?>" method="get">'
+'<input type="submit" value="'+sessid+'" name="sessid" />'
+'</form>';
And to get the value in your controller:
PHP
public function tes(){
$data['sessid'] = $_GET['sessid']; //OR $_POST['sessid']
$this->load->view('view_b', $data);
}
Turns out that passing a variable from javascript to codeigniter controller is just:
function btnView(sessid){
window.location = "printvo/"+sessid;
}
I was using ajax because I don't know how to pass the variable, I always thought that passing variable is using brackets: window.location = "printvo("+sessid+")"; and that didn't work.

php - codeigniter ajax form validation

Hi I’m quite new to jquery -ajax and I’d like some help please to join it with CI.
I have followed this tutorial on Submitting a Form with AJAX and I’d like to add this functionality to my CodeIgniter site. What I’d like to do is when the user submits the form, if there are any validation errors to show the individually on each input field (as in native ci process), or if this is not possible via validation_errors() function. If no errors occured to display a success message above the form.
Here's my code so far:
my view
// If validation succeeds then show a message like this, else show errors individually or in validation_errors() in a list
<div class="alert alert-success">Success!</div>
<?php echo validation_errors(); //show all errors that ajax returns here if not individualy ?>
<?php echo form_open('admin/product/add, array('class' => 'ajax-form')); ?>
<p>
<label for="product_name">Product *</label>
<input type="text" name="product_name" value="<?php echo set_value('product_name', $prod->product_name); ?>" />
<?php echo form_error('product_name'); ?>
</p>
<p>
<label for="brand">Brand</label>
<input type="text" name="brand" value="<?php echo set_value('brand', $prod->brand); ?>" />
<?php echo form_error('brand'); ?>
</p>
...
my controller
public function add($id){
// set validation rules in CI native
$rules = $this->product_model->rules;
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() === true) {
// get post data and store them in db
$data = $this->input_posts(array('product_name', 'brand', 'category_id', 'description'));
$this->product_model->save($data, $id);
// no errors - data stored - inform the user with display success-div
} else {
// validation failed - inform the user by showing the errors
}
//load the view
$this->load->view('admin/products/add', $data);
}
and here’s the js script
$(document).ready(function () {
$('form.ajax-form').on('submit', function() {
var obj = $(this), // (*) references the current object/form each time
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
obj.find('[name]').each(function(index, value) {
// console.log(value);
var obj = $(this),
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.ajax({
// see the (*)
url: url,
type: method,
data: data,
success: function(response) {
console.log(response); // how to output success or the errors instead??
}
});
return false; //disable refresh
});
});
How should I pass my validation results (either success or the post errors) throught the ajax request and display them on my view??
From some little research I did I've found that you can use a single controller, that holds both the native proccess and the ajax request (instead of using 2 controllers), but my main difficulty is, I don't understand how the results of the validation will pass through the js script and display them on my view?? Please note that I don't want to display anything on an alert box, instead show the results on a div or the errors individualy(if possible).
EDIT I did some changes to my application, here's the code so far:
the controller
public function manage($id = NULL){
$this->load->library('form_validation');
$data['categ'] = $this->category_model->with_parents();
//fetch a single product or create(initialize inputs empty) a new one
if (isset($id) === true) {
$data['prod'] = $this->product_model->get($id);
$data['attr'] = $this->attribute_model->get_by('product_id', $id, null, true);
} else {
$data['prod'] = $this->product_model->make_new();
$data['attr'] = $this->attribute_model_model->make_new();
}
if (isset($_POST['general_settings'])) {
if ($this->form_validation->run('product_rules') === true) {
// get post inputs and store them in database
$data = $this->product_model->input_posts(array('product_name', 'brand', 'category_id', 'general_description'));
$this->product_model->save($data, $id);
$status = true;
} else {
// validation failed
$status = validation_errors();
}
if ( $this->input->is_ajax_request() ) {
echo json_encode($status);
exit;
}
redirect('admin/product');
}
//if (isset($_POST['attributes_settings'])) { the same thing here }
// load the view
$this->load->view('admin/products/manage', $data);
}
and the js
success: function(response) {
//console.log(response);
if (data.status === true) {
$('#ajaxResults').addClass('alert alert-success').html(response);
} else {
$('#ajaxResults').addClass('alert alert-error').html(response);
};
}
But I'm having some issues
Although I get the error messages from validation_errors() as an alert-error when there are no errors I get the true in an alert-error too, insted of alert-success.
2.how should I return the success message too? eg. a message saying "Saves were done!".
Althought in a non-ajax-request the data are stored in the database, in case fo ajax the don't store. Any ideas What may be wrong???
HTML:
<div id="ajaxResults"></div>
Javascript ajax:
success: function(response) {
$('#ajaxResults').text(response);
}
this script you've wrote is only if the validation succeeds, right?
Wrong. The code in "success" gets executed any time you get a response back from the server (assuming the HTTP header is 200). Does your javascript knows if the server has any error for you? No.
You need your JavaScript to recognize if the validation failed or succeeded. You have many ways to do that. One of these could be sending the message to display followed by a 0 or 1.
So your PHP will looks like:
return "0 " . $errorMessage;
and
return "1 " . $successMessage;
and your javascript should then recognize, with if statement and substring, if the message starts with 0 or with 1.
Use this way i hope this will work for you
<script type='text/javascript'>
var base_url = '<?=base_url()?>';
function ajax_call()
{
var ids = $("#all_users").val();
$.ajax({
type:"POST",
url: base_url+"expense/home/get_expense",
data: "userid=" + ids,
success: function(result){
$("#your_div_id").html(result);
}
});
}
</script>

php website and Jquery $.ajax()

The website I'm developing is structured in this way:
It has a function that switches the module for the homepage content when $_GET['module'] is set, example:
function switchmodules()
{
$module=$_GET['module'];
switch($module)
{
case 'getnews': news(); break;
default: def();
}
}
As you can see, this switch calls another function for each module.
For example I wrote getNews() to work in this way:
function getNews()
{
$id=$_GET['id'];
if(!id)
{
//CODE TO LIST ALL NEWS
}
if(isset($id))
{
//CODE TO GET ONLY 1 NEWS BY ID
}
}
So, as you can see I'm not using an unique file for each module; all operations of a module are part of an unique function in which an action is switched again to change the result.
If I want to get a news from database I should use an url like this: ?index.php&module=getnews&id=1
My question now is:
With jQuery and $.ajax() method is there a way to get a news (for example) using this structure based on functions switched by a get? Or do I have to change everything and make a file for each function?
you can simply call the same url via $.ajax(). the only thing which should be changed for axjax calls is that you don't output your layout, but only the news itsself.
in php you can check for an ajax request like
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
// dont output layout
}
If this code is in say 'test.php' you can do:
<script>
$.get(
'/test.php',
{
module: 'news',
id: 1
},
function( data ) {
alert( data );
}
);
</script>
And js will send GET request to test.php with needed params. Then your server script will decide how to process request.
jQuery
$(document).ready( function() {
var form = '#my_awesome_form';
$(form + ' input[type=submit]').click(function(e) {
e.preventDefault();
$.ajax({
type: "GET",
url: 'index.php',
data: $(form).serialize(),
success: function( response ) {
alert('DONE!');
}
});
});
});
HTML
<form id="my_awesome_form" // OTHERS PROPERTIES //>
// LOT OF FIELDS HERE //
<input type="submit" value="Send">
</form>

Categories