How to make ajax call in yii2? - php

In yii version 1.14 we used
CHtml::ajaxlink
for ajax call what about in yii2?

You can make an ajax link like
Html::a('Your Link name','controller/action', [
'title' => Yii::t('yii', 'Close'),
'onclick'=>"$('#close').dialog('open');//for jui dialog in my page
$.ajax({
type :'POST',
cache : false,
url : 'controller/action',
success : function(response) {
$('#close').html(response);
}
});return false;",
]);

From: http://www.yiiframework.com/wiki/665/overcoming-removal-of-client-helpers-e-g-ajaxlink-and-clientscript-in-yii-2-0/
You can easily create and combine all such client helpers for your
need into separate JS files. Use the new AssetBundle and AssetManager
functionality with the View object in Yii2, to manage these assets and
how they are loaded.
Alternatively, inline assets (JS/CSS) can be registered at runtime
from within the View. For example you can clearly simulate the
ajaxLink feature using a inline javascript. Its however recommended if
you can merge where possible, client code (JS/CSS) into separate
JS/CSS files and loaded through the AssetBundle. Note there is no more
need of a CClientScript anymore:
$script = <<< JS
$('#el').on('click', function(e) {
$.ajax({
url: '/path/to/action',
data: {id: '<id>', 'other': '<other>'},
success: function(data) {
// process data
}
});
});
JS;
$this->registerJs($script, $position);
// where $position can be View::POS_READY (the default),
// or View::POS_HEAD, View::POS_BEGIN, View::POS_END

$.get( "' . Url::toRoute('controller/action') . '", { item: $("#idoffield").val()} ) /* to send the parameter to controller*/
.done(function( data )
{
$( "#lists" ).html( data );
})
and give lists id for div
<div id="lists"></div>
for more visit https://youtu.be/it5oNLDNU44

<?=yii\helpers\Url::toRoute("site/signup")?>

Related

Pass data back to parent file from a ajax loaded file without using PHP

In INDEX.PHP I open a Boostrap dialog which loads via ajax BACKUPS.PHP
BootstrapDialog.show({
size: BootstrapDialog.SIZE_NORMAL,
title: 'Backups',
closable: true,
message: $('<div></div>').load('backups.php'),
buttons: [{
id: 'download_backups',
label: 'Download selected',
action: function(dialogItself){
$.ajax({
url : 'downloadbackup.php?q=download',
type: 'POST',
success : function(data){
}
});
dialogItself.close();
}]
});
BACKUPS.PHP renders a list of files that the user can select by checking the relative checkboxes. The values of the checked checkboxes are correctly stored in the array selected_db_chk using jQuery:
$('input[type=checkbox]').change(function() {
selected_db_chk = [];
$('input[type=checkbox]:checked').each(function() {
filename = $(this).val();
if(selected_db_chk.indexOf(filename) === -1) { // If not exists...
selected_db_chk.push(filename);
}
});
});
The goal is to pass the array selected_db_chk to INDEX.PHP so that it can be then passed to DOWNLOADBACKUP.PHP to download the selected files.
My question is how can I pass selected_db_chk back to INDEX.PHP using Javascript NOT PHP? I thought that if it was declared in INDEX.PHP it would be globally defined:
var selected_db_chk;
and accessible from other files, but if I try this way when I call it in BACKUPS.php I get selected_db_chk is undefined.

How to use Ajax in Symfony?

I have a page with a list of items and some controls that are used for searching/sorting these items. I want these controls to work dynamically, using Ajax, but I can't find a way to use it in Symfony.
In plain PHP, I had the JS file that collected the data, then sent it to a PHP file, which triggered specified method from a class. How can I do something like that in Symfony3? Only tutorial I found was for Symfony 1.x.
If you are in a form, you can do something like :
$(document).submit(function () {
var url = $('form').attr('action');
var data = $('form').serialize();
$.post(url, data, function (data) {
window.location.href = data.redirect;
})
.fail(function () {
$('form').replaceWith(data.form);
});
});
You just need to send the correct url :
$(document).on('click', 'a', function () {
var url = window.location.href;
$.get(url, function (data) {
$('.container').replaceWith(data);
});
});
It is also possible to use a routing generator, simply add: "friendsofsymfony/jsrouting-bundle": "dev-master" to your composer.json.
AppKernel.php :
new FOS\JsRoutingBundle\FOSJsRoutingBundle()
Then config it in your routing.yml :
fos_js_routing:
resource: "#FOSJsRoutingBundle/Resources/config/routing/routing.xml"
And finally use "expose" arg in your routing :
#Route("/{table}/index", name="beta.index", options={"expose"=true})
I use annotation routing
In your JS :
var url = Routing.generate('beta.index', { 'table': 'foo' });
Hope it'll help you :)

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
}

how to run php function without reloading the page

I am a newbie to php
<?php
getDBData(){
//log the call
$fetchedData = myDbCode.fetchData();
return
}
?>
<script type="text/javascript">
dbData = <?php echo json_encode(getDBData()); ?>
</script>
As observed in the log that getDBData get called only once during the page loading and later on even with dbData = <?php echo json_encode(getDBData()); ?> this code the call to getDBData() doesn't happen.
Any idea why the call to getDBData() happening only on page load and not thenafter
How to call getDBData() from javascript
You don't actually understand, how it works.
Javascript is a client-side language, which means, that it executes in web browser.
PHP is server-side which mean it executes on server.
While handling request, first PHP is executed, that the response is returned to user, and then Javacript executes.
To communicate between client and server you can use ajax requests, which are basically simple http requests but without reloading whole page.
You should use Ajax for that. I.e. you have a php file which returns the output of the function:
// data.php
<?php
function getDBData(){
//log the call
$fetchedData = myDbCode.fetchData();
return $fetchedData;
}
echo getDBData();
?>
// html file
<script type="text/javascript">
var getDBData = function(callback) {
$.ajax({
url: "data.php"
}).done(callback);
}
var dbData = <?php echo json_encode(getDBData()); ?>
getDBData(function(data) {
dbData = data;
})
</script>
The code above uses jQuery.
you can used AJAX for get server side php vaue into javascript variable read this ajax example and implement it.
// Launch AJAX request.
$.ajax(
{
// The link we are accessing.
url: jLink.attr( "href" ),
// The type of request.
type: "get",
// The type of data that is getting returned.
dataType: "html",
error: function(){
ShowStatus( "AJAX - error()" );
// Load the content in to the page.
jContent.html( "<p>Page Not Found!!</p>" );
},
beforeSend: function(){
ShowStatus( "AJAX - beforeSend()" );
},
complete: function(){
ShowStatus( "AJAX - complete()" );
},
success: function( strData ){
ShowStatus( "AJAX - success()" );
// Load the content in to the page.
jContent.html( strData );
}
}
);
// Prevent default click.
return( false );
}
);
You can do it through ajax.
Here is a link here to do it with jquery : using jquery $.ajax to call a PHP function
use jquery
$.ajax({
url: 'yourpage.php',
type: 'POST',
data:'',
success: function(resp) {
// put your response where you want to
}
});
You can't directly call PHP functions from javascript.
You have to "outsource" the getDBDate to an own .php file where you output the json_encoded string and call this file with ajax and get the output of the page.
The easiest to do AJAX requests in javascript is to use the JQuery Library: http://api.jquery.com/jQuery.ajax/

common server response page causes in ajax?

I have developed an facebook app which is using ajax request/response each 3secs. and also there are menu items which are loading content in main div. Every ajax request is going to common.php. Few ajax are very slow. I want to know that using a single file for all request is slowing performance?
Here is ajax request which is slow:
function FetchMore()
{
document.getElementById("debugger").innerHTML = "Fetch more called";
attempt++;
/*********proccessing ajax***********/
document.getElementById("bldr").style.display="";
var urlp="https://www.shopinion.net/facebook/common.php?FBUID="+fbuid+"&action=more&attempt="+attempt+"&what="+lstevt;
if(lstevt == "home" || lstevt == "rec")
{
if(complete==false)
{
complete=true;
setTimeout("Watcher()",10000);
document.getElementById("debugger").innerHTML = "Reqest send Fetch more called";
MoreAjaxReq = $.ajax({
async: true,
url: urlp,
cache: true,
success: function(data) {
complete=false;
document.getElementById("debugger").innerHTML = "Data received Fetch more";
setTimeout("getScroll()",3000);
document.getElementById("content").innerHTML +=data;
document.getElementById("content").style.opacity="1";
Tip();
$('a[rel*=facebox]').facebox({
loadingImage : 'facebox/loading.gif',
closeImage : 'facebox/closelabel.png'
})
var handler = null;
// Prepare layout options.
var options = {
autoResize: true, // This will auto-update the layout when the browser window is resized.
container: $('#content'), // Optional, used for some extra CSS styling
offset: 6, // Optional, the distance between grid items
itemWidth: 210 // Optional, the width of a grid item
};
$(document).bind('scroll', onScroll);
// Call the layout function.
handler = $('#tiles li');
handler.wookmark(options);
$('a[rel*=facebox]').facebox({
loadingImage : 'facebox/loading.gif',
closeImage : 'facebox/closelabel.png'
})
document.getElementById("bldr").style.display="none";
//FB.Canvas.scrollTo(0,400);
setTimeout("Trick87()",3000);
}
});
}
//
Please help me how to improve response time?
Thanks in advanced.
Oh, there are lots of ways to improve performence. I will list a few
Cache data on server side
Minimize the content in the response
Maybe you don't have to fetch more data if the first request hasn't success yet.
Use as few database calls as possible

Categories