Grails - Ajax submit not working? - javascript

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);
}
})
});
});

Related

I am trying to send data to my PHP page from html page using ajax POST method but it give error ,Notice: Undefined index:

<head>
<title>Document</title>
<script>
$(document).ready(function () {
$("#search").on("keyup", function () {
var search_term = $(this).val();
console.log('value--', search_term)
$.ajax({
url: "ajax-live-search.php",
type: "POST",
data: { search: search_term },
success: function (ajaxresult) {
$("table-data").html(ajaxresult);
}
});
});
});
</script>
</head>
<body>
<div id="search-bar">
<label>Search</label>
<input type="text" id="search" autocomplete="off">
</div>
<div id="table-data">
</div>
</body>
PHP page
$search_input = $_POST["search"];
echo $search_input;
error
Notice: Undefined index: search in C:\xampp\htdocs\ajax\ajax-live-search.php on line 3
Change "type" to "method" as below:
$.ajax({
url: "ajax-live-search.php",
method: "POST",
data: { search: search_term },
success: function (ajaxresult) {
$("table-data").html(ajaxresult);
}
});

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

Enable browser autocomplete when submitting a form via ajax

After googling for a while I can't found a good answer for my problem.
I have a form that is displayed using a modal windows (bootbox for instance). This form is submitted using ajax post, but the browser can't store input values (autocomplete) so that it can display these values when showing this form again.
function openModal(view) {
var buttons = {};
buttons.success = {
label: "Salvar",
className: "btn-primary",
callback: function() {
var $form = box.find("form");
var valuesToSubmit = $form.serialize();
$.ajax({
type: "POST",
url: $form.attr('action'),
data: valuesToSubmit,
dataType: "json"
}).success(function(response) {
box.modal('hide');
if (successCallback) {
successCallback();
}
}).error(function(response) {
box.find(".modal-body").html(response.responseText);
enableBasicControls(box);
if (errorCallback) {
errorCallback();
}
});
return false;
}
};
buttons.danger = {
label: "Cancelar",
className: "btn-danger"
};
box = bootbox.dialog({
title: title,
animate: false,
message: view,
onEscape: function() {},
buttons: buttons,
size: "large"
});
}
<form asp-action="Create">
<input asp-for="Id" type="hidden" />
<input asp-for="ConsultaId" type="hidden" />
<div class="row">
<input data-focus="true" data-select="true" class="form-control" type="number" data-val="true" data-val-required="The QtdEmbalagens field is required." id="QtdEmbalagens" name="QtdEmbalagens" value="1">
</div>
<div class="row">
<input rows="4" class="form-control" type="text" id="Observacao" name="Observacao" value="">
</div>
</form>
I resolve this problem submitting to a fake page using iframe:
<iframe name="myframe" id="frame1" src="Create" style="display: none;"></iframe>
<form asp-action="Create" target="myframe">
<input asp-for="Id" type="hidden" />
....
function openModal(view) {
var buttons = {};
buttons.success = {
label: "Salvar",
className: "btn-primary",
callback: function () {
var $form = box.find("form");
var url = $form.attr('action');
$form.attr('action', "about:blank");
$form.submit();//======================== fake
var valuesToSubmit = $form.serialize();
$.ajax({
type: "POST",
url: url, //sumbits it to the given url of the form
data: valuesToSubmit,
dataType: "json"
...

How to grab the text field values and send the value over a webservice

When the user clicks on the button, i need the values of the following TextFields to be submitted to a Webservice located at /TestService/SaveMethod.
<div class="content">
#Html.TextBoxFor(mo => mo.id, new { id = "id" })
<input type="text" id="fname" name="fname" />
<input type="submit" value="send" class="save"/>
</div>
jquery:
$(function () {
$('.save').click(function () { // How to grab the values of those textfields and send it over the webservice located at `/TestService/SaveMethod` });
});
You don't need the jQuery unless you explicitly want to use it and that too for ajax. Just put one form in your html like:
<div class="content">
#using(Html.BeginForm("SaveMethod","TestService",new{},FormMethod.Post,new{}){
#Html.TextBoxFor(mo => mo.id, new { id = "id" },new{})
<input type="text" id="fname" name="fname" />
<input type="submit" value="send" class="save"/>
}
</div>
You can get the textfield value in script by accessing its value using val() method and send the value to webservice using ajax post.
$(function () {
$('.save').click(function () {
var name = $("#taYourName").val();
$.ajax(
{
Type: "POST",
contentType: "application/xml",
url: "YourNameIs.asmx/YourName",
data: { yourName: name },
success: function (msg) {
$("#lblForAjax").text(msg);
}
});
});
});
Should be like this : it will give you first name value.
$(function () {
$('.save').click(function ()
{
var name = $("#fname").val();
});
});
You can do it with jquery ajax . This is a tested code for you .
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Test webservices</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function () {
$('#submit').click(function (e) {
e.preventDefault();
var x = $('#myval').val();
$.ajax({
url: 'webservice.php',
type: 'GET',
contentType: 'text/html',
dataType: 'text',
data: {
data : x
},
success: function(response)
{
alert("data send to webservice");
},
error: function (response)
{
},
});
});
});
</script>
</head>
<body>
<form action='' method='get'>
<input type='text' name='myval' id='myval' >
<input type='submit' value='Go' id='submit' >
</form>
</body>
</html>
I hope this will solve your problem .

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