Yii Ajax on click - javascript

I have some app on Yii. I want to implement ajax calls on click of div.
I've found some docs with form ajax validation, but it'snot clear for me, how can I do what I want. That's what I did:
$(document).on('click','div.lessonDiv', function()
{
$.ajax(
{
type: "POST",
url: "../../protected/controllers/AjaxController.php",
success: function(data, textStatus, jqXHR)
{
console.log(data);
}
});
}
That says that the directory is forbidden. Where should I put file which is able to interact with ajax? Or it alreay has it?
UPDATE I'm using version 1.1.

You shouldn't call files directly, Yii doesn't work this way. It is MVC framework with controllers and actions and it uses routes, also for AJAX request. So you should add an action to AjaxController and call createUrl to get it's URL.
PHP
class AjaxController extends CController
{
public funcion actionDoThing()
{
// Get request object
$request = Yii::app()->request;
// Check if request is acceptable
if ($request->isPost && $request->isAjaxRequest)
{
echo CJSON::encode(array('hello'=>'world'));
}
// else
// {
// throw new CHttpException(403);
// }
}
}
JS
$(document).on('click','div.lessonDiv', function() {
$.ajax({
type: "POST",
url: <?php echo $this->createUrl('ajax/doThing'); ?>,
success: function(data, textStatus, jqXHR) {
console.log(data);
}
});
});
I'd recommend to read Yii guide more closely. It is also available in Russian

Try this
$(function(){
$(document).on('click','div.lessonDiv', function()
{
$.ajax(
{
type: "POST",
url: "<?php echo Yii::app()->createUrl('Ajax/index'); ?>",
success: function(data, textStatus, jqXHR)
{
console.log(data);
}
});
});
});
To learn about createUrl() in YII click here

Related

Why AJAX on retry sending different url request

I have very stange problem: I have product list and when you click on product to edit the product you go to product form. On this product form I have AJAX that is sending request to getFiltersGroup. I want to resend this AJAX on error, but for some reason on error AJAX is start sending url request for product form not for getFiltersGroup.
Any ideas what is wrong, why is not sending request to getFiltersGroup?
This is what happen on retry:
This is the code:
var retry;
$('#filters-ajax').on('click', function(){
var product_id = "<?php echo isset($set_id) ? $set_id : NULL; ?>";
var ajaxConfig = $.ajax({
url: "index.php?route=catalog/product/getFiltersGroup&token=<?php echo $token ?>",
type: "POST",
data: '&product_id='+product_id,
dataType: 'json',
beforeSend: function(){
$('#btn-product-filter-groups').prop('disabled', true);
},
success: function(data){
clearInterval(retry);
$('#btn-product-filter-groups').prop('disabled', false);
},
error: function(xmlhttprequest, textstatus, message) {
retry = setInterval(function(){
$.ajax(ajaxConfig);
}, 6000)
}
});
})
UPDATE
I fix the url request but now I can't reset the setInverval(). Also I'm never getting alert message. Any ideas what wrong?
var retry;
$('#filters-ajax').on('click', function(){
var product_id = "<?php echo isset($set_id) ? $set_id : NULL; ?>";
$.ajaxSetup({
url: "index.php?route=catalog/product/getFiltersGroup&token=<?php echo $token ?>",
type: "POST",
data: '&product_id='+product_id,
dataType: 'json'
});
var ajaxConfig = $.ajax({
beforeSend: function(){
$('#btn-product-filter-groups').prop('disabled', true);
},
success: function(data){
alert('WTF')
clearInterval(retry);
$('#btn-product-filter-groups').prop('disabled', false);
},
error: function(xmlhttprequest, textstatus, message) {
retry = setInterval(function(){
$.ajax(ajaxConfig);
}, 6000)
}
});
})
$.ajax() returns a jqXHR object, which you are later passing to $.ajax() as a configuration object for a new call:
var ajaxConfig = $.ajax({ ... });
// ...
$.ajax(ajaxConfig);
But that jqXHR object is not an $.ajax() config object, and it will not have a url: ... key/value pair (nor any of your other settings). Checking the docs for the $.ajax() config object it says (emphasis mine):
jQuery.ajax( [settings ] )
settings
Type: PlainObject
A set of key/value pairs that configure the Ajax request. All settings are optional.
And regarding the url setting:
url (default: The current page)
So since there is no URL specified in the config object, it will default to the current page. Your new $.ajax() request will request the current page, your edit page.
If you want to make your AJAX call a callable function, just put it in a function and call it:
function ajaxCall() {
$.ajax({
url: "index.php?route=catalog/product/getFiltersGroup&token=<?php echo $token ?>",
type: "POST",
// ... your code
error: function(xmlhttprequest, textstatus, message) {
retry = setInterval(ajaxCall, 6000)
}
});
}
$('#filters-ajax').on('click', function(){
// ...
ajaxCall();
});
This approach sends off all kinds of recursive alarm bells for me though, I would consider trying another approach.
I dont know why but this one is working if anyone can explain why this code is working and previous code is not working i will accept his answer
$('#filters-ajax').on('click', function(){
var product_id = "<?php echo isset($set_id) ? $set_id : NULL; ?>";
$('#btn-product-filter-groups').prop('disabled', true);
$(function callAjax(){
$.ajax(`index.php?route=catalog/product/getFiltersGroup&token=<?php echo $token ?>&product_id=${product_id}`)
.success( function(data) {
$('#btn-product-filter-groups').prop('disabled', true);
})
.error(function() {
setTimeout ( function(){ callAjax() }, 6000);
});
})
}
})

Unable to receive ajax request in codeIgniter PHP

I have just started codeigniter and I am stuck at sending employee ID to my controller.
Actually, I have a datatable which shows all the registered employees, and there is a button which get the ID of the employee of row clicked and send it to controller through ajax call but i am unable to receive it in my ajax call.
JS code
$('#viewAllEmployeeTable tbody').on('click', '.viewEmployeeDetail', function() {
var data = viewAllEmployeeTable.row($(this).parents('tr')).data();
console.log(data);
employeeID = data.employeeID;
alert(employeeID);
$.ajax({
url: "/ackamarackus/employee/viewEmployeeProfile",
type: "GET",
data: {
"employeeID": employeeID
},
dataType: "json",
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
});
Controller
public function viewEmployeeProfile() {
$name = $this->input->post('employeeID');
echo "INPUT";
echo $name;
die();
}
This is what ajax is sending : employeeID:1000
Can anyone tell me what I am doing here? I have already tried google and stack overflow link, but nothing solved my problem. Thanks
You cannot send field data with type: 'GET'
Change this to type:'POST' and this will solve your issue :)
You are sending employeeID as GET method and accessing it as POST in Your controller, change your type in ajax request to POST as follows
$('#viewAllEmployeeTable tbody').on('click', '.viewEmployeeDetail', function() {
var data = viewAllEmployeeTable.row($(this).parents('tr')).data();
console.log(data);
employeeID = data.employeeID;
alert(employeeID);
$.ajax({
url: "/ackamarackus/employee/viewEmployeeProfile",
type: "POST", //Your problem here
data: {
"employeeID": employeeID
},
dataType: "json",
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
});

Submit a form using Ajax

First, here is my code :
routes.php
$router->resource('vips','formController');
formController.php (im only posting the concerned function)
public function store(CreateVipRequest $request, Vip $vip, Pool $pool, Url $url)
{
$new_vip = $vip->create($request->except(['srv_hostname', 'srv_ip', 'srv_port','url']));
$pool->fill($request->only(['srv_hostname', 'srv_ip', 'srv_port']));
$url->fill($request->only(['url']));
/* Some more inserts on the database...*/
return redirect()->route('vips.show', [DB::table('vips')->max('id')]);
}
My code submits the form, and after some json requests to a distant Api (and some databases insertions) it redirects to the show view.
Now I want to add a second button that submits the form via Ajax.
Question : Is there a way to use the same function store ? I need it to be able to process both an ajax submit and a normal submit.
Submit form using ajax
$("#form-name").submit(function(ev){
ev.preventDefault();
var formURL = $(this).attr("action");
var postData = $(this).serializeArray();
$.ajax({
url: formURL,
type: 'POST',
data: postData,
success: function(data, textStatus, jqXHR){
location.reload();
},
error: function(jqXHR, textStatus, errorThrown){
var errResponse = JSON.parse(jqXHR.responseText);
},
});
});
Yes, you can.
In your javascript you can do something like this (assuming you're using jquery):
// if you're using a form
var data = $('form').serialize();
// if data comes from elsewhere
var data = {foo: 'bar', ...};
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
success: function (data) {
// Do something if everything went fine
},
error: function (jqXHR, textStatus, errorThrown) {
// Do something if something went wrong
},
});
Your controller will catch the data coming from the request as you are already doing.

Sending data, Class, and Method through Ajax

How can I send data through ajax to a specific method in a another PHP class? In the url value I have pointed to the class file, but where can I assign the method name to use?
$.ajax({
type:'POST',
url:'ResortController.php',
data: vidData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(vidData);
//window.location.reload();
},
error: function(data){
console.log("error");
}
});
Pass the data in data:vidData and specify your function name after call of controller.
url = BASE_PATH + 'ResortController/FUNCTION_NAME';
vidData = {id: 123, vidName: "testVideo"};
$.ajax({
type:'POST',
url:url,
data: vidData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
//window.location.reload();
},
error: function(data){
console.log("error");
}
});
Using $_POST in your function you will get your ajax data in $_POST['vidData'].
Also you need to call data instead of vidData variable in success of ajax console.log(data).
You need to have a server-side mechanism in place to handle how to direct your requests. Presumably the url you are sending a request to just has the class declaration...you need some sort of dispatcher or else php doesn't know what to do:
jQuery:
$.ajax({
type:'POST',
url:'/dispatcher.php',
data: {
"data":vidData,
"class":"ResortController",
"method":"rMethod"
},
cache:false,
success:function(data){
console.log("success");
console.log(vidData);
//window.location.reload();
},
error: function(data){
console.log("error");
}
});
/dispatcher.php
<?php
// This is dangerous if you have no controls in place to allow/restrict
// a program to run a command
// Anyone could send a cURL request and run an automated class/method through
// this mechanism unless you have some way to restrict that
if(!empty($_POST['class']) && !empty($_POST['method'])) {
// Here you want to have some way to check that a request is valid and not
// made from some outside source to run arbitrary commands
// I will pretend you have an admin identifier function....
if(is_admin()) {
call_user_func_array(array($_POST['class'],$_POST['method']),array('data'=>$_POST['data']));
}
}

How do I send an ajax post request to a specific module in Drupal6?

I want to send an ajax post request to a module named sampleTest in Drupal6.
I have tried some bits of codes but I do not know how to put the module url in the jquery ajax function.
<script type="text/javascript">
$(function(){
$("#one").click(function(){
$.ajax({
type: 'POST',
url: 'http://localhost/drupal/www/admin/build/modules/module/get/contact',
dataType: 'json',
data: "test",
success:function(data) {
alert("123");
},
complete: function(data){
alert("complete");
}
});
});
});
</script>
You can't send an AJAX request to a module as such, rather you implement a path in your module (using hook_menu()), provide a page callback for that path that outputs the AJAX response, and then call that path in your AJAX call. This is a very basic example:
function mymodule_menu() {
$items['ajax-test'] = array(
'access callback' => TRUE,
'page callback' => 'mymodule_ajax_callback',
'type' => MENU_CALLBACK
);
}
function mymodule_ajax_callback() {
$post_data = $_POST;
// Do something with the post data
$output = array('status' => 'OK');
// For Drupal 6
drupal_json($output);
exit();
// Or for Drupal 7, just in case you want to know
drupal_json_output($output);
drupal_exit();
}
Then your JS would look like this:
$(function(){
$("#one").click(function(){
$.ajax({
type: 'POST',
url: '/drupal/ajax-test',
dataType: 'json',
data: "test",
success:function(data) {
alert(data.status);
},
complete: function(data){
alert("complete")
}
});
});
});

Categories