Ajax not reciving data. Symfony2 - ajax

The idea is when i click on a button it calls sendeRequest() and the controller receives the petition. But I'm not receiving anything.
I wan't to send a request to the controller. (I have set a redirection in the controller, to check that I'm receiving the data). I've tried doing:
function sendRequest(){
$.ajax({
type: "POST",
url: "{{ path('login') }}" ,
cache: "false",
dataType: "html",
success: function(result){ $("div#box").append(result);}
});
}
And in the controller
$request = $this->getRequest();
if($request->isXmlHttpRequest()){
return $this->render('mainBundle:Register:register.html.twig');
}
I'm using jquery 1.7.2

You can do this:
if($this->getRequest()->isXmlHttpRequest()){
return new Response(json_encode(array(
'form'=>$this->render('mainBundle:Register:register.html.twig')->getContent()))
);
}

Related

Laravel 8 Method Not Allowed 405 Ajax CRUD

I fixed my csrf
I fixed my route , route clear too
but still error show up .
I'm doing ajax form in modal :
My Route
Route::post('increp/store',[\App\Http\Controllers\IncrepController::class,'store'])->name('increp.store');
My ajax
// Create article Ajax request.
$('#submit_increp').click(function(e) {
e.preventDefault();
var data = $("#main-form").serialize();
$.ajax({
url: "{{ route('increp.store') }}",
type: 'POST',
data: data,
dataType: 'json',
beforeSend:function(){
$(document).find('span.error-text').text('');
},
success: function(result) {
if(result.errors) {
console.log(result.errors);
$('.alert-danger').html('');
$.each(result.errors, function(key, val) {
$('span.'+key+'_error').text(val[0]);
});
} else {
$('.alert-danger').hide();
$('.alert-success').show();
}
}
});
});
I doing this for days, i dont have idea how to fix this errors .
Network tab
Console tab

AJAX POST Request in Laravel says url not found

I am trying to post data to a controller through ajax request. But it can't find the route and says the following in console.
POST http://127.0.0.1:8000/addNotification_action 404 (Not Found)
This is my ajax call below.
function editNotification(obj) {
// alert(obj.id);
var obj_id = obj.id;
var id = obj_id.split("_");
$.ajax({
url: "{{ url('addNotification_action') }}",
type: 'POST',
dataType: 'json',
data: {edit_notification_id: id[1]},
})
.done(function(result) {
console.log(result);
$('#title').val(result['title']);
$('#description_notification').val(result['details']);
$('#edit_flag_notification').val(result['notification_id']);
})
.fail(function() {
alert("error");
});
}
And I am just trying to dd() the request I get in the controller. Please help. Thanks
First of all, you should create a route and give this route a name. You have to generate the ajax url as "route('route_name')".
// Route (for Laravel 8)
Route::post('addNotification_action', [NotificationController::class, 'notify_method'])->name('notify');
// Ajax Settings
....
url: "{{ route('notify') }}",
....
Jus Give admin/addNotification_action in Ajax URL

Is there way to get anything in ajax success response with MVC action returning emptyresult()

i have a controller action e.g create() that returns emptyresult() in it after doing some back end work . i am calling my create() action through ajax . Now if the back-end work is successful i want to do something back in jquery in ajax success . How should i do that ?
public ActionResult Create(string id)
{
//does something
return new EmptyResult();
}
and i want to do something in my ajax success portion now
$.ajax({
type: "POST",
url: "#Url.Action("Create", "controller")",
data: "{Id:'" + id + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (response) {
alert();
$("#getoptionSp").empty();
$("#getoptionSp").append("<div>Pending<div>");
},
error: function () {
}
})
i want to change the front end with jquery .. how can i do this if action return empty result . i cant return view it will be messier for the code .
well i got the answer while trying just return
return Json("",JsonRequestBehavior.AllowGet);
and we are good to go for the ajax success response .

yii Ajax call not going to correct action

I have the following link to make my ajax call in yii2:
echo Html::a('Load more','ajaxShowMoreProducts', [
'onclick'=>"console.log('Load more');
$.ajax({
type:'POST',
cache: false,
url: 'ajaxShowMoreProducts',
success: function(response) {
console.log('suc');
}
});return false;",
]);
Then I have an action in my SiteController:
/**
* #return string|\yii\web\Response
*/
public function actionAjaxShowMoreProducts() {
var_dump('in');die;
$params = [];
$productModel = new Product();
$params['products'] = $productModel->getAll();
$this->renderPartial('partialProductItem', $params);
}
However when I click the link,the correct controller action does not seem to be called. Its still calling site/index. Any ideas what I have to do to get this working? Have i forgotten some sort of annotation or maybe I have to define my new action somewhere?
When I look in the console, it looks correct:
Request URL: http://localhost:8080/site/ajaxShowMoreProducts
In yii2 you should use the proper notation for action url (in url calling si not used the camelNotation but the words are separated by - (minus)
echo Html::a('Load more','ajax-show-more-products', [
and in ajax url too
url: 'ajax-show-more-products',
or try using Url Helper
use yii\helpers\Url;
....
echo Html::a('Load more', Url::to(['/site/ajax-show-more-products']), [
'onclick'=>"console.log('Load more');
$.ajax({
type:'POST',
cache: false,
url: '" . Url::to(['/site/ajax-show-more-products']) . "',
success: function(response) {
console.log('suc');
}
});return false;",
]);

Jquery ajax returning null values back to controller - MVC3

I'm using jQuery ajax to build a viewmodel list and then trying to send that viewmodel to another ActionResult in order to create PartialViews. The first part works well, and I'm able to create the viewmodel (List), but when I try to send the viewmodel back to the controller to build up the partial views, everything within the viewmodel is 0. It returns the correct number of items in the list, but it seems to lose the values.
Can anyone see if I'm missing anything here?
jQuery:
$.ajax({
async: false,
type: 'GET',
dataType: "json",
url: '#Url.Action("GetMapDetails")',
success: function (data) {
$.ajax({
async: false,
type: 'POST',
dataType: "json",
url: '#Url.Action("GetMapItems")',
data: {
list: data
},
success: function (list) {
//callback
});
}
});
}
});
and the controller:
public ActionResult GetMapDetails()
{
List<ViewModel> vm = new List<ViewModel>();
//create viewmodel here
return Json(vm.ToArray(), JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult GetMapItems(List<ViewModel> list)
{
return PartialView("_MapItemsPartial", list);
}
I've tried also using contentType: 'application/json' and JSON.stringify(data) but that gave me an Invalid JSON primitive error.
Any help appreciated - thanks
You could send them as JSON request:
$.ajax({
async: false,
type: 'POST',
contentType: 'application/json',
url: '#Url.Action("GetMapItems")',
data: JSON.stringify({
list: data
}),
success: function (result) {
//callback
}
});
Also notice that I have removed the dataType: 'json' parameter because your GetMapItems POST controller action doesn't return any JSON. It returns a PartialView. So I guess you did something wrong and this is not what it was meant to be returned from this controller action because from what I can see in your success callback you are expecting to manipulate JSON.
Oh, and please remove this async:false => it defeats the whole purpose of AJAX as you are no longer doing any AJAX, you are now doing SJAX.

Resources