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
}
Related
i'm new to codeigniter i can't not get data from the controller using the ajax request i think i do mistake in writing the url of the controller function in ajax call
here is the code of my ajax call
$(document).ready(function(){
$("#fname").focusout(function(){
// alert();
$.ajax({
url: "<?php echo base_url();?>/proposal/ajax_load",
type: 'POST',
success: function(result){
$("#div1").html(result);
}
});
});
});
Here is my controller
class Proposal extends CI_Controller {
public function ajax_load()
{
return ("Hello");
}
}
You are confuse between the meaning of [Return, Echo] in PHP,
Echo
echo — Output one or more strings
Return
return returns program control to the calling module. Execution
resumes at the expression following the called module's invocation.
and as long as the Ajax response callback is reading a server response [output], you must send an output to the server.
public function ajax_load()
{
echo "Hello";
}
Further reading :-
What is the difference between PHP echo and PHP return in plain English?
Difference between php echo and return in terms of a jQuery ajax call
a short and simple answer
in ajax_load() - Should be echo not return if you're getting a response via ajax.
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();
}
}
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.
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.
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>