Laravel Message from API (Ajax) - ajax

I have a Laravel project and would like the API server to return a message (validation) that will be displayed in Laravel.
Laravel
<script>
jQuery('#ajaxSubmit').click(function(e){
$.ajax({
type: 'post',
url: $("#r").val(),
data: {
i:$("#i").val(),
c:$("#c").val(),
cn:$("#cn").val(),
s:$("#s").val(),
m:$("#m").val(),
},
success: function(response) {
if($.isEmptyObject(response.error)){
location.reload();
}else{
printErrorMsg(response.error);
}
}
});
});
function printErrorMsg (msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display','block');
$.each( msg, function( key, value ) {
$(".print-error-msg").find("ul").append('<li>'+value+'</li>');
});
}
</script>
API Server
return response()->json(['error' => 'My Message']);

I believe
response.error
must be
response.data.error

Related

How to download Laravel Excel with Ajax method

I'm working on Laravel Excel using Ajax method. Below is my controller.
public function downloadExcel(){
return Excel::download(new SomeExport(), 'project.xlsx');
}
And this is ajax call.
$(document).on('click', '#download_excel', function(e) {
downloadExcel().then(data => {
//may be need to do some here.
}).catch(error => {})
});
function downloadExcel() {
return new Promise((resolve, reject) => {
$.ajax({
url: `${route.url}/api/...`,
type: 'GET',
headers: {"X-CSRF-TOKEN":route.token},
success: function(data) {
resolve(data)
},
error: function(error) {
reject(error)
},
})
})
}
This work for normal request but not work for ajax. Any advice or guidance on this would be greatly appreciated, Thanks.
I've tried this, and it works.
$(document).on('click', '#download_excel', function(e) {
window.location="{{ route('yourRoute')}}";
})

Notification Laravel

i want to make notification in laravel using ajax and get data from controller but i don't know why this always said 500 internal server error
this is my ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
// updating the view with notifications using ajax
function load_unseen_notification(view = '')
{
$.ajax({
url:"notif",
method:"POST",
beforeSend: function(xhr){xhr.setRequestHeader('X-CSRF-TOKEN', $("#token").attr('content'));},
data:{view:view},
dataType:"json",
success:function(data)
{
$('.dropdown-menu').html(data.notification);
if(data.unseen_notification > 0)
{
$('.count').html(data.unseen_notification);
}
}
});
}
load_unseen_notification();
setInterval(function(){
load_unseen_notification();;
}, 5000);
});
controller
public function index()
{
$pengumuman = Pengumuman::select("pengumuman.*")->count('pengumuman.id');
$data = array(
'unseen_notification' => $pengumuman
);
}
web.php
Route::Post('notif', 'NotifController#index')->name('notif');

laravel- request empty in controller using ajax

I am using laravel 6.0 and i am building crud application. I have following jquery code in view file
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/'+id,
method: 'post',
success: function (res) {
console.log(res);
}
})
});
}
And this is the code in controller
public function update(Request $request, $id='') {
$country = $request->input('countryname');
$sortname = $request->input('sortname');
$phonecode = $request->input('phonecode');
//return $country.$sortname.$phonecode;
return $request;
// DB::table('countries')->where('id',$id)->update(
// [
// 'name' => $country,
// 'sortname' => $sortname,
// 'phonecode' => $phonecode,
// ]);
}
The problem is $request returns empty.
If I don't use ajax then I am getting all input values. But I dont know why its not working for ajax request. Also I have added this line in view file
headers: {
'X-CSRF-TOKEN': '{!! csrf_token() !!}'
}
});
Please help me to solve this problem
You are not passing your form data. Try this:
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/' + id,
method: 'post',
data: $(this).serialize();
success: function (res) {
console.log(res);
}
})
});
}
laravel by default does not send raw data , you have to convert your data to json, the best practice is :
return response()->json([
'data' => $request
]);
Just try this code for example and see if you get any hint.
function updaterecord(id) {
$('#modalupdate').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'update/' + id,
method: 'post',
data: {'countryname' : 'India','sortname' : 'Sort Name', 'phonecode' : '022'};
success: function (res) {
console.log(res);
}
})
});
}
See if you are getting any response.

laravel passport bearer token not working

Hi I am trying to get the passport login working using the bearer token in laravel. the alert shows a token from localstorage.
I have the following javascript code which in the laravel project is in :
/public/js folder:
var token = localStorage.getItem('token');
alert( token );
var jsonp_url = "http://localhost/site1/api/get_data?callback=?"
$.ajax({
method: "GET",
dataType: 'jsonP',
url: jsonp_url,
jsonp: true,
headers: {"Authorization": "Bearer " + token},
success: function(result) {
alert("DATA");
alert(JSON.stringify(result));
},
error: function(result) {
alert("ERR");
alert(JSON.stringify(result));
}
});
then in a external javascript file I include it as follows:
<script src="http://localhost/site1/public/js/api_users.js" type="text/javascript"></script>
The API route in api.php is as follows:
Route::middleware('auth:api')->get('/get_data', function (\Illuminate\Http\Request $request) {
try {
return response()->json([ 'stuff' => 'some data'], '200' )->setCallback($request->input('callback'));
}
catch( \Exception $e ) {
Log::error('Error - ajax_srch_postcode'.$e);
return Response()->json([ 'error' => 'Error cannot proceed!!'], 500 ); // Status code here
}
});
So the code returns a status 200 message but is dropping to the error handler code in the ajax code, rather than the result bit...any ideas??

How to use ajax in Wordpress?

I want to use ajax in wordpress. How can I do it? I have attached my code here. But this is not working for me.
Here it is my wordpress action and hook.
function ajax_enqueuescripts() {
wp_enqueue_script('ajaxloadpost', get_template_directory_uri().'/js/my-ajax.js', array('jquery'));
wp_localize_script( 'ajaxloadpost', 'ajax_postajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', ajax_enqueuescripts);
add_action('wp_ajax_nopriv_ajax_ajaxhandler', 'my_action_callback' );
add_action('wp_ajax_ajax_ajaxhandler', 'my_action_callback' );
function my_action_callback(){
//echo "Df";print_r($_POST);die;
}
and here it is my js code
jQuery(document).ready(function(){
jQuery('#event-form').submit( function () {
var email = jQuery('#event_name').val();
jQuery.ajax({
type: 'POST',
url: ajax_postajax.ajaxurl,
data: {
action: 'ajax_ajaxhandler',
email : email
},
success: function() {
alert(email);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Fd");
}
});
return false;
});
});
The value that you alert in your success ajax function must come from your php function so you would have something like this:
PHP
function my_action_callback(){
echo $_POST['email']; die();
}
Javascript
jQuery.ajax({
type: 'POST',
url: ajax_postajax.ajaxurl,
data: {
action: 'ajax_ajaxhandler',
email : email
},
success: function(data) {
alert(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Fd");
}
});
in your case data in javascript will be equal to anything that you echo out in your php function.
You can send json objects to javascript by encoding arrays in which case you would have
PHP
function my_action_callback(){
echo json_encode('email' => $_POST['email']));
die();
}
Javascript
jQuery.ajax({
type: 'POST',
url: ajax_postajax.ajaxurl,
data: {
action: 'ajax_ajaxhandler',
email : email
},
success: function(data) {
alert(data.email);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Fd");
}
});
I only gave you example of the places in your code that needed to be replaced, the rest seems alright.

Resources