I'm trying to send values from the radio when clicking the button by ajax for a laravel route, however it is returning 419 and I send the token csrf.
$(document).ready(function(){
$("#valor").on('click', function()
{
$.ajax({
headers: {
'X-CSRF-Token': $('input[name="_token"]').val()
},
type: 'POST',
url: "personagem",
data: 'personagem='+$('input[name="personagem"]').val(),
success: function(data){
$(location).attr('href', "{{ URL::to(Request::path()) }}");
},
error: function(){
alert('Erro no Ajax !');
}
});
});
});
<div class="col-md-2 name-system">
<input type="radio" id="system" name="personagem" value="1"/>
<label for="system"><img src="img/system.png" alt=""></label>
<center><span><h3>System</h3></span></center>
</div>
<div class="col-md-2 name-web">
<input type="radio" id="personagem2" name="personagem" value="2"/>
<label><img src="img/web.png" alt=""></label>
<center><span><h3>Web</h3></span></center>
</div>
<div class="col-md-2 name-master">
<input type="radio" id="personagem3" name="personagem" value="3"/>
<label><img src="img/master.png" alt=""></label>
<center><span><h3>Master</h3></span></center>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="button" id="valor" name="valor" />
</div>
The variable must be delivered by post to the controller but an error is already occurring in the request.
You must send the token in your data body request. Try this:
$(document).ready(function(){
$("#valor").on('click', function()
{
$.ajax({
type: 'POST',
url: "/personagem",
data: {
personagem: $('input[name="personagem"]').val(),
_token: "{{ csrf_token() }}"
},
success: function(data){
$(location).attr('href', "{{ URL::to(Request::path()) }}");
},
error: function(){
alert('Erro no Ajax !');
}
});
});
});
Related
I have three google forms on a page. Each form is linked to a tab on a single spreadsheet.
For now I have duplicated the working code from here: https://codepen.io/xergioalex/pen/ZNevvM
A single form was working fine, however now that there are three it no longer functions.
All inputs eg. "entry.472617792" should be correct.
Link to public Spreadsheet.
// Form01
$('#contact-form01').submit(function(event) {
event.preventDefault();
$('#feedback01').html('');
setTimeout(function() {
// Get data
var data = {
'entry.472617792': $('#form-name01').val(),
'entry.898916053': $('#form-phone01').val(),
'entry.1085111698': $('#form-message01').val()
};
// Validate form
var formSuccess = true;
Object.keys(data).forEach(function(key, index) {
if (!data[key]) {
formSuccess = false;
$('#feedback01').html('<label class="text-danger">Please complete all fields</label>');
}
});
if (formSuccess) {
// Send request
$.ajax({
url: 'https://docs.google.com/forms/u/2/d/e/1FAIpQLSfiJghWBgMBn-twEzVfeIWMQhyp_3oFa26r1bdA-A71n_3Enw/formResponse',
type: 'POST',
crossDomain: true,
dataType: "xml",
data: data,
success: function(jqXHR, textStatus, errorThrown) {
console.log('Enter on success');
$('#feedback01').html('<label class="text-success">Message sent!</label>');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('Enter on error');
$('#feedback01').html('<label class="text-success">Message sent!</label>');
}
});
}
}, 300);
});
// Form02
$('#contact-form02').submit(function(event) {
event.preventDefault();
$('#feedback02').html('');
setTimeout(function() {
// Get data
var data = {
'entry.472617792': $('#form-name02').val(),
'entry.898916053': $('#form-phone02').val(),
'entry.1085111698': $('#form-message02').val()
};
// Validate form
var formSuccess = true;
Object.keys(data).forEach(function(key, index) {
if (!data[key]) {
formSuccess = false;
$('#feedback02').html('<label class="text-danger">Please complete all fields</label>');
}
});
if (formSuccess) {
// Send request
$.ajax({
url: 'https://docs.google.com/forms/u/2/d/e/1FAIpQLSfnPLSloZWtGXTqhexuJsb9LoEA9U8-uYGYj3Ex5SS5Nwty0w/formResponse',
type: 'POST',
crossDomain: true,
dataType: "xml",
data: data,
success: function(jqXHR, textStatus, errorThrown) {
console.log('Enter on success');
$('#feedback02').html('<label class="text-success">Message sent!</label>');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('Enter on error');
$('#feedback02').html('<label class="text-success">Message sent!</label>');
}
});
}
}, 300);
});
// Form03
$('#contact-form03').submit(function(event) {
event.preventDefault();
$('#feedback03').html('');
setTimeout(function() {
// Get data
var data = {
'entry.472617792': $('#form-name03').val(),
'entry.898916053': $('#form-phone03').val(),
'entry.1085111698': $('#form-message03').val()
};
// Validate form
var formSuccess = true;
Object.keys(data).forEach(function(key, index) {
if (!data[key]) {
formSuccess = false;
$('#feedback03').html('<label class="text-danger">Please complete all fields</label>');
}
});
if (formSuccess) {
// Send request
$.ajax({
url: 'https://docs.google.com/forms/u/2/d/e/1FAIpQLSfK6S-GlcKsq8YCz4OBwlTsf9g8frbGouP4VGkyXiykaH1UMw/formResponse',
type: 'POST',
crossDomain: true,
dataType: "xml",
data: data,
success: function(jqXHR, textStatus, errorThrown) {
console.log('Enter on success');
$('#feedback03').html('<label class="text-success">Message sent!</label>');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('Enter on error');
$('#feedback03').html('<label class="text-success">Message sent!</label>');
}
});
}
}, 300);
});
.container {padding-bottom:50px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--Form 01-->
<div class="container">
<h2>Form 01</h2>
<form method="post" id="contact-form01">
<input type="text" class="form-control" id="form-name01" placeholder="Name*"><br>
<input type="text" class="form-control" id="form-phone01" placeholder="Phone*"><br>
<textarea type="text" class="form-control" id="form-message01" placeholder="Message*"></textarea><br>
<button type="submit" class="btn btn-default">
Submit
</button>
<div id="feedback01"></div>
</form>
</div>
<!--Form 02-->
<div class="container">
<h2>Form 02</h2>
<form method="post" id="contact-form02">
<input type="text" class="form-control" id="form-name02" placeholder="Name*"><br>
<input type="text" class="form-control" id="form-phone02" placeholder="Phone*"><br>
<textarea type="text" class="form-control" id="form-message02" placeholder="Message*"></textarea><br>
<button type="submit" class="btn btn-default">
Submit
</button>
<div id="feedback02"></div>
</form>
</div>
<!--Form 03-->
<div class="container">
<h2>Form 03</h2>
<form method="post" id="contact-form03">
<input type="text" class="form-control" id="form-name03" placeholder="Name*"><br>
<input type="text" class="form-control" id="form-phone03" placeholder="Phone*"><br>
<textarea type="text" class="form-control" id="form-message03" placeholder="Message*"></textarea><br>
<button type="submit" class="btn btn-default">
Submit
</button>
<div id="feedback03"></div>
</form>
</div>
I do not have access to input values when using Ajax in View(MVC) but I have access to input values when not use Ajax. actually values is empty when use Ajax
When I use Ajax:
<form id="Form1" asp-action="Register" asp-controller="UserPanel" method="post">
<div class="row">
<div class="col-lg-5 col-md-5 col-sm-12 col-12 .sm-right" id="margin-top">
<span>Name:</span>
<input type="text" asp-for="Name" class="form-control">
</div>
<div>
<span>Number:</span>
<input type="text" asp-for="Number" class="form-control">
</div>
</div>
<input type="reset" value="send" id="ajax-button" class="btn btn-success btn-sm waves-effect waves-light submit-btn" />
</form>
Script:
<script>
$(document).ready(function () {
var url = '#Url.Action("Register", "UserPanel")';
var data = $('#Form1').serialize();
$('#ajax-button').click(function () {
debugger
$.ajax({
type: "POST",
data: data,
url: url,
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert('Done');
},
error: function () {
alert("error");
}
});
})
})
</script>
I added tag helpers
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#addTagHelper *, SmsWebClient
#using Microsoft.AspNetCore.Razor.TagHelpers;
Value is null before enter to ajax ,image:
Please Move the
var data = $('#Form1').serialize();
to below
$('#ajax-button').click(function () {
In fact, your code should be:
<script>
$(document).ready(function () {
var url = '#Url.Action("Register", "UserPanel")';
$('#ajax-button').click(function () {
var data = $('#Form1').serialize();
debugger
$.ajax({
type: "POST",
data: data,
url: url,
success: function (result) {
alert('Done');
},
error: function () {
alert("error");
}
});
})
})
</script>
In your code data set when docuement loaded and for this reason the value
is null
You must write like this
<form id="Form1" asp-action="Register" asp-controller="UserPanel" method="post">
<div class="row">
<div class="col-lg-5 col-md-5 col-sm-12 col-12 .sm-right" id="margin-top">
<span>Name:</span>
<input type="text" asp-for="Name" class="form-control">
</div>
<div>
<span>Number:</span>
<input type="text" asp-for="Number" class="form-control">
</div>
</div>
<div class="form-group">
<button id="ajax-button">Submit</button>
</div>
</form>
And This ViewModel
public class RegisterVm
{
public string Name { get; set; }
public string Number { get; set; }
}
And finally this is the Ajax code
#section Scripts{
<script>
$(document).ready(function () {
var url = $('#Form1').attr("action");
var model = $('#Form1').serialize();
var token = $('input[name=__RequestVerificationToken]').val();
model.__RequestVerificationToken = token;
$('#ajax-button').click(function () {
$.ajax({
type: $('#Form1').attr("method"),
data: model,
url: url,
success: function (result) {
alert('Done');
},
error: function () {
alert("error");
}
});
})
})
</script>
}
Your data are set when docuement loaded, it will not pass the value which you enter.
For a working demo, try code below:
<script>
$(document).ready(function () {
$('#ajax-button').click(function () {
var url = '#Url.Action("Register", "Home")';
var data = new FormData();
data.append('Name', $('#Name').val());
data.append('Number', $('#Number').val());
$.ajax({
type: "POST",
data: data,
url: url,
processData: false,
contentType: false,
success: function (result) {
alert('Done');
},
error: function () {
alert("error");
}
});
})
})
</script>
I have a ajax request script with post method using body value, what I want is, to print the response value.
$('#my-form').submit(function () {
$.ajax({
url: 'https://apiurl.com/users',
type: 'post',
headers: {
'accept': 'application/json;charset=UTF8',
'content-type': 'application/json',
'api-key': 'judmkd895849438'
},
contentType: 'application/json',
data: { "firstname": $('#firstname').val(), "lastname": $('#lastname').val() },
success: function( data, textStatus, jQxhr ){
$('#response pre').html( JSON.stringify( data ) );
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
});
and the form script is:
<form id='my-form'>
<div><input type='text' name='firstname' id='firstname' placeholder='Firstname' /></div>
<div><input type='text' name='lastname' id='lastname' placeholder='Lastname' /></div>
<div><input type='submit' value='Submit' /></div>
</form>
<!-- where the response will be displayed -->
<div id="response">
<pre></pre>
</div>
but nothing display on screen, anyone know why?
thanks
As Roy stated, you'll need to prevent the browser from submitting the form. You'll have to prevent the default event from firing as you're handling it via an AJAX request.
$('#my-form').submit(function (event) {
event.preventDefault();
$.ajax({
url: 'https://apiurl.com/users',
...
I have this select option:
<select name="rank" id="rankvalue" onChange="rank({{$thisData->id}})">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
which is calling this Ajax:
function rank(id)
{
$.ajax({
type:"POST",
url: "{{ url('do_sort') }}"+"/"+id,
dataType: "json",
cache: false,
data: $('#rankvalue').serialize(),
success: function(data){
console.log(data);
},
error: function (data) {
console.log(data);
}
});
}
I want to convert them into three buttons like this
<div name="rank" id="rankvalue" onClick="rank({{$thisData->id}})">
<button value="1">1</button>
<button value="2">2</button>
<button value="3">3</button>
</div>
But the parameter doesn't get sent.
I have tried moving name, id, and onClick on each button, any combination I can think of, but it still doesn't work.
What am I missing here?
Note: I'm not looking for CSS solution if possible.
I ended up sending the value from function rank() instead:
<div>
<button onClick="rank({{$thisData->id}},1)">1</button>
<button onClick="rank({{$thisData->id}},2)">2</button>
<button onClick="rank({{$thisData->id}},3)">3</button>
</div>
Then form the json in ajax.
function rank(id,value)
{
$.ajax({
type:"POST",
url: "{{ url('do_sort') }}"+"/"+id,
dataType: "json",
cache: false,
data: {
'rank': value
},
success: function(data){
//$("#contentdata").load(" #contentdata");
console.log(data);
getRank();
},
error: function (data) {
console.log(data);
}
});
}
I have a form and ajax.
I can't send with $(form).serialize();
How do I send the button value with the form?
html:
<form action="" id="ogrenci_arama_formu">
<input type="text" id="eposta" name="eposta">
<button id="ogrenci_ara" name="ogrenci_ara" value="true" class="btn btn-info">Öğrenciyi Ara</button>
<!--<input id="ogrenci_ara" type="hidden" name="ogrenci_ara" value="true">-->
</form>
ajax:
$("#ogrenci_arama_formu").submit(function (e) {
e.preventDefault();
console.log("form: ",$(this).serialize());
$.ajax({
url: "sayfalar/ogrenci_bilgileri.php",
type: 'post',
/*dataType: 'json',*/
data: $(this).serialize()
}).done(function(data) {
$("tbody").html(data);
}).fail(function(data) {
console.log("error",data);
});
});
output:
eposta=
try like store button value into a variable and send with form serialize like this
JAVASCRIPT-
$("#ogrenci_arama_formu").submit(function(e) {
e.preventDefault();
var btnValue = $(this).find('#ogrenci_ara').val();
console.log("form: ", $(this).serialize()+'&ogrenci_ara='+btnValue);
$.ajax({
url: "sayfalar/ogrenci_bilgileri.php",
type: 'post',
/*dataType: 'json',*/
data: $(this).serialize()+'&ogrenci_ara='+btnValue
}).done(function(data) {
$("tbody").html(data);
}).fail(function(data) {
console.log("error", data);
});
});