500 Internal Server Error when using Ajax in Laravel - javascript

I'm trying to use ajax call in my blade view and post ajax data to controller to insert to database.
Here is my ajax:
<!DOCTYPE html>
<html>
<head>
<title>FormBuilder Editor</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://formbuilder.online/assets/js/form-builder.min.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<div id="fb-editor"></div>
<div id="saveToDatabase">
<button id="saveBtn" type="button">Save To Database</button>
</div>
</body>
<script>
var formBuilder = $('#fb-editor').formBuilder();
$("#saveBtn").click(function() {
var mFormData = formBuilder.actions.getData(); //JSON data return
console.log(mFormData);
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "POST",
url: "save",
data: {
"mFormData":mFormData
}
}).done(function (msg) {
alert("Data saved!" + msg);
});
});
</script>
</html>
And here is my controller:
public function saveToDb(Request $request) {
$data = $request->all();
if($data) {
Form::insertData($data);
}
return view('welcome');
}
And this is my insert function in Model:
public function insertData($formData) {
DB::EnableQueryLog();
$sql = DB::table('form')->insert(['formKey' => 'testForm2', 'formData' => $formData]);
return $sql;
}
When I click on button save, this is error in Network XHR:
How I can fix this? Thank you very much!

you are calling the inserData statically. so it should be
public static function insertData($formData) {
DB::EnableQueryLog();
$sql = DB::table('form')->insert(['formKey' => 'testForm2', 'formData' => $formData]);
return $sql;
}

Replace this line:
Form::insertData($data);
with this:
app()->make(From::class)->insertData($data);
Or inject the Form model instance in the constructor if you prefer.
However, the way you are inserting is not how models are meant to be inserted.

Related

Passing multiple type of data via AJAX to MVC C# Controller

I'm using AJAX to get the info from the Razor View and send it to controller
Everything is working but now I need to pass an Array + String so the data could be:
// View - Javascript
var idkey = $('#idkey').val();
var selected = ['test1', 'test2', 'test3'];
$.ajax({
type: 'POST',
url: '/Adm/MyAction',
traditional: true,
data: { idkey: idkey, selected: selected }), ...
// Controller
[HttpPost]
public async Task<JsonResult> MyAction(string idkey, string[] selected)
{
// Do something with the data passed on params
}
The issue is ... I can't find anywhere how to send two different types of data from AJAX to controller
this works:
Controller:
public class HomeController : Controller
{
[HttpPost]
public string Index900(string theValue, string[] stringArray)
{
//put breakpoint here
try
{
throw new Exception("this is the Value" + theValue);
}
catch (Exception ex)
{
return ex.Message;
}
}
public ActionResult Index()
{
return View();
}
View:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
$(function () {
$("#theBtn").click(function () {
var idkey = $('#idkey').val();
var selected = ['test1', 'test2', 'test3'];
var theValue = $("#theInput").val();
$.ajax({
url: "/Home/Index900",
dataType: 'text',
type: 'post',
contentType: 'application/json',
data: JSON.stringify({ theValue: idkey, stringArray: selected }),
success: function (result) {
alert(result);
},
error: function (data) {
alert("error...")
}
});
});
});
</script>
</head>
<body>
<div>
<input type="button" id="theBtn" value="Click to start ajax" />
<input type="text" id="idkey" value="Some Value" />
</div>
</body>
</html>

Ajax 500 internal server error in laravel 7,

I Already put the token in the data to be send but the error still 500 internal server error
in the web.php
Route::post('/Achievement', 'AchievementController#store');
url /Achievement go to AchievementController and run function store
in the AchievementController
public function store(Request $req){
$idPembicara= Pembicara::where('idUser','like',Auth::user()->id)->first();
$data = Penghargaan::create([
'idPembicara'=>$idPembicara->id,
'tahun' => $req['tahunRow1'],
'lokasi' => $req['lokasiRow1'],
]);
return $data;
}
app.blade.php
<meta name="csrf-token" content="{{ csrf_token() }}">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
achievement.blade.php
<form id="updateAchievement">
{{csrf_field()}}
<input type="text" class="form-control" id="tahunRow1" name="tahunRow1">
<input type="text" class="form-control" id="lokasiRow1" name="lokasiRow1">
<button type="submit" value="submit" class="btn btn-primary"></button>
</form>
<script type="application/javascript">
$(document).ready(function() {
$("#updateAchievement").submit(function(e) {
e.preventDefault();
var token = $('meta[name="csrf-token"]').attr('content');
var mData = {
'lokasiRow1': $('input[name=lokasiRow1]').val(),
'tahunRow1': $('input[name=tahunRow1]').val(),
_token: token,
};
console.log(mData);
$.ajax({
type: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "/Achievement",
data: mData,
success: function(e) {
location.reload();
},
error: function(e) {
console.log(e);
}
});
});
});
is there anything i miss, thanks before, sorry for bad english

Trouble with MVC Navbar Home button Get Request

I am having this issue with my home button not adding headers in a get request. I have stored a token inside of the localStorage and I send it in the headers when I make a get request to Controller: Home Action: Index. From what I see, it doesn't use my jquery and goes straight to the Account/Index.
Below is my code for the file "Views/Shared/_Layout.cshtml":
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - Chat</title>
<environment include="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="~/css/site.css" />
</environment>
<environment exclude="Development">
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>
<script src="~/js/NavBarFunctions.js"></script>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li id="li_btnHome"><a asp-area="" asp-controller="Home" asp-action="Index">A Different Page</a></li>
</ul>
</div>
</div>
</nav>
<div class="container body-content">
#RenderBody()
<hr />
<footer>
<p>© 2018 - Chat</p>
</footer>
</div>
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
</environment>
<environment exclude="Development">
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery"
crossorigin="anonymous"
integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
crossorigin="anonymous"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
</script>
<script src="~/js/site.min.js" asp-append-version="true"></script>
</environment>
#RenderSection("Scripts", required: false)
</body>
</html>
Here's the javascript file "wwwroot/js/NavBarFunctions.js":
$("#li_btnHome a")[0].click(function (event) {
alert("Called click")
event.preventDefault();
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8;',
url: '#Url.Action("Index", "Home")',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", localStorage.getItem("token"));
},
success: function (response) {
$("html").html(response);
}
});
});
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Chat.Enums;
using Chat.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
namespace _Chat.Controllers
{
public class HomeController : Controller
{
private AuthenticateUser authenticateUser = new AuthenticateUser();
public async Task<IActionResult> Index()
{
var request = Request;
var headers = request.Headers;
StringValues token;
if (headers.TryGetValue("Authorization", out token))
{
var result = await this.authenticateUser.ValidateToken(token);
if (result.Result == AuthenticateResult.Success)
{
return View();
}
else
{
return RedirectToAction("Index", "Account");
}
}
return RedirectToAction("Index", "Account");
}
}
}
EDIT: For some odd reason, it looks like after my page is redirected from log in to home, all scripts/javascript stop working.
Here's the code authenticating login. Located in "Controllers/AccountController":
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Chat.Models;
using Chat.DatabaseAccessObject;
using Chat.Identity;
using Chat.DatabaseAccessObject.CommandObjects;
using System.Linq.Expressions;
using System.Net.Mime;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authentication;
using Microsoft.IdentityModel.Tokens;
namespace Chat.Controllers
{
public class AccountController : Controller
{
private const string SECRET_KEY = "CHATSECRETKEY";
public static SymmetricSecurityKey SIGNING_KEY = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SECRET_KEY));
private ServerToStorageFacade serverToStorageFacade = new ServerToStorageFacade();
private AuthenticateUser authenticateUser = new AuthenticateUser();
public IActionResult Index()
{
return View();
}
// Post: /login/
[HttpPost]
public async Task<IActionResult> Login([FromBody]LoginModel loginModel)
{
if (ModelState.IsValid)
{
var mapLoginModelToUser = new MapLoginModelToUser();
var user = await mapLoginModelToUser.MapObject(loginModel);
// If login user with those credentials does not exist
if(user == null)
{
return BadRequest();
}
else
{
var result = await this.authenticateUser.Authenticate(user);
if(result.Result == Chat.Enums.AuthenticateResult.Success)
{
// SUCCESSFUL LOGIN
// Creating and storing cookies
var token = Json(new
{
data = this.GenerateToken(user.Email, user.PantherID),
redirectUrl = Url.Action("Index","Home"),
success = true
});
return Ok(token);
}
else
{
// Unsuccessful login
return Unauthorized();
}
}
}
return BadRequest();
}
private string GenerateToken(string email, string pantherId)
{
var claimsData = new[] { new Claim(ClaimTypes.Email, email), new Claim(ClaimTypes.Actor, pantherId) };
var signInCredentials = new SigningCredentials(SIGNING_KEY, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "localhost",
audience: "localhost",
expires: DateTime.Now.AddDays(7),
claims: claimsData,
signingCredentials: signInCredentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public async Task<IActionResult> Error() => View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
public class MapLoginModelToUser
{
private ServerToStorageFacade serverToStorageFacade;
public MapLoginModelToUser()
{
serverToStorageFacade = new ServerToStorageFacade();
}
public async Task<User> MapObject(LoginModel loginModel)
{
Expression<Func<User, bool>> expression = x => x.Email == loginModel.inputEmail;
var user = await this.serverToStorageFacade.ReadObjectByExpression(new User(Guid.NewGuid()), expression);
if(user == default(Command))
{
return null;
}
return new User(user.ID)
{
Email = loginModel.inputEmail,
Password = loginModel.inputPassword,
FirstName = user.FirstName,
LastName = user.LastName,
PantherID = user.PantherID,
ClassDictionary = user.ClassDictionary,
UserEntitlement = user.UserEntitlement
};
}
}
}
Also the code that renders the page. Located in "wwwroot/js/Login.js":
$(document).ready(function () {
$("#formSubmit").submit(function (event) {
event.preventDefault();
var email = $("#inputEmail").val();
var password = $("#inputPassword").val();
var remember = $("#rememberMe").val();
var loginModel = {
inputEmail: email,
inputPassword: password,
rememberMe: remember
};
$.ajax({
type: 'POST',
url: 'Account/Login',
data: JSON.stringify(loginModel),
contentType: 'application/json; charset=utf-8;',
success: function (response) {
var token = response.value.data;
localStorage.setItem("token", token);
alert("You have successfully logged in.");
setHeader();
redirect(response.value.redirectUrl);
}
});
});
function setHeader() {
$.ajaxSetup({
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', localStorage.getItem("token"));
}
});
}
function redirect(redirectUrl) {
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8;',
url: redirectUrl,
success: function (response) {
$("html").html(response);
}
});
}
});
I just noticed there is something off when none of the scripts (or any javascript for that matter) works. I believe it may be triggered with the line $("html").html(response);. AccountController/Login Returns a view, and this was the only way I knew of displaying a view.
This is the error received after loading the new html page:
There is a problem with the location of NavBarFunctions.js in your layout. You're loading the JS and trying to bind the click event before the li_btnHome element has been created. You're also trying to do this before JQuery has been loaded on the page.
Take the script out of the page header and move it down the bottom, near the RenderSection for the scripts.
The way you bind click handler with jQuery is not correct :
$("#li_btnHome a")[0].click(function(event){
// ...
})
$(selector) will return a collection of matched elements . However ,$(selector)[0] is not a jQuery object , but a normal DOM element . So you cannot bind onclick event handler by using .click(function(event){/* ... */}) .
Also ,
It's good to return false;
As #I. R. R said , you should convert the token to string .
As #Lyons said , you should make the code executed after the jQuery loaded
To bind the onclick handler correctly , change your code as below :
$("#li_btnHome a")[0].onclick=function(event){
event.preventDefault();
alert("called click");
var tokenObj = localStorage.getItem("token");
var tokenStr = tokenObj==null ? "what_about_tokenObj_is_null?": tokenObj.toString();
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8;',
url: '#Url.Action("Index", "Home")',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization",tokenStr);
},
success: function (response) {
alert(1);
$("html").html(response);
}
});
return false;
};

Json object display in html

Hey guys I am new with this json syntax and I have one problem.
I made function that gets data from remote server in json like this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-3.1.0.min.js"></script>
<script type="text/javascript">
function getStates(value) {
var data = {
q: value
}
$.ajax({
url: 'https://something.hr/api/search',
method: 'GET',
headers: {'Accept': 'application/json'},
data: data
}).done(function(data) {
//do something with data I returned to you
console.log("success")
console.log(data)
}).fail(function(data) {
//doSomethingWith the data I returned to you
console.log("fail")
console.log(data)
});
};
</script>
</head>
<body>
<input type="text" onkeyup="getStates(this.value)" >
<br>
<script>
</script>
</body>
</html>
My problem is that I know how to get object in console log, but i wish to get that object in html, like in some box, than click on it and open his data(name, id, adress etc.)
var httpManager = (function() {
var getData = function(value) {
$.ajax({
url: 'https://api.github.com/users/zixxtrth',
method: 'GET'
}).done(function(data) {
//do something with data I returned to you
jQuery('#avatar').attr('src', data.avatar_url);
jQuery('#name').html(data.name);
jQuery('#username').html(data.login);
}).fail(function(data) {
//doSomethingWith the data I returned to you
alert('No Data');
});
};
return {
getData: getData()
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<img src='' id='avatar' width='200' height='200' />
<h1 id='name'></h1>
<h2 id='username'></h2>

No response in html page call to web api

i am trying to call c# web api but there is no response in html page but i getting response in cshtml
WEB API CODE
namespace MvcApplication3.Controllers
{
public class StoreController : Controller
{
public string Get2()
{
return "response data";
}
}
}
HTML CODE
<html>
<head>
<script src="jquery-1.8.2.js">
</script>
<!--<script src="jquery-1.8.2.min.js">
</script>-->
<script type="text/javascript">
$(function () {
$(document).ready(function () {
$('body').on('click', '.test', function (e) {
alert('a');
jQuery.support.cors = true;
$.ajax({
// url: 'http://localhost:3595/api/values/5',
url: 'http://localhost:1152/Store/Get2',
type: 'GET',
dataType: "Jsonp",
success: function (data) {
alert(data);
}
});
});
});
});
</script>
<title>
</title>
</head>
<body>
<input type="button" value="submit" class="test"/>
</body>
</html>

Categories

Resources