Request of Ajax with Laravel 5.4 - ajax

I am trying to make an example of Ajax request with Laravel 5.4.
The test example is simple, just enter a numeric value in an input = text field in my View and leave the field to send to the Controller, then add + 10 to that value and then return that value to my View so that it can displayed on an alert.
HTML : viewteste.blade.php
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<form action="">
Valor: <input type="text" id="valor" name="valor" />
</form>
</body>
</html>
JS: The js file is inside viewteste.blade.php, I just split it to make it easier to interpret.
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$("#valor").on('blur', function()
{
valor = $(this).val();
$.ajax({
type:'POST',
url:"{{ URL::to('/teste/valor') }}",
dataType: 'JSON',
data: {
"valor": valor
},
success:function(data){
alert('Success');
},
error:function(){
alert('Error');
},
});
});
});
</script>
Route
Route::get('/teste', 'TesteAjaxController#index');
Route::post('/teste/valor', 'TesteAjaxController#valor');
Controller
class TesteAjaxController extends Controller
{
public function index()
{
return view('painel.viewteste');
}
public function valor(Request $request)
{
$valor= $request->input('valor');
$valor += 10;
return $valor; // How do I return in json? in case of an error message?
}
}
Always when I try to send the request via ajax it goes to alert ('Error'). is it that I'm doing something wrong in sending the ajax or route?

to return a json response. you need to use.
response()->json([
'somemessage' => 'message',
'valor' => $valor
]);
UPDATE: you are getting an error alert because i think your route method doesnt match your controller methods.
Route::post('/teste/valor', 'TesteAjaxController#valor');
where in your controller you have
public function cep() ...

Related

Ajax Call to PartialViewResult does not Replace Div with PartialView

I've done this dozens of times before and have been testing all morning, I must be missing something very obvious.
I have a form that submits data and if the data already exists, I just want to overwrite that form using a PartialView. I can debug the code and watch the POST get called and I even watch the PartialView reciev its model and data but the PartialView doesn't get rendered on the screen and my AJAX doesn't return anything to the console so I'm not sure how to Troubleshoot this.
My Controller
[HttpPost]
[Route("Send")]
public PartialViewResult Send([FromBody] InstantAlert InstantAlert)
{
string view = "~/views/shared/_InstantAlert_Exists.cshtml";
}
My View
<!-- Form -->
<div id="DivSubmitForm">
<partial name="~/views/home/_Partials/_SubmitForm.cshtml", model="Model" />
</div>
<!-- End Form -->
My Script
$(function () {
$(document).on("click", '#btnSubmit', function () {
if ($('form').valid()) {
Submit();
}
});
function Submit() {
//JSON data
var InstantAlert = {
url: $('#url').val(),
userId: $('#userId').val(),
institutionId: $('#institutionId').val()
}
var jsonToPost = JSON.stringify(InstantAlert);
$.ajax({
url: '/home/Send',
contentType: "application/json; charset=utf-8",
data: jsonToPost,
type: "POST",
success: function (result) {
console.log("Success");
//$('#DivSubmitForm').html(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
});
PartialView
<div class="form-group">
<div class="alert alert-danger alert-dismissible" role="alert">
<strong>This article has already been submitted</strong>
<hr class="message-inner-separator">
<p>
test
</p>
</div>
</div>
Argh, so I discovered a form tag on my page which means the controller was inevitably always reloading my initial controller....

ajax post with laravel 5.6

I can't figure out how to get this ajax request to post.
<button class="btn btn-sm btn-primary" id="ajaxSubmit">Submit</button>
<textarea rows="4" class="form-control resize_vertical" id="application_notes" name="application_notes" placeholder="Notes">{{$application->notes}}</textarea>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var url = "/instructor-notes-save/{{$application->id}}"
$(document).ready(function(){
$('#ajaxSubmit').click(function(e){
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: url,
method: 'post',
data: {
application_notes: jQuery('#application_notes').val(),
},
success: function(response){
console.log(response);
}});
});
});
</script>
My controller is this:
public function saveNotes(Request $request, $id)
{
$application = Application::findOrFail($id);
$application->notes = $request->application_notes;
$application->save();
return response()->json(['success'=>'Data is successfully added']);
}
And for what it's worth, here is my route:
Route::post('/instructor-notes-save/{id}', 'InstructorsController#saveNotes')->name('instructor.save.note');
What am i missing to get this ajax request to work? In my console log, i get a 419 unknown status error.
Kindly check that the meta tag _token is present in your layout file inside the <head> tag.
Also please make sure that the AJAX url is present in your routes file.
add the following tag in your html <head>:
<meta name="csrf-token" content="{{ csrf_token() }}">

How to call ajax function on buttonclick in laravel?

View Code:
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
<body>
<div id = 'msg'>This message will be replaced using Ajax. Click the button to replace the message.</div>
<input type="button" value="Replace Message" onclick='getMessage()'>
</body>
Here ,When I click on the button it should be replaced by the other text. But nothings appears on clicking.
Controller code:
public function index(){
$msg = "This is a simple message.";
return response()->json(array('msg'=> $msg), 200);
}
In pure js that code work fine
function getMessage(){
alert('Its working!');
}
<body>
<div id = 'msg'>This message will be replaced using Ajax.
Click the button to replace the message.</div>
<input type="button" value="Replace Message" onclick='getMessage()'>
</body>
Looks OK.
Put a breakpoint in your success and see what data is.
Or do a console.log
Mick
in your ajax code you didn't define dataType, add dataType:"json", to retrive the json data, change your ajax code as
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
dataType:'json',
data:{
_token = '<?php echo csrf_token() ?>'
},
success:function(data){
$("#msg").html(data.msg);
}
});
Update your code with below mentioned code, and let's try.. i will working for me..
<script type="text/javascript" charset="utf-8">
$(document).on('click', '#btnSelector', function(event) {
event.preventDefault();
/* Act on the event */
getMessage();
});
var getMessage = function(){
$.ajax({
type:'POST',
url:'/getmsg', //Make sure your URL is correct
dataType: 'json', //Make sure your returning data type dffine as json
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
console.log(data); //Please share cosnole data
if(data.msg) //Check the data.msg isset?
{
$("#msg").html(data.msg); //replace html by data.msg
}
}
});
}
</script>
<body>
<div id = 'msg'>This message will be replaced using Ajax. Click the button to replace the message.</div>
<input type="button" value="Replace Message" id='btnSelector'>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<body>
<div id='msg'>This message will be replaced using Ajax. Click the button to replace the message.</div>
<input type="button" id="ajax_call" value="Replace Message">
</body>
<script>
$(function () {
$('#ajax_call').on('click', function () {
$.ajax({
type:'POST',
url:'<?php echo url("/getms"); ?>',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
},
complete: function(){
alert('complete');
},
error: function(result) {
alert('error');
}
});
});
});
</script>
Jquery onclick function: jquery onclick function not defined
Also check: Function not calling within an onclick event

Ajax laravel 5.2 doesn't work

I want to develop simple ajax with laravel5.2 with this code
This oneline_help.php view
<html>
<head>
<title>Ajax Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
</head>
<body>
<div id = 'msg'>This message will be replaced using Ajax.
Click the button to replace the message.</div>
<?php
echo Form::button('Replace Message',['onClick'=>'getMessage()']);
?>
</body>
</html>
This is the routes
Route::get('/ajax','front#support');
Route::post('/getmsg','Hello#index');
This is front #support
public function support()
{
return view('online_help', array('title' => 'Welcome', 'description' => '', 'page' => 'online_help','subscribe'=>"",'brands' => $this->brands));
}
This is Hallo #index controller
public function index(){
echo"i in in hello index";
$msg = "This is a simple message.";
return response()->json(array('msg'=> $msg), 200);
}
The button appear But when click on it, The text doesn't change .
Please tell me why and how to resolve it.
Here is my working example of AJAX....
You don't need to add token in your ajax request, make it global so with every ajax request, your CSRF token will be added automatically.
In your HTML Head section add this meta tag
<meta name="csrf-token" content="<?php echo csrf_token() ?>">
Then add this code in your Javascript tags. this will add CSRF token in every ajax request.
Note this required jquery file should be included in your page. once include call this method below from the file.
<script type="text/javascript">
var csrf_token = $('meta[name="csrf-token"]').attr('content');
$.ajaxSetup({
headers: {"X-CSRF-TOKEN": csrf_token}
});
</script>
I have modified your method....
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
data:'_token = <?php echo csrf_token() ?>', //remove this line
dataType:'json', // you skipped this line
beforeSend:function(){
alert('loading....'); //this will show loading alert
},
success:function(data){
$("#msg").html(data.msg);
},
error:function(){
alert('loading error...')
}
});
}
</script>

Why Ajax Jquery form click not working vs div that works?

Ajax Jquery form not working vs div why its happen and how can i fix my error?
view.html-Code with form
not working
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
</head>
<body>
<form id="parse-form" action="#" method="post">
<button type="submit" id="submit-html">submit ajax request without parameters</button>
</form>
<div>array values: <div id="array-values"></div></div>
<script type="text/javascript">
$(document).ready(function() {
$('#submit-html').click(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType:'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function (i, elem) {
$('#array-values').append('<div>'+elem+'</div>');
});
}
});
});
});
</script>
</body>
</html>
view.html -form replaced by div
working
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
</head>
<body>
<div id="parse-form">
<button type="submit" id="submit-html">submit ajax request without parameters</button>
</div>
<div>array values: <div id="array-values"></div></div>
<script type="text/javascript">
$(document).ready(function() {
$('#submit-html').click(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType:'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function (i, elem) {
$('#array-values').append('<div>'+elem+'</div>');
});
}
});
});
});
</script>
</body>
</html>
controller.php -simple php file that return json array:
<?php
$arr=array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
Thanks
The form has a default action with a type="submit" button, which is submitting, so you'll need to stop that from happening by adding return false or event.preventDefault() , like this:
$(document).ready(function() {
$('#submit-html').click(function(e) {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType:'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function (i, elem) {
$('#array-values').append('<div>'+elem+'</div>');
});
}
});
return false;
//or e.preventDefault();
});
});
Without this, the form is submitting as it normally would with no JavaScript, leaving the page. So effectively it's doing a refresh, instead of AJAX submitting your form (which doesn't have time to complete...because you left :)
An element of type=submit inside a <form> will perform the form request when clicked on.
You need to abort the default behavior by running event.preventDefault() inside the click callback.
My guess is that the form is submitting and refreshing the page before the ajax has a chance to respond.
Try putting return false; at the end of the click handler.
$('#submit-html').click(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType: 'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function(i, elem) {
$('#array-values').append('<div>' + elem + '</div>');
});
}
});
return false;
});
Of course you'll have the same issue if the user hits Enter in one of the fields. Unless you're preventing the Enter key from submitting the form, you may want to the handle the event using the submit() handler.
$('#parse-form').submit(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType: 'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function(i, elem) {
$('#array-values').append('<div>' + elem + '</div>');
});
}
});
return false;
});
Try using submit() http://api.jquery.com/submit/ , this should work with keyboard events as well as clicks. You can use serialize() to get any form data into the ajax objects data variable.

Resources