Ajax 500 internal server error in laravel 7, - javascript

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

Related

sending message to telegram bot

i need some help,
am trying to send message to telegram bot
but things are not working out for me,
am just trying to archive what i want to do. am new to jquery and javascript
below is what i tried
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<script>
$(document).ready(function () {
$("#add_button").click(function(event) {
Execute();
});
var fname = document.querySelector('input[name="fname"]').value;
var country = document.querySelector('input[name="country"]').value;
Message: "<html><br>| Fullname: ${fname} <br> | Country: ${country} <br></html>";
function Execute(){
$.ajax({
type: 'POST',
url: 'https://api.telegram.org/bot<token>/sendMessage?chat_id=<id>text=<message>&parse_mode=html',
data: Message,
success: function(res) {
$('#response').text('Message sent');
},
error: function() {
alert("error failed");
}
});
};
});
</script>
<input type="text" id="fname" name="fname" placeholder="fullname">
<input type="text" id="country" name="country" placeholder="country">
<input type="button" id="add_button" value="Submit">
<div id="response"></div>
<body>
</body>
</html>
There are several issues in you script:
Your <body> tag is misplaced
AFAIK, your payload must be form encoded (not as GET params)
Use ` for format strings instead of "
read the input values in the execute method, not outside (otherwise you read them only once on page load).
You cannot use <br> or <html> in the message, see the docs
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="fname" name="fname" placeholder="fullname">
<input type="text" id="country" name="country" placeholder="country">
<input type="button" id="add_button" value="Submit">
<div id="response"></div>
<script>
const token = '<token>';
const chatId = '<chat_id>';
$(document).ready(function () {
$("#add_button").on('click', function (event) {
execute();
});
function execute() {
const fname = document.querySelector('#fname').value;
const country = document.querySelector('#country').value;
const message = `Fullname: ${fname}\nCountry: ${country}`;
$.ajax({
type: 'POST',
url: `https://api.telegram.org/bot${token}/sendMessage`,
data: {
chat_id: chatId,
text: message,
parse_mode: 'html',
},
success: function (res) {
console.debug(res);
$('#response').text('Message sent');
},
error: function (error) {
console.error(error);
alert("error failed");
}
});
}
});
</script>
</body>
</html>
And a security note:
Do NOT use this script in any production! NEVER EVER!
Everyone would be able to read and abuse your bot token.
Use a backend for this.

500 Internal Server Error when using Ajax in Laravel

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.

Why method not allowed http exception?

I have a form in laravel.
I want to send the data to server using ajax post request.
The laravel give me error. I dont know why?
My view source url is : http://localhost/lily/public/search
(1/1) MethodNotAllowedHttpException
in RouteCollection.php (line 251)
at RouteCollection->methodNotAllowed(array('GET', 'HEAD'))
in RouteCollection.php (line 238)
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready( function () {
$("#submit").submit( function(){
var name = $("#name").val();
console.log(name);
$.ajax({
type: "POST",
url : "{{url('/search')}}",
data : name ,
success : function(data)
{
console.log(data)
},
error : function(error)
{
console.log(error)
}
});
});
});
</script>
<div class="col-md-6 offset-3">
<form id="submit" method="POST">
<input type="name" name="name" id="name">
<button type="submit" class="btn btn-success">search</button>
</form>
</div>
</body>
</html>
Route::post('/search/{name}', 'HomeController#in');
public function in() {
return json("fdfdfdfdfdf");
}
You defined a a route for /search/parameter, but your action is only '/search'.
Remove the useless {name} part in the route. Or make it optional with {name?}
Pass the CSRF token along with the request, after changing your route definition to either remove {name} or making it optional {name?} then change your data to
$(document).ready(function() {
$("#submit").submit(function() {
e.preventDefault(); // Prevent the Default Form Submission
var name = $("#name").val();
console.log(name);
$.ajax({
type: "POST",
url: "{{ url('/search') }}",
data: {
name: name,
_token: "{{ csrf_token() }}"
},
success: function(data) {
console.log(data)
},
error: function(error) {
console.log(error)
}
});
});
});
The input type should be text instead of name in the form
<input type="text" name="name" id="name">
Because you did not add CSRF token value as a hidden type.
You must add CSRF hidden input to Form.
<input type="hidden" name="_token" value="{{ csrf_token() }}" />

Grails - Ajax submit not working?

i'm trying to update a div when a form is submited, but it seems that I am forgetting something.
here's my html:
<%# page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<meta name="layout" content="main" />
<g:javascript library="jquery"/>
</head>
<body>
<form id="formEntrada">
<label>Evento: </label>
<g:select from="${listaEvento}" name="evento_id" optionValue="nome" optionKey="id" noSelection="${['':'Selecione...']}" required="true"/><br><br>
<label>Participante: </label>
<input type="text" id="codigo" onkeyup="pesquisa(event,'/eventoEntrada/pesquisar')" value="${participante?.id}" size="15px"/>&nbsp&nbsp
<input type="text" value="${participante?.nome}" size="50px" disabled required="true">
<input type="submit" value="Adicionar">
</form>
<div id="divList">
<g:render template="list"/>
</div>
</body>
</html>
here's my JavaScript
$(document).ready(function () {
$('#formEntrada').submit(function () {
alert("evento_id+participante_id");
var evento_id = document.getElementById("evento_id").value;
var participante_id = document.getElementById("participante_id").value;
$.ajax({
type: 'POST',
url: '/eventoEntrada/entrada',
data: {"evento_id": evento_id, "participante_id": participante_id},
dataType: 'text',
success: function (data) {
$("#divLista").html(data);
}
})
});
});
and this is the method:
def entrada(){
EventoEntrada entrada = new EventoEntrada()
entrada.setEvento(Evento.get(params.evento_id))
entrada.setParticipante(Pessoa.get(params.participante_id))
println params.evento_id
println params.participante_id
entrada.hora_entrada = java.sql.Time.valueOf(new SimpleDateFormat("HH:mm:ss").format(new Date()))
entrada.saida_antecipada = false
if (!entrada.validate()) {
entrada.errors.allErrors.each {
println it
}
}else{
entrada.save(flush:true)
def listaParticipante = EventoEntrada.list()
render (template:"list", model:[listaParticipante:listaParticipante])
}
}
when i submit the form i get the url ".../.../eventoEntrada/index?evento_id=X&participante_id=Y"
why am i missing?
thanks!
I guess your Ajax url is the problem. you can try to give controller Name and action instead of giving path.
$(document).ready(function () {
$('#formEntrada').submit(function () {
var evento_id = document.getElementById("evento_id").value;
var participante_id = document.getElementById("participante_id").value;
$.ajax({
type: 'POST',
url: "${createLink(controller: 'controllerName', action: 'entrada')}",
data: {"evento_id": evento_id, "participante_id": participante_id},
dataType: 'text',
success: function (data) {
$("#divLista").html(data);
}
})
});
});

Evaluating scripts in an ajax response

I have the following code:
$.ajax({
type: 'POST',
url: urlData,
data: { OwnerId: ownerIdData, Text: textData },
success: function (data) {
$('#post-container').prepend(data);
},
error: function () {
}
});
Now I want to eval the scripts contained in the variable data in the success function.
How I do that ?
Thanks in advance.
EDIT
I have the following form:
<form class="new-post-form">
<textarea id="post-creation-text-input" name="Text" rows="10"> Write something ... </textarea>
<input type="hidden" value="#Model.OwnerId" id="post-creation-id-input"/>
<input type="submit" value="Post" id="post-creation-submit-input" />
<script type="text/javascript">
$('#post-creation-submit-input').click(function (event) {
event.preventDefault();
var textData = $('#post-creation-text-input').val();
var ownerIdData = $('#post-creation-id-input').val();
var urlData = '#Url.Action("Create", "Posts")';
$.ajax({
type: 'POST',
url: urlData,
data: { OwnerId: ownerIdData, Text: textData },
success: function (data) {
$('#post-container').prepend(data);
});
},
error: function () {
}
});
});
</script>
</form>
Now the ajax response is the following view:
#using Facebook.Presentation.Web.Utils
#model Facebook.Presentation.Web.ViewModels.Posts.PostViewModel
<div class="post" id ="last-post">
<h3>#Html.UserName(Model.Author)</h3>
<br/>
<div>
#Html.DisplayFor(model => model.Text)
</div>
<br/>
#{
Html.RenderPartial("_CommentsPartial", Model.Comments, new ViewDataDictionary { { "ActionName", "Comment" }, { "ControllerName", "Posts" } });
}
</div>
This response also contains scripts that must be evaluated.
Thanks again.
Use jQuery.getScript() function. Documentation: http://api.jquery.com/jQuery.getScript/

Categories

Resources