Play 2.x: How to make an AJAX request with a common button
For this job you should go with javascriptRoutes
as it generates correct JS paths based on your routes.conf. You'll find usage sample in Zentask sample
Anyway, for now you can fix your AJAX call by changing the url
to
url : '@routes.Application.saveDefaultPhoneForUser()',
This way requires it to place the whole JS in template, which is wrong. It can or even should be moved to separate JS file and to make it possible you need to use javascriptRoutes.More...
javascriptRoutes are not described yet in official documentation, but here's step-by-step introduction to it. Although the description looks sophisticated de facto using this way brings a lot of benefits.
1. Create the common routes
First you need to create common routes in conf/routes
file:
GET /item/:id controllers.Application.getItem(id: Long)
POST /item/new controllers.Application.newItem
PUT /item/:id controllers.Application.updateItem(id: Long)
Of course, you need to create at least these three actions in Application
controller:getItem(Long id){ ... }
newItem() { ... }
updateItem(Long id) { ... }
2. Create an action translating common routes to JS
- place it somewhere, ie. in your
Application
controller - Let's call it
javascriptRoutes()
conf/routes
filepublic static Result javascriptRoutes() {
response().setContentType("text/javascript");
return ok(
Routes.javascriptRouter("myJsRoutes",
routes.javascript.Application.getItem(),
routes.javascript.Application.newItem(),
routes.javascript.Application.updateItem(),
//inside somepackage
controllers.somepackage.routes.javascript.Application.updateItem()
)
);
}
Note: Don't set any params in brackets.3. Create a route for javascriptRoutes
action and include it in your template
Route conf/routes
GET /javascriptRoutes controllers.Application.javascriptRoutes
View in <head>
part of /views/main.scala.html
<script type="text/javascript" src='@routes.Application.javascriptRoutes()'></script>
4. Use javascriptRoutes where you want
Up from now you can use routes in JS to get the correct path without need to specify the url
and type
. For an example instead of:
$('.getAjaxForThisContainer').click(function(e) {
var idToGet = $("#someField").val();
$.ajax({
type : 'GET',
url : '@routes.Application.getItem()',
data : {
id: idToGet
},
success : function(data) {
// ... some code on success
}
});
return false;
});
you can use simplified version (myJsRoutes
from point 2):myJsRoutes.controllers.Application.getItem(idToGet).ajax({
success : function(data) { ... some code ... }
});
or myJsRoutes.controllers.Application.newItem().ajax({
success : function(data) { ... some code ... }
});
etc...- you don't need to specify
type: "POST"
- JS router will use correct method according toconf/routes
rule - you can set
id
of the record (or other params) toGET
orPUT
(or other methods) usingroutes-like
syntax in pure JS - If your route rule contains all required params you can really minimize yours JS:
GET /some/:a/:b/:c controllers.Application.getABC(a: String, b: Integer, c: String)
JS:myJsRoutes.controllers.Application.getABC("a", 1, "b" ).ajax({});
Play: Performing ajax calls.....?
if you want include the js the you have to
<script type="text/javascript" charset="utf-8" src="@routes.SomeCtrl.ajaxForm()"></script>
according to your code your js will act as a page, and the content written on your js will shown on web as it is written.for ajax refrence you can check http://www.playframework.com/documentation/2.2.x/ScalaJavascriptRouting
and check this question Play 2.x: How to make an AJAX request with a common button
How can I send an Ajax Request on button click from a form with 2 buttons?
Given that the only logical difference between the handlers is the value of the button clicked, you can use the this
keyword to refer to the element which raised the event and get the val()
from that. Try this:
$("button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/pages/test/",
data: {
id: $(this).val(), // < note use of 'this' here
access_token: $("#access_token").val()
},
success: function(result) {
alert('ok');
},
error: function(result) {
alert('error');
}
});
});
How to trigger a iron-ajax request on a paper-button click?
You need to wrap your polymer elements in a tag that will register as polymer element. You can use dom-bind
in your case.
<template id="t" is="dom-bind">
<textarea value="{{dataToPost::input}}"></textarea>
<paper-button on-tap="postData">Post Data</paper-button>
<iron-ajax
id="dataAjax"
method="post"
url="data/url"
on-response="postComplete"></iron-ajax>
</template>
In the script you need to call generateReqeust
on iron-ajax
element.(function (document) {
'use strict';
document.addEventListener('WebComponentsReady', function() {
// We have to bind the template with the model
var t = document.querySelector('#t');
var ajaxRequest = t.$.dataAjax;
// make the iron-ajax call
t.postData = function() {
ajaxRequest.body = {
'text': t.dataToPost;
}
ajaxRequest.generateRequest();
}
//callback on request complete
t.postComplete = function(){
alert('whoa! request complete');
}
});
})(document);
Working plunker for GET
: http://plnkr.co/edit/13QJ7QFETIBg4bEiCMS7?p=preview Multi AJAX Request in Laravel
This should work:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("form").on('submit', function(e) {
e.preventDefault();
var post_id = $("#post_id").val();
var reaction = $(".btn-submit").val();
$.ajax({
type: 'POST',
url: "{{ route('ajaxRequest.post') }}",
data: { post_id, reaction },
success: function(data) {
alert(data);
}
});
});
public function ajaxRequestPost(Request $request)
{
$data = $request->all();
return response()->json($data);
}
Play framework write Action with Ok(...) that doesn't load new page
In order to accomplish this task, i had to use play's javascriptRouting
This question's answer helped a lot.
I'm not experienced with jquery so writing that correctly was difficult. For those that find this, here is my final jquery that worked:
$(document).ready(function(){
$("div#results").on("click", ".hideme", function(event) {
var $form = $(this).closest("form");
var id = $form.find("input[name='id']").val();
var name = $form.find("input[name='name']").val();
var email = $form.find("input[name='email']").val();
var emailsecondary = $form.find("input[name='emailsecondary']").val();
var url = $form.find("input[name='url']").val();
$.ajax(jsRoutes.controllers.Application.createLinkedin(id, name, email, emailsecondary, url))
.done(function(data) {
console.log(data);
$form.closest('li.item').slideUp()
})
.fail(function(data) {
console.log(data);
});
});
});
Note that my submit button was class="hideme", the div that gets filled with results from the DB was div#results and the forms were contained within li's that were class="item". So what this jquery is doing is attaching a listener to the static div that is always there:<div id="results">
It waits for an element with class="hideme" to get clicked. When it gets clicked it grabs the data from the closest form element then sends that data to my controller via ajax. If the send is successful, it takes that form, looks for the closest li and does a .slideUp()Hope this helps
Play 2: get reply from server to AJAX
first you need to send Json response back to browser have a look at official docs,
second you have to handle response in javascript like this
jsRoutes.controllers.Items.delete(id).ajax({
success: function(datafromserver) {
// if success put your logic here
},
error:function(xhr, status, error) {
// handle exception
}
});
Jquery and play framework 2 javascript router issue
You could add the id as an attribute on the delete link:
<a href="#" data-id="@item.id">delete</a>
And then read that with jquery in your js, something like:$('delete').click( function() {
var id = $(this).attr("data-id");
jsRoutes.controllers.Application.Items.delete(id).ajax({
...
Related Topics
Jquery Returning "Parsererror" for Ajax Request
How to Avoid Freezing the Browser When Doing Long-Running Computations in JavaScript
JavaScript Property with Three Dots (...)
JavaScript Date Timezone Issue
How to Export Socket.Io into Other Modules in Nodejs
Event.Wheeldelta Returns Undefined
Twig Variable in External Js File
Updating Svg Element Z-Index with D3
If (Key in Object) or If(Object.Hasownproperty(Key)
Why Does JavaScript Getyear() Return 108
Why Does a Simple .*? Non-Greedy Regex Greedily Include Additional Characters Before a Match
Backbone: Why Assign '$('#Footer')' to 'El'
How to Reset the Scale/Zoom of a Web App on an Orientation Change on the Iphone
Is Localstorage.Getitem('Item') Better Than Localstorage.Item or Localstorage['Item']
I Can't Reference an Image in Next.Js