Symfony2 Ajax app_dev.php in url - ajax

Just starting out in Symfony2 and really loving it after being a long time ZF1 developer.
Started to add some Ajax functionality to a site tonight and am a bit confused about the following.
in my ajax call eg:
$.ajax({
url: '/app_dev.php/ajax/urlgetter',
data: "url="+urlinput,
dataType: 'html',
timeout: 5000,
success: function(data, status){
// DO Stuff here
}
});
I had to add /app_dev.php to the url to make it work in dev environment. Is there not a better way of doing this? Does this mean when I change the project to a production environment I need to search and replace all instances of /app_dev.php?? Hopefully I have totally missed something simple.

I ended up using the jsrouting-bundle
Once installed I could simply do the following:
$.ajax({
url: Routing.generate('urlgetter'),
data: "url="+urlinput,
dataType: 'html',
timeout: 5000,
success: function(data, status){
// DO Stuff here
}
});
where urlgetter is a route defined in routing.yml like:
urlgetter:
pattern: /ajax/urlgetter
defaults: { _controller: MyAjaxBundle:SomeController:urlgetter }
options:
expose: true
notice the expose: true option has to be set for the route to work with jsrouting-bundle

I guess this question is already kind of old but I came across the same problem.
Its not any "best practice" solution but here is what I do.
In twig you can use this {{ path('yourRouteName') }} thing in a perfect way. So in my twig file I have a structure like that:
...
<a href="{{ path('myRoute') }}"> //results in e.g http://localhost/app_dev.php/myRoute
<div id="clickMe">Click</div>
</a>
Now if someone clicks the div, I do the following in my .js file:
$('#clickMe').on('click', function(event) {
event.preventDefault(); //prevents the default a href behaviour
var url = $(this).closest('a').attr('href');
$.ajax({
url: url,
method: 'POST',
success: function(data) {
console.log('GENIUS!');
}
});
});
I know that this is not a solution for every situation where you want to trigger an Ajax request but I just leave this here and perhaps somebody thinks it's useful :)

Since this jQuery ajax function is placed on twig side and the url points to your application you can insert routing path
$.ajax({
url: '{{ path("your_ajax_routing") }}',
data: "url="+urlinput,
dataType: 'html',
timeout: 5000,
success: function(data, status){
// DO Stuff here
}
});

Related

Laravel ajax post not working even though CSRF token included

I am having difficulty getting an ajax post to work with laravel v5.5.24. Here is what my ajax call looks like:
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "/postCustomer?XDEBUG_SESSION_START=19683",
type: 'POST',
data: {_token: CSRF_TOKEN, message:myData, "_method": 'POST'},
dataType: 'JSON',
success: function (data) {
console.log('call to postCustomer successful');
}
});
Here is my route:
Route::post('/postCustomer','AdminUserController#store');
The interesting thing about this problem is that when all the post's are changed to get's (both in the ajax call and in the route) the request arrives and is handled correctly. The debug is triggered, and all is well. However, iof the route and the ajax call is set to POST, the debug is never triggered, and the request does not appear to make it. Naturally this smells like a CRSF issue, but I am including the CRSF token in the header.
if the javascript code inside .blade.php file try this
data: {_token:'{{ csrf_field() }}', message:myData, "_method": 'POST'},
hope its help
Try this,
<meta name="_token" content="{!! csrf_token() !!}"/>
$.ajaxSetup({
headers:
{'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')}
});
$.ajax({
url: "/postCustomer?XDEBUG_SESSION_START=19683",
type: 'POST',
data: {message:myData, "_method": 'POST'},
dataType: 'JSON',
success: function (data) {
console.log('call to postCustomer successful');
}});
No need to pass token in ajax data again.
Heartfelt thanks to everyone who responded. A couple of things helpled in fuguring this thing out. First of all, I consolidated the CSRF token mentions,
and confined what I was sending as data to just that - no need to include the CSRF token in the data if you do it in the ajaxSetup. The second thing wasn't visible from my post, but I was encountering a race condition involving the button that triggered the ajax transaction. The button was causing a page reload before ajax could do its thing, and this is why occasionally the thing would appear to work, but mostly not. So the return false is necessary to prevent that - probably not in both places, but certainly after the ajax transaction has been invoked and we are waiting for the callback. The code which works can be found below. I hope it will prevent somebody else from spending a night going mad trying how to figure out what their POST's aren't working. Take away points: handle your CSRF in an ajaxSetup call, and return false from the whole business.
Thanks again to everybody.
-George Pipkin
Afton, Virginia
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
/* the route pointing to the post function */
url: "/postCustomer?XDEBUG_SESSION_START=19159",
type: 'POST',
/* send the csrf-token and the input to the controller */
data: {message:myData},
dataType: 'json',
/* remind that 'data' is the response of the AjaxController */
success: function (data) {
$("#success_msg").show();
return false;
}
});
return false;
You should have to pass the _token inside the data object.
data: {_token:'{{ csrf_token() }}',, message:myData, "_method": 'POST'},

Meteor HTTP.call and jquery ajax

I would like to use Meteor.call('GET') instead of $.ajax(). I have an ajax call as the following:
$.ajax({
url: url,
crossDomain:true,
type: method,
data: query,
dataType: 'json'
}).done(function(data) {
_tokens.request = {
token: data.oauth_token,
secret: data.oauth_token_secret.split('')
};
});
Have some options but I don't know how to pass to Meteor.call(). Please help!
Thank you so much
You probably mean HTTP.call or HTTP.get. Meteor.call is related to another concept.
http://docs.meteor.com/#/full/http_get

NotFoundHttpException: No route found for "POST / in SYmfony2

I have an ajax posted form causing me to want to pull my hair having tried various answers based on almost similar problems here to no avail.
I have the following route in my routing.yml file
_save_profile:
pattern: /register/save-profile/{data}
defaults: {_controller: MYBundle:Registration:saveProfile}
requirements:
_method: GET|POST
options:
expose: true
and use the following code to post my form
var postData = $('#form').serializeArray();
$.ajax(
{
url: Routing.generate('_save_profile',{
type: "POST",
data : postData,
}).done(function()
{
alert("Saved");
});
Any help will be much appreciated.
You don't need send form data through parameter {data} in route. If you want send form with ajax, so you need.
Change route:
_save_profile:
pattern: /register/save-profile/
defaults: {_controller: MYBundle:Registration:saveProfile}
Change js:
var postData = $('#form').serializeArray();
$.ajax({
url: Routing.generate('_save_profile'),
type: "POST",
data: postData,
dataType: "json",
success:
function(result) {
console.log(result);
},
error:
function() {
alert('Error')
}
});
note: I don't use FOSJsRoutingBundle bundle for js routing. I always render route on template in data attribute. For example.
html
<form type="POST" id="form" data-url="path('_save_profile')">
js
var url = $('#form').data('url');
References
How to implement a simple Registration Form
FOSJsRoutingBundle documentation

Linking AJAX with PHP code. Do i need to write it again?

I have a real problem. I have a php code and a form where when the form is submitted a POST request is sent and the page reloads again and ofcourse the post is viwed in the page.But i want to work with AJAX in order page not to be refreshed.I know the basics of AJAX but i don't want to build all the project from the beggining.Is there a way in success function of AJAX to link to my php code??
$.ajax({
type: "POST",
url: "index.php",
datatype: "html",
data: dataString,
success: function(data) {
//How can i link here to start running my php code which is located in the same page.
}
});
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
// try this
console.log(data);
// see what 'data' actually is
}
});
then check in the browser by hitting F12 to look at the console.
also are you sure you want datatype of html ? you probably want a data type of json or XML , what is the server returning to you after the ajax post?
You have to cancel the form's submission so that the ajax request will take place, otherwise it is canceled. Also use .serialize to get a name-value pair string of the form data to use in the ajax call.
Html
<form id="MyForm">
<button id="MyButtonId">Submit</button>
</form>
JS
$("#MyForm").submit(function(e){
//Prevents the form from being submitted
e.preventDefault();
$.ajax({
type: "POST",
data: $("#MyForm").serialize(),
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
alert(data);
}
});
});

AJAX on click not calling/loading as it should

I have been learning AJAX for the best part of 2 hours, trying to get my head around how to get this to work, it seems it is calling the function as if I put an alert in, it all works fine.
I tried using another method and it seemed to call the function on it's own and it would load what the .php page is echoing.
What am I doing wrong in order for it to not work at all?
<script type="text/javascript">
$('a.fire').click(call_ajax);
function call_ajax() {
$.ajax({
type: "GET",
url: "http://127.0.0.1/onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
}
});
}
</script>
Edit: I have also just tried
$('a.fire').click(function() {
$.ajax({
type: "GET",
url: "http://127.0.0.1/onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
}
});
});
Which also does not work.
EDIT: I have now got code that GET's the php file I wanted, but for some reason does it on it's own
<script type="text/javascript">
function call_ajax() {
$.ajax({
type: "GET",
url: "http://127.0.0.1/onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
}
});
}
<script type="text/javascript">
$(function() {
$(document).ready(function() {
$('a.fire').click(call_ajax());
});
});
The issue with this code is that it fires on it's own
EDIT: Now have new code, that is attempting to fire according to Firebug console but I get the alert ERROR: error, so I don't have a clue what is happening in order for it to fail, I have also tried many different URL's with no working solution
$('a.fire').click(function () {
$.ajax({
type: "GET",
url: "/onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
},
error:function(xhr, text, error){
alert("Error: " + text);
}
});
});
SOLVED: I have now got it to work! For some reason my anchor had a href of "", which would cause it to reload the page and removing my GET from the page
ajax will only work if it's the same domain. This means that if you execute jQuery from domain x to domain y, it won't work. This is for safety-reasons to prevent websites from loading from another website. Does your jQuery-ajax call work if you remove the 127.0.0.1 from your url?
Furthermore I guess you should add the click-function inside your $(document).ready(); function, like this:
$(document).ready(function(){
$('a.fire').click(function() {
$.ajax({
type: "GET",
url: "onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
}
});
});
});
for testing purposes, you can also use the complete function inside your ajax and alert your data. firebug can be helpful too to find your problem :)

Resources