I am using Codeigniter with Zurb Foundation framewrk. i am tryin to load data in reveal box(fancy popup) using AJAX.. The trick is, i am not loading just the inner html content, but the HTML itself..I mean, i want the function in controller to return the php file to ajax calling function whose contents will be displayed in popup.. My code is
Ajax function call
function ajaxfunct() {
$.ajax({
type: "POST",
url: "welcome/test",
data: { name: "Jigar", location: "jain" }
}).done(function( html ) {
$("#tagUser").append(html);
});
}
My Controller Code is
public function test() {
$data['name'] = $_POST['name'];
$data['location'] = $_POST['location'];
$this->load->view('index', $data);
echo 'WHAT SHUD I ECHO HERE ?'
}
I know the last 2 lines of my Controller code is wrong..I just dont know how to fetch a php file from views folder, process it and pass it to ajax as a pre-processed html(string).
I am not looking for entire code..just a reference to some function or online tutorials will be great..
thanx
You already do fetch a PHP file from your views folder in your Controller.
The line
$this->load->view('index', $data);
Loads the /application/views/index.php file and processes it with data from the $data array.
So for Your AJAX call you could make a different view file than index.php like test.php that contain the proper HTML for the AJAX and call it with the line
$this->load->view('test', $data);
And skip the ECHO part...
Related
I try that: when clicking on an image a function is executed, this function collects a value and sends it via POST to the controller, this controller collects this data and displays the view. The problem is that everything works but it doesn't get to show me the view, I stay where I was.
Image that calls the function when clicking:
<img onclick="getSubjectPublication(<?php echo $inf->codiAsignaturaDesti; ?>)" id="click" src="/EEmobi/resources/images/click.png"/>
Function:
function getSubjectPublication(data){
console.log("EntroFuncion");
console.log(data);
$.ajax({
type: "POST",
url: "perfil.php/" + "subjectPublications",
data: {"data":data},
success: function(response) {
console.log(response);
},
error: function(t, e) {
window.alert("Error al intentar visualitzar les publicacions");
}
})}
The function calls this general controller (lib), it collects the sent data and passes it to the specific controller:
case 'subjectPublications':
$controllerName = "SubjectPublicationsController";
$actionName = "showSubjectPublications";
$data = $_POST['data'];
array_push($parameters, $data);
break;
Specific Controller:
<?php class SubjectPublicationsController{
function __construct(){
$this->view = new View();
}
public function showSubjectPublications($parameters){
require 'models/PublicationsSubjectModel.php';
$publicationsSubjectModel = new PublicationsSubjectModel();
$data = $parameters[0];
echo "<script>console.log('ENTROFINAL');</script>";
echo "<script>console.log('. json_encode( $data ) .');</script>";
$subjectPublications = $publicationsSubjectModel->getPublicationOfSubject($data);
$route = $this->view->show("PublicationsSubject.php");
$publicationsSubjectModel->disconnect();
include ($route);
}}?>
The case is that in the console browser it shows me the console.log that I do in the function and the response returns the entire web including the view that I include in the controller (the view that i wanted to show in the browser), but it doesn't show it on the screen, i continue with the same screen and not the one that I included in the controller. What am I doing wrong?
Browser Screenshot
When you complete a ajax request you generally want to send back a json object. In this case maybe about the image that you clicked. So then you do something with that in your success function e.g alert - or show a popup or something. Look at json_encode to send your data back from your php page php.net/manual/en/function.json-encode.php
So what I'm doing is that when someone clicks on search button it loads carousel's html code via ajax call, which is in another file and places under the <div id="filter_product"></div>. And it's css and js is linked in file's header and footer where I am making ajax call. I am calling only html of carousel. Let me show you my code
ajax call is
function submit() {
$.ajax({
method: "POST",
url: "<?php echo base_url() ?>public_controller/search_product",
dataType:'html',
data: {color:color, year:year, cat:cat, brand:brand, model:model},
success: function(data){
console.log(data);
$('#filter_product').html(data);
}
});
}
$(document).on('click','#serch_btn',function(){
submit();
})
controller code is
public function search_product(){
$data['cat'] = $this->input->post('cat');
$data = $this->load->view('public/result_product',$data,TRUE);
echo $data;}
If i don't call carousel code via ajax call and simply place that in index.php it is working fine. but when i call code via ajax call then it's js file is not working and display is scrambled but html is loading fine. is there any way to solve this.
thanks in advance
Function name submit is reserved. You can't use it. Try to rename it.
Suggestion: in PHP method you don't need to echo and base_url() you can use in the next way
public function search_product(){
$data['cat'] = $this->input->post('cat');
$this->load->view('public/result_product',$data);
}
//////////////////////////////////////////////////////////
url: "<?= base_url('public_controller/search_product') ?>",
Put line $('#filter_product').owlCarousel(); after $('#filter_product').html(data); in your AJAX request success function.
I referred to some examples online and modified functions.php and the front end template to fire an ajax call to fetch some data. But I've hard time understanding on hoe the data is returned from the requested url.
At the end of functions.php, I added,
wp_enqueue_script('jquery');
function myFunction(){
echo "hi";
die();
}
add_action('wp_ajax_myFunction', 'myFunction');
add_action('wp_ajax_nopriv_myFunction', 'myFunction');
In my custom template page, I added,
var datavalue = 'test data string';
jQuery.ajax({
url: "/wp-admin/admin-ajax.php",
method: "GET",
data: { 'datavar' : datavalue }
}).success(function(data) {
console.log("successfully run ajax request..." + data);
}).done(function(){
console.log("I am from done function");
}).fail(function(){
console.log("I am from fail function.");
}).always(function(){
console.log("I am from always function");
});
});
After running it, I get these response.
I am from fail function.
I am from always function
I don't understand how to fetch data from a specific url and display the result in ajax's success function.
I don't even know how the function defined in function.php would be called by this ajax call? How are they related?
Please explain. Also I would like to fire ajax call to query database by passing keyword, how can I do that in wordpress?
Your AJAX function should include an action parameter to tell admin-ajax which function you would like to execute.
url: "/wp-admin/admin-ajax.php",
method: "GET",
data: {
action : 'myFunction'
}
(or, if you are set up for it, then you can include it in your url, as below)
url: "/wp-admin/admin-ajax.php?action=myFunction"
Also, your function in functions.php should be written in PHP:
function myFunction(){
echo 'hello';
die();
}
You have to use a action on ajax like.
jQuery.ajax({
url: "/wp-admin/admin-ajax.php",
method: "GET",
data: {
action : 'myFunction'
'datavar' : datavalue,
}
});
PHP function need to edit.
function myFunction(){
echo 'success calling functions';
wp_die();
}
you are not passing the "action" parameter in "data". Which contains callback function's name. Please check the attached link.
https://www.sitepoint.com/how-to-use-ajax-in-wordpress-a-real-world-example/
In this you've to make a callback functions.
Wordpress dsnt work with the specific url.
But if you still want to use the specific url. Follow the steps:-
1. Make a wordpress template.
2. Add your specific url code there.
3. Make a page in the admin panel and assign the template you've created above.
4. Now the permalink of that page can be used as a specific url in the jQuery ajax.
In addition to above answers, in your function.php, make use of $_REQUEST. The $_REQUEST contains all the data sent via AJAX from the Javascript call. Something like this
function myFunction() {
if ( isset($_REQUEST) ) {
{
global $wpdb;
$keyword = $_REQUEST["keyword"];
if($keyword){
$query = "
SELECT `$keyword`, COUNT($keyword) AS Total
FROM `profileinfo` GROUP BY `$keyword`
";
$result = $wpdb->get_results($query);
$data = array();
foreach($result as $row)
{
$data[] = $row
}
echo json_encode($data);
}
}
}
die();
}
add_action( 'wp_ajax_myFunction', 'myFunction' );
add_action('wp_ajax_nopriv_myFunction', 'myFunction');
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 running into trouble accessing global variables when I make an AJAX call to a php function in the MediaWiki framework.
My jQuery AJAX call looks like this:
jQuery.ajax({
url: 'GeneralFunctions.php',
type: 'GET',
dataType: 'json',
data: {
text: anchorText
},
success: function (data) {
alert("data: " + data);
}
});
My GeneralFunctions.php file looks like this:
<?php
if (isset($_GET['text'])) {
jsonInlineParse((string) $_GET['text']);
}
function jsonInlineParse($wikiText)
{
global $wgOut;
$return = $wgOut->parseInline($wikiText); //fails here
echo json_encode($return);
}
?>
When I run the jQuery call through a click event I get as far as the parseInline() function. The global variable is never defined in the scope and I get the error:
Fatal error: Call to a member function parseInline() on a non-object in /path/to/file/GeneralFunctions.php on line 54
I'm not sure how to make the parse call and define the global variable when the AJAX call is made?
UPDATE
$wgOut is the OutputPage object associated with MediaWiki. It holds all the HTML of the page and is used throughout the MediaWiki framework to add content to a page or article. It is used on the server side to create customized output for wiki articles. I use it to create forms or add HTML on many of our wikis.
More info here: http://www.mediawiki.org/wiki/Manual:$wgOut
UPDATE 2
#Juhana I changed my function to look like this which results in the same error as before. Each echo outputs "NULL".
<?php
function jsonInlineParse($wikiText)
{
include_once '/path/to/file/includes/OutputPage.php';
include_once '/path/to/file/includes/parser/Parser.php';
echo var_dump($wgOut);
global $wgOut;
echo var_dump($wgOut);
$return = $wgOut->parseInline($wikiText);
echo $return;
echo json_encode($return);
}
?>
I took a different approach after running into global variable problems. I changed the AJAX call I was making and the code below works very well for me. I'm using the editable jquery table you can find here.
PHP
function ajax_parse(){
global $wgRequest;
if($wgRequest->wasPosted()){
$text = $wgRequest->getVal("text");
wfDebug("Recieving::::".$text);
if(!strpos($text, "href")){
$text = myInlineParse($text);
$text = str_replace("<pre>", "", $text);
$text = str_replace("</pre>", "", $text);
}
wfDebug("Returning::::".$text);
echo $text;
}
exit;
}
function myInlineParse( $wikiText ) {
global $wgOut;
return $wgOut->parseInline( $wikiText );
}
JavaScript
// inject wikitext after hitting save
function postSave(o) {
var response = new Array("");
for(var i=0;i<o.row.length;i++){
new Ajax.Request(wgScript +'/Special:EditClass/ajax_parse',
{
asynchronous: false,
parameters: {'text': o.row[i].innerHTML},
onSuccess: function(text){
response.push(text.responseText);
}
}
);
}
return response;
}
For whatever reasons, extensions don't seem to have access to $wgOut. I solved this for my extension by using the hook: OutputPageParserOutput for the code I needed output (I needed to inject some scripts and stylesheets as well as using another hook to modify links and didn't want to bother with Resource_Loader though it is useful and recommended):
$wgHooks['OutputPageParserOutput'][] = array($this, 'doOutputPageParserOutput'); // 'doOutputPageParserOutput' defined as method in my class
As with other hooks, you can get rid of the array in favor of just a function name if you don't want to execute within a class.