How do I perform a jQuery ajax request in CakePHP? - ajax

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);
});
}
});
});

Related

ajax request is not returning back to view in laravel 5

I wanted to submit a for using ajax call in laravel 5.
In view i wrote something like
$("#updateSubmit").on('submit',function(e){
e.preventDefault();
var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
method:'POST',
url: '/account/updateForm',
//dataType: 'json',
data: {accountId:'1111', _token: '{{csrf_token()}}'},
success: function( data )
{
alert(data)
return false;
}
},
error: function(error ){
alert("There is some error");
}
});
and on controller side
public function update(Request $data )
{
return Response()->json(['success' => true],200);
}
while in route for post method
Route::post('account/updateForm', 'AccountController#update')->name('account/updateForm');
its working till ajax. on Submission of ajax it goes to controller action.
but it does not retrun back as ajax comes back in normal form submisson.
it just go to controller and stops there with {"success":true} line.
I want ajax to come back to view form so that I can perform different dependent actions.
Do you mean that when you submit your form, you just have a white page with {"success": true} ?
If that's the case, maybe the error is on your javascript.
Maybe your jQuery selector is wrong, or maybe your js isn't compiled ?

how do basic jquery ajax in typo3 flow?

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>

AJAX avoid repeated code

I'm using Symfony2.1 with Doctrine2.1
I'd like to use AJAX for many features on my site , editing a title , rate an article , create an entity on the fly , etc.
My question is simple :
Do I need to create a JQuery function for each functionnality , like this :
$('#specific-functionality').bind('click', function(e){
var element = $(this);
e.preventDefault();
// the call
$.ajax({
url: element.attr('href'),
cache: false,
dataType: 'json',
success: function(data){
// some custom stuff : remove a loader , show some value, change some css
}
});
});
It sounds very heavy to me, so I was wondering if there's any framework on JS side, or a specific method I can use to avoid this. I was thinking about regrouping items by type of response (html_content , boolean, integer) but maybe something already exists to handle it nicely !
From what I understand, you are asking for lighter version of JQuery ajax method. There are direct get/post methods instead of using ajax.
$.get(element.attr('href'), {'id': '123'},
function(data) {
alert(data);
}
);
To configure error function
$.get(element.attr('href'), {'id': '123'}, function(data) {alert(data);})
.error(function (XMLHttpRequest, textStatus, errorThrown) {
var msg = jQuery.parseJSON(XMLHttpRequest.responseText);
alert(msg.Message);
});
Also, you can pass callback function to do any synchronous operations like
function LoadData(cb)
{
$.get(element.attr('href'), { 'test': test }, cb);
}
And call
LoadData(function(data) {
alert(data);
otherstatements;
});
For progress bar, you use JQuery ajaxStart and ajaxStop functions instead of manually hiding and showing it. Note, it gets fired for every JQuery AJAX operation on the page.
$('#progress')
.ajaxStart(function () {
//disable the submit button
$(this).show();
})
.ajaxStop(function () {
//enable the button
$(this).hide();
});
Instead of $('#specific-functionality').bind('click', function(e){, try this:
$(".ajax").click(function(){
var url = $(this).attr("href") ;
var target = $(this).attr("data-target") ;
if (target=="undefined"){
alert("You forgot the target");
return false ;
}
$.ajax(....
And in html
<a class="ajax" href="..." data-target="#some_id">click here </a>
I think it is the simplest solution. If you want some link to work via ajax, just give it class "ajax" and put data-target to where it should output results. All custom stuff could be placed in these data-something properties.

Updating a dropdown via knockout and ajax

I am trying to update a dropdown using knockout and data retrieved via an ajax call. The ajax call is triggered by clicking on a refresh link.
The dropdown is successfully populated when the page is first rendered. However, clicking refresh results in clearing the dropdown instead of repopulating with new data.
Html:
<select data-bind="options: pages, optionsText: 'Name', optionsCaption: 'Select a page...'"></select>
<a id="refreshpage">Refresh</a>
Script:
var initialData = "[{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}]";
var viewModel = {
pages : ko.mapping.fromJS(initialData)
};
ko.applyBindings(viewModel);
$('#refreshpage').click(function() {
$.ajax({
url: "#Url.Action("GetPageList", "FbWizard")",
type: "GET",
dataType: "json",
contentType: "application/json charset=utf-8",
processData: false,
success: function(data) {
if (data.Success) {
ko.mapping.updateFromJS(data.Data);
} else {
displayErrors(form, data.Errors);
}
}
});
});
Data from ajax call:
{
"Success": true,
"Data": "[{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}]"
}
What am I doing wrong?
The problem you have is that you are not telling the mapping plugin what to target. How is it suppose to know that the data you are passing is supposed to be mapped to the pages collection.
Here is a simplified version of your code that tells the mapping what target.
BTW The initialData and ajax result were the same so you wouldn't have noticed a change if it had worked.
http://jsfiddle.net/madcapnmckay/gkLgZ/
var initialData = [{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"},{"Id":"145033098963549","Name":"Product2"}];
var json = [{"Id":"231271443653720","Name":"Car2"},{"Id":"439319486078105","Name":"Electronics1.2"},{"Id":"115147185289433","Name":"Product"}];
var viewModel = function() {
var self = this;
this.pages = ko.mapping.fromJS(initialData);
this.refresh = function () {
ko.mapping.fromJS(json, self.pages);
};
};
ko.applyBindings(new viewModel());
I removed the jquery click binding. Is there any reason you need to use a jquery click bind instead of a Knockout binding? It's not recommended to mix the two if possible, it dilutes the separation of concerns that KO is so good at enforcing.
Hope this helps.

how can i get file data on ajax page in magento?

I have made a custom module in magento. I am using ajax in it(prototype.js).i can find the post variable on ajax page. But I am unable to find the file array on ajax page.
I am using following code for this.Please let me know where i am wrong?
//Ajax code on phtml page
new Ajax.Request(
reloadurl,
{
method: 'post',
parameters: $('use-credit-Form').serialize(),
onComplete: function(data)
{
alert(data.responseText);
}
});
//Php code on ajaxpage
public function ajaxAction()
{
$fileData = $_FILES;
echo '<pre>';
print_r($fileData);die;
}
It always print blank. but when I added this line
"VarienForm.prototype.submit.bind(usecreditForm)();"
I can get the value of file array. but draw back now page starts refreshing.
Please give me some suggestion.
Try this:
Event.observe('use-credit-Form', 'submit', function (event) {
$('use-credit-Form').request({
onFailure: function () {
alert('fail.');
},
onSuccess: function (data) {
alert(data.responseText);
}
});
Event.stop(event); // stop the form from submitting
});
Credit: submit a form via Ajax using prototype and update a result div

Resources