error with jsrouting-bundle symfony - javascript

I have installed the jsrouting-bundle, and this is my code:
Javascript:
$(document).ready(function () {
$(".pmcontents").hide();
$(".pmbox").click(function () {
$(this).css("font-weight", "normal");
$(this).next().toggle();
var myValue = $('this').attr('id');
var DATA = 'sentValue=' + myValue;
$.ajax({
type: "POST",
url: Routing.generate('isread'),
data: DATA,
cache: false,
success: function (data) {
alert("database has been updated");
}
});
});
});
Controller:
public function isreadAction() {
$request = $this->get('request');
if ($request->isXmlHttpRequest()) {
var_dump($request->request->get('sentValue'));
$em = $this->getDoctrine()->getEntityManager();
$pm = $this->getDoctrine()
->getRepository('LoginLoginBundle:Privatemessage')
->findBypmid($request->request->get('sentValue'));
$pm->setIsRead(true);
$em->flush();
return new Response();
}
}
Routing:
isread:
path: /game/isread
defaults: { _controller: LoginLoginBundle:Default:isread }
requirements:
_method: POST
I get the following error in my console:µ
Error: The route "isread" does not exist.
So along with the errors that I get on the image below this should be my problem, however I don't know what I have done wrong.

You need to expose the route, like:
isread:
path: /game/isread
defaults: { _controller: LoginLoginBundle:Default:isread }
requirements:
_method: POST
options: # < add these two
expose: true # < lines
» manual

Related

Server Error in '/' Application on mvc jquery

he partial view Views/Shared/_RoomDetailsPartial.cshtml was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Room/Views/Shared/_RoomDetailsPartial.cshtml.aspx
hey so I'm getting this error and I have no idea why.
here is my js code in index:
function LoadRoomDetail() {
//divLoadRoomDetails
$.ajax({
async: true,
data: 'GET',
contentType: false,
processData: false,
url: '/Room/GetAllRooms',
success: function (data) {
$("#divLoadRoomDetails").html(data);
},
error: function () {
alert('There is a problem! Fix it.');
}
});
}
here is my RoomControler
public PartialViewResult GetAllRooms()
{
IEnumerable<RoomDetailsViewModel> listOfRoomDetailsViewModels =
(from objRoom in objHMSdbEntities.Rooms
join objBooking in objHMSdbEntities.BookingStatus on objRoom.BookingStatusId equals objBooking
.BookingStatusId
join objRoomType in objHMSdbEntities.RoomTypes on objRoom.RoomTypeId equals objRoomType.RoomTypeId
select new RoomDetailsViewModel()
{
RoomNumber = objRoom.RoomNumber,
RoomDescription = objRoom.RoomDescription,
RoomCapacity = objRoom.RoomCapacity,
RoomPrice = objRoom.RoomPrice,
BookingStatus = objBooking.BookingStatus,
RoomType = objRoomType.RoomTypeName,
RoomId = objRoom.RoomId
}).ToList();
return PartialView("Views/Shared/_RoomDetailsPartial.cshtml", listOfRoomDetailsViewModels);
}

symfony Redirect to an other page after true comparison of request from ajax

I have a function in my JavaScript that returns data. I would like to send data to my controller and do a test with that data from my js. Then, if true, I want to display another page.
$.ajax({
type: "POST",
url: path,
data: { s_certifiedNir: a.Patients[0].s_certifiedNir },
success: function (data) {
console.log('yooo' + a.Patients[0].s_certifiedNir) ;
}
,
error: function () {
alert('ko');
}
});
Here is my controller :
public function getCpsInfosAction(Request $request)
{
$nir= $request->get('s_certifiedNir');
if ($request->isXmlHttpRequest()) {
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$data = $serializer->normalize($nir);
if ($data=='2550699999999 34')
{
return $this->redirectToRoute('test');
}
//return new JsonResponse($data);
}
}
I got ko and There are no registered paths for namespace " DMP".
DMP is the first route of my page.
Why not just set the redirect URL in the response and handle it in your JS?:
public function getCpsInfosAction(Request $request)
{
if ($request->isXmlHttpRequest()) {
// ...
if ($data === '2550699999999 34') {
return new JsonResponse([
'success' => true,
'redirect' => $this->generateUrl('your_route');
]);
}
return new JsonResponse(['success' => false]); // else..
}
}
Then just run the redirect from JavaScript:
$.ajax({
// ...
success: function (data) {
if (data.success) {
window.location.href = data.redirect; // <-- HERE
}
},
// ...
});

Laravel 5.3 AJAX login doesn't redirect

I have similar issue like this one.
I'm trying to make AJAX login using Laravel 5.3 Auth.
Here's what I got so far:
var login = function()
{
var data = {};
data["email"] = $('#email').val();
data["password"] = $('#password').val();
if($('#remember').is(':checked'))
data["remember"] = "on";
$.ajax({
type: "POST",
url: '/login',
data: JSON.stringify(data),
// data: data,
headers : { 'Content-Type': 'application/json' },
success: function(data) {
console.log(data);
// window.location.href = "/dashboard";
}
});
};
I'm sending CRSF token as X-CSRF-TOKEN header.
The problem is that when I successfully login, I say on the same page,
but in Network tab I can see that /dashboard page is loaded by I'm not
redirected.
In the same manner, when I pass wrong credentials, I stay on the same page,
but I can see that /login page is loaded in the separate call with an error message that should be actually displayed.
Also, I've tried without headers : { 'Content-Type': 'application/json' },
and sending data as: data = data, but I get the same thing.
Why the browser doesn't redirect to that page since it is loading it in the "background"?
Edit: I'm getting correct page as request response as well, I can see it
in console (console.log(data);).
//Login FORM
$(document).on('submit', 'form#FormID', function(e) {
e.preventDefault();
var forms = document.querySelector('form#FormID');
var request = new XMLHttpRequest();
var formDatas = new FormData(forms);
request.open('post','/login');
request.send(formDatas);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
if (request.responseText == 'success') {
setTimeout(function() {
window.location.href = "/dashboard";
}, 5000);
}else{
};
}
}
}
});
//Controller
public function authUser(Request $request){
$data = $request->except('_token');
$validate = \Validator::make($data, [
'email' => 'email'
]);
if ($validate->fails())
return 'Invalid email format for username.';
if (\Auth::attempt($data)) {
return 'success';
}else{
return 'Invalid username or password';
}
}
//Route
Route::post('/login', 'YourController#authUser');
The problem might be with the response AJAX request is expecting before redirect.
Try the above code.
in the controller method
function login(Request $request){
if(\Auth::attempt($request)){
return response()->json('success');
}else{
return response()->json('wrong username or pass', 401);
}
}
in ajax
$.ajax({
type: "POST",
url: '/login',
data: JSON.stringify(data),
// data: data,
headers : { 'Content-Type': 'application/json' },
success: function(data) {
console.log(data);
window.location.href = "/dashboard";
},
error : function(data){
alert(data);
}
});
Here's an interesting solution.
/**
* Get the failed login response instance.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
protected function sendFailedLoginResponse(Request $request)
{
if ($request->ajax()) {
return response()->json([
'error' => Lang::get('auth.failed')
], 401);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors([
$this->username() => Lang::get('auth.failed'),
]);
}
And this:
var loginForm = $("#loginForm");
loginForm.submit(function(e) {
e.preventDefault();
var formData = loginForm.serialize();
$('#form-errors-email').html("");
$('#form-errors-password').html("");
$('#form-login-errors').html("");
$("#email-div").removeClass("has-error");
$("#password-div").removeClass("has-error");
$("#login-errors").removeClass("has-error");
$.ajax({
url: '/login',
type: 'POST',
data: formData,
success: function(data) {
$('#loginModal').modal('hide');
location.reload(true);
},
error: function(data) {
console.log(data.responseText);
var obj = jQuery.parseJSON(data.responseText);
if (obj.email) {
$("#email-div").addClass("has-error");
$('#form-errors-email').html(obj.email);
}
if (obj.password) {
$("#password-div").addClass("has-error");
$('#form-errors-password').html(obj.password);
}
if (obj.error) {
$("#login-errors").addClass("has-error");
$('#form-login-errors').html(obj.error);
}
}
});
});

Controller not receiver parameter passed by ajax POST in .Net MVC

I want to make an ajax shopping cart, the GetCarts and AddCart all working, but the RemoveRow not
receiver the parameter "strms". When alert(strms) in removeRow(strms) js function, it show right value
of the book id (equal 8). But in the CartController/RemoveRow debug, the strms value is NULL.
I think it's can be a problem with the routing, but I think my route configs are right!
Please help me.
The view is _Layout.cshtml, which contain js code
The controller is CartController
My RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Sach", action = "Detail", id = "7" }
);
routes.MapRoute(
"Cart",
"{controller}/{category}/{ms}/{sl}",
new { controller = "Cart", action = "AddCart", ms = UrlParameter.Optional, sl = UrlParameter.Optional }
);
routes.MapRoute(
"CartRemoveRow",
"{controller}/{action}/{ms}",
new { controller = "Cart", action = "RemoveRow", ms = UrlParameter.Optional });
}
}
CartController.cs
public class CartController : Controller
{
List<CartItem> listCart;
[HttpPost]
public ActionResult GetCarts()
{
listCart = Cart.getCart(Session);
return PartialView("Cart", listCart);
}
public void AddCart(string ms, string sl) {
int masach = int.Parse(ms);
int soluong = int.Parse(sl);
Cart.AddCart(masach, soluong, Session);
//return PartialView("Default");
}
public void RemoveRow(string strms)
{
int ms1 = int.Parse(strms);
var sach = new Sach() { MaSach = ms1 };
Cart.removeCart(sach, true);
}
}
Ajax js code
<script type="text/javascript">
function showCart() {
// alert("1");
//Load content from CartController
$(function () {
//alert("2");
$.ajax({
type: "POST",
url: '#Url.Action("GetCarts", "Cart")',
success: function (data) {
var result = data;
$('#myCart').html(result);
//alert($('#myCart').html());
}
});
});
$("#myCart").modal('show');
}
function addCart(ms, sl) {
var masach = [];
masach.push(ms);
masach.push(sl);
// alert(masach);
$(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("AddCart", "Cart")/'+ms+'/'+ $("#soluong").val(),
success: function (data) {
showCart();
}
});
return false;
});
}
function removeRow(strms){
$(function () {
// alert(strms);
$.ajax({
type: 'POST',
url: '#Url.Action("RemoveRow", "Cart")/' + strms,
success: function (data) {
showCart();
}
});
});
}
</script>
try passing the parameter in the data property, I have multiple examples but not at home right now.
function removeRow(this_strms){
$(function () {
// alert(strms);
$.ajax({
type: 'POST',
url: '#Url.Action("RemoveRow", "Cart")',
data: { strms: this_strms},
success: function (data) {
showCart();
}
});
});
}
I normally pass C# objects/classes as parameters like this
public void RemoveRow(CartObject strms)
{
int ms1 = strms.ms1;
var sach = new Sach() { MaSach = ms1 };
Cart.removeCart(sach, true);
}
in JS i do something like this
var thisCartObject= {
ms1: 1,
otherproperty: 0.4,
otherproperty2: "Description"
};
function removeRow(thisCartObject){
$(function () {
// alert(strms);
$.ajax({
type: 'POST',
url: '#Url.Action("RemoveRow", "Cart")',
data: JSON.stringify({ strms: thisCartObject}),
contentType: 'application/json',
dataType: 'json',
success: function (data) {
showCart();
}
});
});
}
If you are going to try this, try without! your custom route defined in the RegisterRoutes class first.
Rename the javascript variable: "strms" to "ms" and then send it, because in your route "CartRemoveRow" you will receive a variable declared with the name "ms" not "strms".
And of course, in your controller, rename the parameter in the method "RemoveRow" to "ms".
Or more short, change your route to accept "strms":
routes.MapRoute(
"CartRemoveRow",
"{controller}/{action}/{strms}",
new { controller = "Cart", action = "RemoveRow", strms = UrlParameter.Optional });
}

Getting a 500 internal server error thanks to some javascript in symfony

This is the code:
Controller:
public function isreadAction(Request $request) {
var_dump($request->get('sentValue'));
$em = $this->getDoctrine()->getEntityManager();
$pm = $this->getDoctrine()
->getRepository('LoginLoginBundle:Privatemessage')
->findBypmid($request->get('sentValue'));
$pm->setIsRead(true);
$em->flush();
return new Response();
}
js:
$(document).ready(function () {
$(".pmcontents").hide();
$(".pmbox").click(function () {
$(this).css("font-weight", "normal");
$(this).next().toggle();
var myValue = $('this').attr('id');
var DATA = 'sentValue=' + myValue;
$.ajax({
type: "POST",
url: Routing.generate('isread'),
data: DATA,
cache: false,
success: function (data) {
alert("database has been updated");
}
});
});
});
Routing:
isread:
path: /game/isread
defaults: { _controller: LoginLoginBundle:Default:isread }
requirements:
options:
expose: true
If i click on the error it says that the variable is undefined:
Parametersapplication/x-www-form-urlencodedNiet sorteren
sentValue undefined
Bron
sentValue=undefined
What is the problem? I have tried some things and it seems that the problem lies within the ajax part of the javascript, but i'm not sure.
Replace
var myValue = $('this').attr('id'); //<- notice quote around this
with
var myValue = $(this).attr('id');

Categories

Resources