How to setup an ajax call using symfony2 - symfony

I have this simply ajax/jquery call to a symfony2 controller/action
$.ajax({
type: 'post',
url: 'http://symfony.local:8080/app_dev.php/api/searches/guitar.json',
success: function(results) {
}
});
I'd need to change the first part of the url 'http://symfony.local:8080/app_dev.php/api/searches/guitar.json' in order to make it independent from the front controller I'm using. How can I achieve this?

First, why are you supplying the whole URL? You could omit the domain part so that the path is relative:
$.ajax({
type: 'post',
url: '/app_dev.php/api/searches/guitar.json',
success: function(results) {
}
});
Second, you can set up the prefix for your AJAX calls in a Symfony view:
<script type="text/javascript"></script>
{% if app.environment == 'dev' %}
var root = '/app_dev.php/';
{% else %}
var root = '/';
{% endif %}
</script>
I've introduced a window.root variable here. You can use it in your scripts then:
// ...
url: root + '/api/searches/guitar.json',
// ...
And as suggested in the comments, the best way here would be passing the URL to your scripts with a separate routing provider for JavaScript.

You could set the url as the href and catch it or set it as some of data tag.
As href
Your link
Link
And the javascript
$('a.ajax-link', function (e) {
e.preventDefault();
// Stop link updating page
var href = $(this).attr('href);
$.ajax({
type: 'post',
url: href,
....
});
});
Or as a data field
Your link
<a data-href="{{ path('your_route') }}" class="ajax-link">Link</a>
And the javascript
$('a.ajax-link', function (e) {
e.preventDefault();
// Stop link updating page
var href = $(this).data('href);
... see above ...
});
With either of these ways there is no use for FOSJsRouting or hard coded routes.

Related

button in ASP.NET are all post method?

Are all button control has to be post method? or we can set it to get method, for example, I want to see an employee details by giving employeeId and click submit button
There is no difference between GET and POST method. They both provide url and parameters. POST method only have some advantages and some restrictions.
If your button is on form (as in classic asp.net), and there is no javascript handler for this button - only POST method can be here.
If you create jquery code (or pure javascript), that overrides default behaviour of the button, you can select what method use: POST or GET
<script>
$('#button').click(function() {
$.ajax({
url: '....',
data: { ....},
type: 'GET', //or 'POST'
success: function(res) {
//all fine
},
error: function() {
//invalid url or server error
}
};
return false; //to avoid default submit
});
</script>

Laravel/dropzone - TokenMismatchException in VerifyCsrfToken.php line 68

I am trying to setup a dropzone image file upload in my Laravel 5.3 app, but whenever I try to upload an image I get a above mentioned error. I am sending a csrf_token in my script like this, so not sure why I get this error?
var token = "{{ csrf_token() }}";
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("div#dropzoneFileUpload", {
url: "/admin/upload",
params: {
_token: token
}
});
Follow these steps, I hope that will solve your problem..
Add this line into your head tag section
<meta name="csrf-token" content="{!! csrf_token() !!}">
and then add these lines before your </body> end/closing section.
var csrf_token = $('meta[name="csrf-token"]').attr('content');
$.ajaxSetup({
headers: {"X-CSRF-TOKEN": csrf_token}
});
so, after doing above steps, you dont need to send token into your dropzone ajax request. eg
params: {
_token: token // dont need this line after following above steps
}

How to manually render a template in Meteor?

The Discover Meteor book shows how to use the sasha:spin package to show a loading spinner template (<template name="loading">) while IronRouter waits for data.
How do I use this same loading template while I'm waiting for a regular jQuery ajax call to finish?
var locationInfoByZipcode = function(zipcode, callback){
$.ajax({
url: "http://api.zippopotam.us/us/" + zipcode,
type: "GET",
beforeSend: function(){
// Render the loading template. I tried Blaze.render("loading") but I'm not using it right
}.
success: function(response){
// Stop the loading template.
},
error: function(){
callback("error");
}
});
};
Blaze.render takes a template and a parent, not a string, so it'd be Template.loading and then the parent template you want to render into. You'd probably want to destroy it in the success callback.
What might be a little bit cleaner is putting the HTTP req inside a method along with a reactive variable & calling that method on click. Then, you can keep the loading template inside an #if reactiveVarIsTrue type thing in spacebars. Just a personal preference to not use jquery ajax calls if I can help it because they're not very expressive.
I got it.
var locationInfoByZipcode = function(zipcode, callback){
var renderedView = {};
$.ajax({
url: "http://api.zippopotam.us/us/" + zipcode,
type: "GET",
beforeSend: function(){
// $('body')[0] is the DOM node object that .render() needs
renderedView = Blaze.render( Template.loading, $('body')[0] );
},
success: function(response){
// to remove the template you need to pass Blaze.remove() the returned value from the initial Blaze.render() call
Blaze.remove(renderedView);
callback(response);
},
error: function(){
callback("error");
}
});
};

Reload a specific controller after Ajax Call

I have embed a controller in a template:
{% render "AcmeUserBundle:User:showUsersList"} %}
<a onClick="changeStatus({{user.getUserId()}})"
The aim is simple:
The user clicks on the link which updates the status via ajax (this works fine)
Reload the embedded controller only, not the entire page!
At the moment, I managed to do this, by reloading the entire page using document.location.reload(true); This has no point so far...
Here is the ajax part:
//...
function changeStatus(userId){
$.ajax({
type: "POST",
url: ajaxControllerPath,
data: "userId="+userId,
success: function(){
document.location.reload(true);
}
});
}
How would you reload the embedded controller only?
This is working so far:
Embed the controller within a div:
<div id="block1">
<a onClick="changeStatus({{user.getUserId()}})"
</div>
And reload the controller using javascript at the end of the ajax call
$('#block1').load("{{ path('show_users_list') }}");
Does anyone have a better suggestion?
When you call the ajax controller, this controller could render the showUsersList template and return the generated html as a json object:
$answer['html'] = $this->forward('AcmeUserBundle:User:showUsersList')->getContent();
$response = new Response();
$response->headers->set('Content-type', 'application/json; charset=utf-8');
$response->setContent(json_encode($answer));
return $response
Then in your javascript use this generated html to replace the content of the controller part of the page (use a div or similar to identify it)
<div id="changethis">{% render "AcmeUserBundle:User:showUsersList"} %}</div>
function changeStatus(userId){
$.ajax({
type: "POST",
url: ajaxControllerPath,
data: "userId="+userId,
success: function(returnData){
$('#changethis').html(returnData['html']);
}
});
}

How to post parameter value to some actionlink

In my view i have 10 link every link associated with some unique value. Now i want that associated value at my controller action and from that action i want to redirect the flow to some other action based on that value.
But the condition is i dont want to display it on url.
How can i acheive this?
I tried ajax.post/#Ajax.ActionLink but doing this will not facilitate redirect to another action.
Is there anything with route i need to do?
View
<ul>#foreach (var item in Model)
{<li>
#Ajax.ActionLink(item.pk_name, "Index","Candidate", new { para1= item.para1 }
, new AjaxOptions { HttpMethod = "POST" })</li>
}</ul>
Action
[HttPost]
public ActionResult(int para1)
{
return RedirectToAction(para1,"anotherController");
}
I am getting value at para1 with ajax post(that is what i primarily needed) but here also want to redirect my application flow base on para1 value which is action name.
Confision : here i am not sure is this is the right way to do this thing. So i am asking you guys should i go for route map of working with ajax post will solve my objective.
If you only need to redirect the user based on what he clicks on without showing him the link, I believe the best way to achieve this is by client-side coding.
In my opinion there is no need to take any request through the server in order to change the page for such a low-complexity redirect.
View
// HTML
// Might be broken, been awhile since I worked with MVC
// Can't really remember if that's how you put variables in HTML
<ul id="button-list">
#foreach(var item in Model)
{
<li class="buttonish" data-para1="#item.para1">#item.pk_name</li>
}
</ul>
// JS
// I wouldn't do any server related work
$('#button-list li.buttonish').click(function(){
// Your controller and action just seem to redirect to another controller and send in the parameter
window.location.href = "/controller/method/" + $(this).data('para1');
});
I think you should make one jQuery function that is call when clicked and pass unique parameter.In that function you can use AJAX and post it on appropriate controller method.
Example:
<input type="button" id="#item.pk_name" onclick="getbuttonvalue(#item.para1);" />
In script
<script type="text/javascript">
$(document).ready(function () {
function getbuttonvalue(para1) {
$.ajax({
cache: false,
type: "POST",
dataType: 'json',
url: "/controller/method/" + para1,
success: function (data) {
}
});
}
});
</script>

Resources