on my projects show page, I have a button to create a document
<td id="tblButton"> {!! link_to_route('projects.document.create', 'Create Document', array($project->id), array('class' => 'btn btn-info')) !!}</td>
This all works fine, I click on the button and I am linked to the route.
Now, I want to remove this button, and instead trigger the route via Javascript. So I was thinking something like the following
$('#document').on('change', function() {
if($(this).val() == 'Project Identified') {
$.ajax({
url: ''
})
}
else {
}
});
But how can I give it the route projects.document.create and also pass it the project id? I basically need to replicate what the button is doing within the ajax call.
Thanks
Look at the route helper function. It'll just give you the URL rather than the full anchor markup.
$('#document').on('change', function() {
if($(this).val() == 'Project Identified') {
$.ajax({
url: "{!! route('projects.document.create', [$project->id]) !!}"
});
}
});
Related
i am typing text in text area
<input placeholder="DISCOUNT COUPON" type="text" id="coupon">
Sending that text to controller using ajax;
$.ajax({
type: "POST",
url: "applyCoupon",
data:{
coupon: $('#coupon').val(),
course_id: {{$course->id}},
_token: {{ csrf_token() }},
},
success: function(dataResult){
alert("success");} // why i am not GETTING this alert?
Controller:
public function applyCoupon(Request $request)
{
$result=new \stdClass();
$coupons = Coupons::select('discount_percentage')->where('coupon_code',$request->get('coupon'))
->where('course_id',$request->get('course_id'))
->get();
$course = Course::findOrFail($request->get('course_id'));
$discounted_price= ($course->price) - (($course->price)*($coupons[0]->discount_percentage)/100);
$result->val = $discounted_price;
$result->statusCode = 200;
return json_encode($result);
}
Web.php:
Route::post('course/applyCoupon', ['uses' => 'CoursesController#applyCoupon', 'as' => 'courses.applyCoupon']);
everything seems fine, but why success function is not running?
You should be using routes/api.php instead of routes/web.phpin the first place.
Also, log error by adding
...
error: function (request, error) {
console.log(error);
alert("Error");
},
That should give you a clue. Could be anything depending on your setup.
You're not using the full URL you setup in your routes/web.php
Change
url: "applyCoupon",
to
url: "course/applyCoupon",
or even better would be to use the route name you provided
url: "{{route('courses.applyCoupon')}}",
Give correct route to your ajax call
Pass this in your ajax url.
url: "{{ route('courses.applyCoupon' }}"
if still not working, then Check your network tab in inspect tool
Click on the ajax call and it will show you the detail on your right side.
post here what you are getting there.
You need to give the response in return of ajax call:-
use Response;
return response()->json(['message' => 'error', 'data' => $data]);
I am showing the checkbox value checked or unchecked based on the db value.but when user try to change it like unchecked it and update the value. i call the ajax i getting this error.
Thanx for help
Code
<div class="{{count($employees) !=0 ? 'sidebar-hide': 'sidebar-customize'}}">
<a>
{{ Form::checkbox('Employee','1',$user->employee) }}
<i class="fa fa-id-card"></i>
<span>Employee</span>
</a>
</div>
Below is the Ajax Function
$(document).ready(function(){
$('#customize').click(function(e){
e.preventDefault();
var customers=document.getElementById('customers').checked ? '1' :'0' ;
var accounts=document.getElementById('accounts').checked ? '1' :'0';
var Inventory=document.getElementById('InventoryItems').checked ? '1' :'0';
var Employee=document.getElementsByName('Employee').checked ? '1' :'0';
console.log(Employee);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url :"{{ url('user')}}",
type :'POST',
data :{
customer : customers,
accounts : accounts,
inventory: Inventory,
employee : Employee
},
dataType: 'JSON'
// ,
// success: function( data ) {
// $("#ajaxResponse").append(data.msg);
// console.log(data);
//}
});
});
});
Is the HTML created dynamically?
If so, then you need to bind the event to a parent element and use the jQuery.on() method instead of click()
$('#parentelement').on('click', 'div.sidebar-customize', function(e) {
//code
});
The second parameter of the method needs to target the element you're trying to use. From you HTML, I can't tell what that will end up being. Maybe implement an additional class or ID so the HTML can be targeted better.
its like i have to include the Id from the checkbox
{{ Form::checkbox('Employee', 'Employee', $user->employee, ['id' => 'employee']) }}
Ajax Code :
$(document).ready(function(){
$('#customize').click(function(e){
e.preventDefault();
var employee=document.getElementById('employee').checked ? '1' :'0' ;
console.log(employee);
});
});
Works prefectly fine as aspected
I am trying to do some very basic ajax. I just want an onchange event on a select that will call an ajax function that will get the options for another select and fill it in. However I am not sure how to do this in a simple way in Typo3 Flow. My php code for the action just looks like this:
public function getProductsByCategoryAction( $category='' ) {
$postArguments = $this->request->getArguments();
echo __LINE__;
TYPO3\Flow\var_dump($postArguments); die;
}
and my ajax call looks like this:
jQuery('#get_category').change(function(event) {
event.preventDefault();
alert('get products');
var category = jQuery('#get_category').val();
alert(category);
jQuery.ajax({
url: "/admin/orders/getproductsbycategory.html",
data: {
'category': category
},
async: true,
dataType: 'html',
success: function(data) {
alert('hi mom');
...
}
});
});
when I try this url in the browser mysite-dot-com/admin/orders/getproductsbycategory.html?category=17ca6f3e-a9af-da7d-75cd-20f8d6a05ed0
on the page the var_dump just gives me array(empty). Why doesn't the request->getArguments() call work and give the category argument?
The getproductsbycategory.html is created in Neos and has the right plugin for the action call. So I know the right action gets run but it does not get any args. At this point the argument is just a string and not an _identity even though I should eventually do it that way, I'm trying to keep things simple for now for the sake of expediency.
Thanks
Update: as a temp workaround shameless hack I just did this to get the variable:
$categoryID = $_GET['category'];
which works but I'd like to know the proper way especially if it does not involve writing my own view helpers.
First define variable in your html file
<script>
var ajaxUrl = '<f:uri.action action="actionName" controller="(controllername)Ajax"/>';
</script>
Your Ajax code will look like :->
$.ajax({
data: '&lookup='+{somevalue},
type: 'POST',
url: ajaxUrl,
success: function(data) {
$('.lookup-id').append(data);
},
});
Your conroller action will look like :->
public function getLookupIdAction(){
// Get company detail for set logo of company
$companyDetail = $this->getUserCompany();
// Template Name
$templateName = 'GetLookupID.html';
$viewVariables = $this->lookupIdentifierRepository->findByCompany($companyDetail);
$templatepath = 'resource://WIND.Alertregistration/Private/Templates/LookupIdentifier/' . $templateName;
$this->standaloneView->setLayoutRootPath('resource://WIND.Alertregistration/Private/Layouts');
$this->standaloneView->setPartialRootPath('resource://WIND.Alertregistration/Private/Partials');
$this->standaloneView->setFormat('html');
$this->standaloneView->setTemplatePathAndFilename($templatepath);
$this->standaloneView->assignMultiple(array("lookUpValue" => $viewVariables));
$this->standaloneView->setControllerContext($this->getControllerContext());
return $this->standaloneView->render();
}
Your view file look like :->
<f:layout name="Lookup" />
<f:section name="Content">
<label for="lookupId" style="box-sizing: border-box;">Identifier</label>
<div class="select-box" style="box-sizing: border-box;">
// Your Code
</div>
</f:section>
I'm using the jQuery plugin jeditable in my template: http://www.appelsiini.net/projects/jeditable
So, if I click on an editable element, the text changes to a form with a textfield and a submit button.
<script type="text/javascript">
$(document).ready(function() {
$('.edit').editable('{{ path('group_update', { id: group.id }) }}', {
type : 'textarea',
submit : 'OK'
});
});
</script>
And in the body I have something like that:
<div class="edit">{{ group.name }}</div>
But there is a problem. When I click on the submit-button, nothing happens. No forwarding to my action (in fact there is no reaction).
What can I do?
In case if you need to handle data received from your action, you should submit the data to function instead of URL.
Example below is taken from the documentation
$('.editable').editable(function(value, settings) {
console.log(this);
console.log(value);
console.log(settings);
return(value);
}, {
type : 'textarea',
submit : 'OK',
});
You can pass data to your function, which will make an AJAX call to your action and process all received data in a way you need
I'm trying to use Ajax in CakePHP, and not really getting anywhere!
I have a page with a series of buttons - clicking one of these should show specific content on the current page. It's important that the page doesn't reload, because it'll be displaying a movie, and I don't want the movie to reset.
There are a few different buttons with different content for each; this content is potentially quite large, so I don't want to have to load it in until it's needed.
Normally I would do this via jQuery, but I can't get it to work in CakePHP.
So far I have:
In the view, the button control is like this:
$this->Html->link($this->Html->image('FilmViewer/notes_link.png', array('alt' => __('LinkNotes', true), 'onclick' => 'showNotebook("filmNotebook");')), array(), array('escape' => false));
Below this there is a div called "filmNotebook" which is where I'd like the new content to show.
In my functions.js file (in webroot/scripts) I have this function:
function showNotebook(divId) {
// Find div to load content to
var bookDiv = document.getElementById(divId);
if(!bookDiv) return false;
$.ajax({
url: "ajax/getgrammar",
type: "POST",
success: function(data) {
bookDiv.innerHTML = data;
}
});
return true;
}
In order to generate plain content which would get shown in the div, I set the following in routes.php:
Router::connect('/ajax/getgrammar', array('controller' => 'films', 'action' => 'getgrammar'));
In films_controller.php, the function getgrammar is:
function getgrammar() {
$this->layout = 'ajax';
$this->render('ajax');
}
The layout file just has:
and currently the view ajax.ctp is just:
<div id="grammarBook">
Here's the result
</div>
The problem is that when I click the button, I get the default layout (so it's like a page appears within my page), with the films index page in it. It's as if it's not finding the correct action in films_controller.php
I've done everything suggested in the CakePHP manual (http://book.cakephp.org/view/1594/Using-a-specific-Javascript-engine).
What am I doing wrong? I'm open to suggestions of better ways to do this, but I'd also like to know how the Ajax should work, for future reference.
everything you show seems fine. Double check that the ajax layout is there, because if it's not there, the default layout will be used. Use firebug and log function in cake to check if things go as you plan.
A few more suggestions: why do you need to POST to 'ajax/getgrammar' then redirect it to 'films/getgrammar'? And then render ajax.ctp view? It seems redundant to me. You can make the ajax call to 'films/getgrammar', and you don't need the Router rule. You can change ajax.ctp to getgrammar.ctp, and you won't need $this->render('ajax');
this is ajax call
$(function() {
$( "#element", this ).keyup(function( event ) {
if( $(this).val().length >= 4 ) {
$.ajax({
url: '/clients/index/' + escape( $(this).val() ),
cache: false,
type: 'GET',
dataType: 'HTML',
success: function (clients) {
$('#clients').html(clients);
}
});
}
});
});
This the action called by ajax
public function index($searchterm=NULL) {
if ( $this->RequestHandler->isAjax() ) {
$clients=$this->Client->find('list', array(
'conditions'=>array('LOWER(Client.lname) LIKE \''.$searchterm.'%\''),
'limit'=>500
));
$this->set('clients', $clients);
}
}
This is a function I use to submit forms in cakephp 3.x it uses sweet alerts but that can be changed to a normal alert. It's very variable simply put an action in your controller to catch the form submission. Also the location reload will reload the data to give the user immediate feedback. That can be taken out.
$('#myForm').submit(function(e) {
// Catch form submit
e.preventDefault();
$form = $(this);
// console.log($form);
// Get form data
$form_data = $form.serialize();
$form_action = $form.attr('action') + '.json';
// Do ajax post to cake add function instead
$.ajax({
type : "PUT",
url : $form_action,
data : $form_data,
success: function(data) {
swal({
title: "Updated!",
text: "Your entity was updated successfully",
type: "success"
},
function(){
location.reload(true);
});
}
});
});