Symfony - Ajax and Twig - javascript

I am working on Symfony2 project. And now want to add some dynamic actions.
I want to use jQuery and Ajax calls and API.
Below I wrote my project model.
Issue is there where I put "?" on the picture.
For example I have comments in my page and 2 buttons "oldest" "newest".
Basically on the page load TWIG load comment to my view and everything works fine.
Then I want to click on the button to change way of display comments. But want to do this without reloading a page.
I click btn -> run JavaScript -> connect byt AJAX with API controller -> take back data from database ... And here I stuck
I have data in JSON but have no idea how to load them into my view instead a date loaded by Twig at the beginning.
That's a serious wall on my way to dynamic changes on web page.
Thinking about:
Creating all the view in JavaScript and replace twig data on the view using jQuery like .html() or something - but there would be a lot of HTML code in JavaScript script, not sure that's right way
Maybe you know how to solve that issue in more elegant way?

It is not a Twig, but a JQuery concern. Here is an example.
Route:
my_symfony_route:
path: /get-filtered-list
defaults: { _controller: "CompanyMyBundle:Comment:getFilteredList" }
methods: POST
Controller
public function getFilteredListAction(Request $request)
{
$param1= $request->request->get('param1');
$param2= $request->request->get('param2');
$result = array();
//Fill $result with DB request
return new JsonResponse($result);
}
JQuery request
$.ajax({
type: 'POST',
url: "{{ path('my_symfony_route') }}",
data: { param1: 'value', param2: 'value' },
dataType: 'json',
success: function (data) {
//Handle your JSON data to update the DOM
$.each(data, function(index, element) {
$('#myDivId').append($('<div>', {
text: element.name
}));
});
}
});

Related

Cannot access Rails variable inside Javascript tag

All the other solutions in stackoverflow doesn't seem to work for me so i'm posting my code for assistance. I want to output the variable: #less_per_unit via jquery
Here is my tag inside _form.html.erb:
<script>
$(document).on('keyup', ".input-quantity", function(){
$.ajax({
url: "/so_check_increment",
type: "GET",
data: { quantity: $(this).val(), product_id: $(this).closest('tr').find('.input-product_code').val()}
});
$(this).closest('td').next('td').find('.increment').text('<%== j #less_per_unit%>');
});
</script>
And here is my controller:
def check_increment
#less_per_unit = "testing"
end
I know that the ajax works, i've also set up the routes. If I try binding.pry, I know that rails can find #less_per_unit, but I can't output it with javascript.
This is not working because:
Let us say this form is rendered in action 'new' of controller 'Post', then #less_per_unit needs to be initialised there to use it in the view file of that action which you are using. Where as you are using an AJAX call and during that call, you are defining an instance variable which will definitely be not accessible to the already rendered html file.
So, you need to return JSON data from your check_increment action and receive that data in AJAX call response and then use it.

Searchfuntion working with ajax calls in Symfony2

I am coding some basic crud application in Symfony2 where I want to implement some type of search function on a certain page.
The idea is that I want to launch a search query by entering something in an inputfield which is going to fire an ajaxcall (I could not think of anything better). The response of that ajaxcall has to be a kind of popup list with clickable items that is placed into another field on the initial page when clicking an item.
I have two questions:
Is there a better approach than ajax and how can I resolve the problem of the 'popup list' thing.
Second: I can make post ajaxcalls in Symfony2 with this kind of code:
var data = 'test';
$.ajax({
url: "{{ path('test_oost') }}",
data: { data: data },
method: "post",
success: function(data) {
//some things here
}
But I thought it is a bit strange to use post and I wanted to use get.. Apparently this is not working as I can not retrieve my data in the controller..
EDIT: I forgot to post my controller where I am handling the ajax call, here is the code:
public function testGetAction(Request $request)
{
$data = $request->request->get('data');
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('EuropsimProductBundle:SimProfile')->find($data);
return new Response($entity); }
This is working fine with method: "post", but failing when I try to use "get".
I also read about typeahead and this is really close to what I meant, the thing is I want a custom little popup or something because the ajax is supposed to return an array of objects with multiple attributes that has to be shown and where mulitple items are selectable. You can see it as two steps where you first launch the searchquery which bring you to a kind of popup or something where you can select the desired rows for further use on the page.
Thanks in advance!
Hicy
You have to use method $request->query:
For GET method:
$data = $request->query->get('data');
For POST method:
$data = $request->request->get('data');
This really is not much a Symfony2 related question... but...
This code is javascript, if you want to use GET just change method to GET,
var data = 'test';
$.ajax({
url: "{{ path('test_oost') }}",
data: { data: data },
method: "get",
success: function(data) {
//some things here
}
Then in Symfony create the route test_oostand do whatever you want on the controller to send "data" in the response.
Then on te success method process this data accordingly and create the needed view.
EDIT: Based on your new edit, you have an error accessing your data parameter, you should use query instead request
$data = $request->query->get('data');

ASP.NET MVC 5 Ajax controller call not working after publish

I have been working on an ASP.NET MVC 5 web application which includes a view that contains a Raphael javascript image that is using AJAX calls to controller method to get some data on the initial render. When I render the page locally on my own machine, everything executes as expected and the page loads fine. However, when I 'Publish' the application to a test server, the AJAX call hits the 'Error' function every time I try to load the page.
After some research I was able to resolve some of the javascript errors by adding this tag to the layout page:
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
However, it still does not work any time I try to use Ajax to make a call to a controller method. When I take a look at the issue with firebug i see the error that is being thrown is "Boostrap requires JQuery". I have searched the error and have ensured that the script tags are in the correct order- JQuery is being called before Boostrap:
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-1.10.2.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/boostrap.min.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/raphael.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/update.js")"></script>
I have also checked the permissions on the files and they both have the same, correct privs which has left me stuck. These controller calls work exactly as expected when I run the application locally on my machine, but error once I have published the application to a server.
I am not sure what else could be causing this issue. Any and all advice would be greatly appreciated!!!
Below is one of the JQuery call to the controller method:
function GetESN(area, ID) {
$.ajax({
url: "/Home/GetESN",
type: 'POST',
async: false,
dataType: 'json',
cache: false,
data: { area: area, ID: ID },
success: function (data) {
esn = data
},
error: function () {
alert('error occurred');
}
});
}
Please let me know if there any more information that is required.
UPDATE
The issue actually fell in the way the site was named- it needed to be formatted as "http://projectname.com/location". I ended up having to split the pathname to account for the "/location" bit and built the URL right at the beginning of the script. Probably not an ideal situation but it works well for my situation.
It is possible that your
"url: "/Home/GetESN",
is an incorrect url when on the web server than on your local.
Try adding
<script>
rootUrl = '#Url.Content("~")'
</script>
to _Layout.cshtml
Then update your js file so you use the rootUrl
function GetESN(area, ID) {
$.ajax({
url: rootUrl + "Home/GetESN", // or url: rootUrl + "/Home/GetESN"
type: 'POST',
async: false,
dataType: 'json',
cache: false,
data: { area: area, ID: ID },
success: function (data) {
esn = data
},
error: function () {
alert('error occurred');
}
});
There are 2 ways where you can achieve this.
Option 1
change the url as follows in your ajax call,
url: #Url.Action("GetESN", "Home")
Option 2
This is the best option if you want to avoid razor tag helpers.
Right click on the project and select "Properties".
In the properties, select the link called "Web".
In the "Web" link find "Project Url" field.
In the "Project Url", set a name to the project as following example.
Example:- http://localhost:1851/TestApp/
Once setting a project name, select "Create Virtual Directory".
In your ajax call, set the url as follows.
Example:- url: "TestApp/Home/GetESN"
Finally make sure to publish the project as the same name. Example:- TestApp

Using Javascript to Add/Remove Users in Rails Admin Interface

In a Ruby on Rails application, I want to be able to place a User's username in a input text box, press an 'Add' button, and have them appear underneath with their details. Then, I can simply remove them from the list if I want using another button.
How does one connect Javascript and Rails database to complete such a task specifically with those buttons? While Javascript isn't a strength of mine, I'm more puzzled by how to extract and modify the Rails database using Javascript. For reference, I'm also using MongoDB.
What would be the best way to approach this?
Here is the jQuery and AJAX code that I'm using to 'POST' to the server endpoint 'admin/popular/users.json', but I'm not sure how to get Rails to create a new user in the database using my Popular::User model.
$(document).ready(function() {
$('.add-to-popular-users-button').click(function(event){
event.preventDefault();
var addToPopularUsersBtn = $(this);
var userToBeAdded = $('input[name=popular_user]').val();
var data = { 'popular_user': {'username': userToBeAdded, 'category': 'popular'} };
var url = "/admin/popular/users.json";
$.ajax({
url: url,
data: data,
dataType: 'json',
type: 'POST',
success: function(e) {
alert('Great success!');
}
});
});
});
Here's my Popular::User model:
class Popular::User
include Mongoid::Document
include Mongoid::Timestamps
POPULAR = 'popular'
field :category, default: POPULAR
index :user_id
belongs_to :user
validates_presence_of :user_id
validates_uniqueness_of :user_id
def self.popular
user_ids = self.where( :category => POPULAR ).map(&:id)
User.where(:_id.in => user_ids)
end
I am not familiar with rails framework, but you can do it using ajax. You can send an ajax post request to controller method which will creae a user, create a table row(or recreate the table), and returnd html place in table.
A simple example is:
$.ajax({
type:'post',
data:{} //user data,
dataType: 'json', //or any other
url: 'page_or_method', //page or method that will return html
success: function (data) {
$('div#userTable').html(data); //in case data contains the table
}
});
Read about $.ajax method (jQuery), or you can use XMLHttpRequest if you don't whant to use jQuery.
So, I was able to figure this out with a bit of testing. But, basically, you can either do this with AJAX/jQuery or with Rails inherent RESTful architecture, i.e., HTTP verbs like calling :delete, and associating it with a particular UI button.
One important idea that you should recognize with AJAX is that whatever data you send to the right server endpoint with a 'POST' or 'DELETE' verb or what have you, it will get picked up by the appropriate controller action. In other words, if I'm sending data via 'POST' to the '/popular/users.json' endpoint to create something, the def create method will be able to manipulate data afterwards. Then, you can assign the data to an ivar in the controller action to be interpreted and manipulated in the UI view corresponding to the controller action.

Problem about triggering View's $(document).ready handler on Controller response in Spring MVC

We are trying to change our HttpServlet to Spring's DispatcherServlet. We use jQuery and JSP in client side. And there is some dynamic stuff in our pages.
For ex there is
$(document).ready(function(){
window.alert("alerted!");
});
in a blah.jsp. And we are triggering it by calling
$("#myDiv").load("blah.jsp");
from another .jsp
Then I made configurations about Spring MVC. And observe new controllers are totally working.
Here is the problem. Controller returns "blah" View from servlet, it is a html string. And i can't make it's $(document).ready handler trigger when i append it to $("#myDiv").
How can i figure this out?
C.O.
my guess is that the problem is that the script is not being run after the you insert the response payload into the page.
so, i think if you specify a dataType attribute in the ajax call, the scripts should be run once inserted into the document
$.ajax({
url: "blah.jsp",
success: function(data) {
$('#myDiv').html(data);
},
dataType: "html"
});
or
$.get("blah.jsp", null, function(data) {
$('#myDiv').html(data);
}, "html");

Categories