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');
Related
I have the following in my Razor view file:
<button onClick="getFavouriteBooks()">Display Favourites</button>
<script>
function getFavouriteBooks() {
var ids = JSON.parse(localStorage.getItem("bookIds"));
$.ajax({
type: "POST",
url: '#Url.Action("Favourites", "Home")',
data: ids,
dataType: "javascript"
});
}
</script>
And in my Home Controller, this action:
public async Task<ViewResult> Favourites(string[] ids)
{
// var bookList = code that retrieves list of all books
var favouriteBooks = bookList.Any(book => ids.Contains(book.Id));
return View("Index", favouriteBooks);
}
When user clicks 'Display Favourites' I get a 500 error for localhost/Home/Favourites. Can anyone help me see where I've gone wrong here?
Update: bookIds is an array of string Ids.
Update data with added contentType in ajax call as below and check again
function getFavouriteBooks() {
var ids = JSON.parse(localStorage.getItem("bookIds"));
$.ajax({
type: "POST",
url: '#Url.Action("Favourites", "Home")',
// jQuery refers below mentioned contentType to serialize data in JSON format
// Without this, serialization will be url encoded string
contentType: "application/json; charset=utf-8",
// Assuming ids as a array of strings
// data to be an object that holds Action methods parameters as it's properties
// Stringify object before assigning to data
data: JSON.stringify({
ids: ids
}),
dataType: "javascript"
});
}
So I think there is a couple of things going on here.
I am assuming it’s a “get” request not a “post” request. Since you want to display the books. If you want to “get” all that match an id the easiest way would be to get the total response and loop through it. If it is just for a small project if it’s serious you want to want to change your SQL to find where ID.
But assuming you just want assistance with the JavaScript.
First of all if you put your javascript in line like that you need to also handle the response in line which isn't going to be syntactically very friendly. After all we are not writing php.
The second point about async functions is that you need a response which will happen asynchronously so need to await. Also need to handle the promise
I have simplified what I think is the solution here to use fetch instead of ajax to avoid all the jquery and Ajax setup with code pen but the logic should be there for you to follow up.
https://codepen.io/sijbc/pen/qBRrgBG?editors=1111
fetch('https://api.github.com/users')
.then(res => res.json())//response type
.then(data => console.log(data))
Also found this article which would be worth checking out
https://medium.com/front-end-weekly/ajax-async-callback-promise-e98f8074ebd7
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
}));
});
}
});
I try to store the data from a graph with jQuery but I always get a 400 Bad request.
The problem is the data_series variable isnt just an array of integers but much more. This is unchangeable since it is necessary for my chart generation to be like this.
A litle piece of it to show you what I mean:
data_series[0][data][0][]:1389975624000
data_series[0][data][0][]:91
data_series[0][data][1][]:1390003200000
data_series[0][data][1][]:446
data_series[0][data][2][]:1390089600000
data_series[0][data][2][]:429
.....
My Jquery post looks like this,
$.ajax({
url: "{{ url_for('save_graph_to_session') }}",
method: "POST",
data: {
data_series: data_series
},
success: function(data) {
console.log('Saved to session')
}
});
On flask side I read it like this, and put in a session:
#app.route('/save_graph_to_session', methods=[ 'POST'])
def save_graph_to_session():
session['data_series'] = request.form['data_series'];
return "saved"
I've tried to post with 'data_series[]:' data_series, didn't work out either.
EDIT:
Maybe the solution lies within the way to request, so :
Is there a way to request in flask that ignores the fact that this is an array of arrays
this is the way one can do this:
session['data_series'] = request.form.getlist('data_series[]');
I'm taking an input from user named as category. On every key up i want to perform an ajax request to search if category with the similar name exists or not. If yes, then a there is a blank div below that input which i want to fill with the similar name categories.
So i created a form. Used ajax via jquery but i'm not receiving the response.
This is the jquery ajax code that i'm using
$("#category").keyup(function () {
$.ajax({
url: "categories/categoryajaxrequest",
type: "get",
data: {
category: $("#category").val()
},
success: function (response) {
$("#category_suggestion").html(response);
}
});
});
This is the route part which is used as url in ajax request
Route::get('categories/categoryajaxrequest', array('as' =>'categoryajaxrequest', 'uses' =>'CategoryController#categoryAjaxRequest'));
and this is the controller part
//app/controllers/CategoryController.php
....
public function categoryAjaxRequest(){
echo "working";
}
So, the input text has an id of "category" and below the input, there is a div with an id of "category_suggestion". At every keyup on the input, i expect it to perform an ajax request and show "success" in div . But it's not doing anything.
However, if i go directly to "/categories/categoryajaxrequest" on my browser, it outputs "working".
Try putting the action directly in the url: property of the $.ajax() method, then no route is needed:
Laravel gives us the liberty to do that. The curly braces {{ }} are used in views. As the JavaScript stuff is usually called in a view, it is legitim to do it that way.
The URL::action part is described in the docs as follows:
To generate a URL to a controller action, we may use the URL::action
method or the action helper method:
$url = URL::action('FooController#method');
$url = action('FooController#method');
So the combination of the template system & the URL::action gives us the possibility of doing it this way:
$("#category").keyup(function () {
$.ajax({
url: "{{URL::action('CategoryController#categoryAjaxRequest')}}",
type: "get",
data: {
category: $("#category").val()
},
success: function (response) {
$("#category_suggestion").html(response);
}
});
});
All the examples of json I can find online only show how to submit json arrays w/ the jquery command $.ajax(). I'm submitting some data from a custom user control as a json array. I was wondering if it's possible to submit a json array as a regular post request to the server (like a normal form) so the browser renders the page returned.
Controller:
[JsonFilter(Param = "record", JsonDataType = typeof(TitleViewModel))]
public ActionResult SaveTitle(TitleViewModel record)
{
// save the title.
return RedirectToAction("Index", new { titleId = tid });
}
Javascript:
function SaveTitle() {
var titledata = GetData();
$.ajax({
url: "/Listing/SaveTitle",
type: "POST",
data: titledata,
contentType: "application/json; charset=utf-8",
});
}
Which is called from a save button. Everything works fine but the browser stays on the page after submitting. I was thinking of returning some kind of custom xml from the server and do javascript redirect but it seems like a very hacky way of doing things. Any help would be greatly appreciated.
This is an old question but this might be useful for anyone finding it --
You could return a JsonResult with your new titleId from the web page
public ActionResult SaveTitle(TitleViewModel record) {
string tId = //save the title
return Json(tId)
}
and then on your ajax request add a success function:
function SaveTitle() {
var titledata = GetData();
$.ajax({
url: "/Listing/SaveTitle",
type: "POST",
data: titledata,
contentType: "application/json; charset=utf-8",
success: function(data) { window.location = "/Listing/Index?titleId=" + data; }
});
}
That would redirect the page after a successful ajax request.
I just saw that you mentioned this at the end of your post but I think it is an easy and quick way of getting around the issue.
Phil Haack has a nice post discussing this scenario and shows the usage of a custom value provider instead of an action filter.
I don't understand why you would want to post Json if you're wanting to do a full page post. Why not just post normal form variables from the Html form element?