Laravel controller not responding back on AJAX request - ajax

i am typing text in text area
<input placeholder="DISCOUNT COUPON" type="text" id="coupon">
Sending that text to controller using ajax;
$.ajax({
type: "POST",
url: "applyCoupon",
data:{
coupon: $('#coupon').val(),
course_id: {{$course->id}},
_token: {{ csrf_token() }},
},
success: function(dataResult){
alert("success");} // why i am not GETTING this alert?
Controller:
public function applyCoupon(Request $request)
{
$result=new \stdClass();
$coupons = Coupons::select('discount_percentage')->where('coupon_code',$request->get('coupon'))
->where('course_id',$request->get('course_id'))
->get();
$course = Course::findOrFail($request->get('course_id'));
$discounted_price= ($course->price) - (($course->price)*($coupons[0]->discount_percentage)/100);
$result->val = $discounted_price;
$result->statusCode = 200;
return json_encode($result);
}
Web.php:
Route::post('course/applyCoupon', ['uses' => 'CoursesController#applyCoupon', 'as' => 'courses.applyCoupon']);
everything seems fine, but why success function is not running?

You should be using routes/api.php instead of routes/web.phpin the first place.
Also, log error by adding
...
error: function (request, error) {
console.log(error);
alert("Error");
},
That should give you a clue. Could be anything depending on your setup.

You're not using the full URL you setup in your routes/web.php
Change
url: "applyCoupon",
to
url: "course/applyCoupon",
or even better would be to use the route name you provided
url: "{{route('courses.applyCoupon')}}",

Give correct route to your ajax call
Pass this in your ajax url.
url: "{{ route('courses.applyCoupon' }}"
if still not working, then Check your network tab in inspect tool
Click on the ajax call and it will show you the detail on your right side.
post here what you are getting there.

You need to give the response in return of ajax call:-
use Response;
return response()->json(['message' => 'error', 'data' => $data]);

Related

How Can I Prevent AJAX From Destroying My Session?

I'm currently building a web application using CodeIgniter 4. In one of my forms, I need ajax to send a post request and get the data result to modify the form base on item selected on a combo box.
The first requests were always okay, but it won't work for the next one. When I refresh the page, it redirects me to login page, due to my filter. It turns out that the AJAX request either destroy all my sessions, or update it to the new ones.
this is my ajax :
`
$('#penilaian_jenis').on('change', function() {
$.ajax({
OST type: "P",
url: '<?= base_url('guru/penilaian/get_nilai') ?>',
data: {
'kelas_id': '<?= $kelas->kelas_id ?>',
'kd_id': '<?= $kd->kd_id ?>',
'penilaian_jenis': $('#penilaian_jenis').val(),
},
dataType: 'json',
success: function(data) {
var result = JSON.parse(data);
alert(result);
}
})
})
`
This is my Controller :
`
public function get_nilaii()
{
echo json_encode('success');
}
`
This is how I stored my session at the auth controller:
$data = [
'user' => $user,
'guru' => $model->where('user_id', $user->user_id)->first(),
'guru_logged_in' => 1,
];
session()->set($data);
My Ajax codes I user are the simplest one. Can Anyone help give me the solutions to this problem, or recommend me another way to do HTML request without losing all my sessions?
Sorry for bad grammar, and thank you in advance

AJAX POST Request in Laravel says url not found

I am trying to post data to a controller through ajax request. But it can't find the route and says the following in console.
POST http://127.0.0.1:8000/addNotification_action 404 (Not Found)
This is my ajax call below.
function editNotification(obj) {
// alert(obj.id);
var obj_id = obj.id;
var id = obj_id.split("_");
$.ajax({
url: "{{ url('addNotification_action') }}",
type: 'POST',
dataType: 'json',
data: {edit_notification_id: id[1]},
})
.done(function(result) {
console.log(result);
$('#title').val(result['title']);
$('#description_notification').val(result['details']);
$('#edit_flag_notification').val(result['notification_id']);
})
.fail(function() {
alert("error");
});
}
And I am just trying to dd() the request I get in the controller. Please help. Thanks
First of all, you should create a route and give this route a name. You have to generate the ajax url as "route('route_name')".
// Route (for Laravel 8)
Route::post('addNotification_action', [NotificationController::class, 'notify_method'])->name('notify');
// Ajax Settings
....
url: "{{ route('notify') }}",
....
Jus Give admin/addNotification_action in Ajax URL

Laravel ajax return whole HTML page instead data

I'm having this trouble with the ajax request. This code works on other pages, only on this not working.
I want to call ajax (from different controller - CalendarController) on "show" page from controller ClientController - (http://.../client/35) maybe is that wrong
Client.js
$(document).ready(function() {
$('#events-list').on('click', '.event-popup', function () {
var getEventId = $(this).data('id'); //this line is okay, return dynamic id as i want
$.ajax({
type: "GET",
url: "getEvent/" + getEventId,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType: 'json',
})
.done(function (data) {
console.log(data); //if i remove dataType: 'json' whole page will print in log instead data
})
.fail(function(data,jqXHR, textStatus, errorThrown) {
toastr.error("error");
console.log(data,jqXHR, textStatus, errorThrown);
})
});
});
Error message from ajax
parsererror" SyntaxError: Unexpected token < in JSON at position
...
responseText: "<!DOCTYPE html><html lang="sr"><head>... - WHOLE PAGE
web.php
Route::get('/getEvent/{id}', 'CalendarController#getEventData');
CalendarController
public function getEventData($id)
{
$event = Event::findOrFail($id);
return Response::json($event);
}
I added how to Controller looks but does not return data, this ajax call does not come to the controller
I think the problem is somewhere in the URL or because I want to add data with another controller to the show page, but I can't figure
Thanks in advance
EDIT
Ajax request is redirected for some reason
Instead of findOrFail() (it returns HTML if the object doesn't exist), use find() method. Then you can check if the object exists or not and return json as per the condition.
Example:
public function getEventData($id)
{
$event = Event::find($id);
if(!$event) {
return response()->json([
'success' => false,
'message' => 'Not Found'
], 404);
}
return response()->json($event);
}

Laravel 5.6: Why does AJAX POST to Controller not show data load in Controller?

I have been working on this for hours,and not getting anywhere. Essentially, my Ajax call appears to be working well. I am pulling in form data from a view. I can see the XHR data when I look into Chrome Network. I have a status 200, and "OK". However, no matter what I do, I can not get any data to show in my controller. I have tested my route by commenting it out and sure enough I get an error, so that is positive. Also the XHR data shows the correct url as well. But even just a simple dd($request) inside the controller gives me nothing, not even an empty []. I have tried every option and Googled this to death. What am I doing wrong - Thanks !
Abbreviated HTML
<form action="" method="POST" id="formData">
<fieldset>
{{ Form::hidden('customer_id',$customer[0]->id,['id'=>'customer_id'])}}
{{ Form::hidden('lastname1',$customer[0]->lastname1,['lastname1'=>'lastname1'])}}
{{ Form::hidden('reference',$quotation[0]->reference,['id'=>'reference'])}}
</fieldset>
</form>
AJAX
$("#editsubmit").on('click', function () {
event.preventDefault();
var formData =$("#formData").serialize();
var id = $("#reference").val();
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
type: 'POST',
contentType:'JSON',
processData: false,
url: '/save_edit/'+id,
data: {
"_method": 'POST',
"result": formData,
},
error: function () {
alert('there has been a system level error - please contact support')
}
});
});
Route
Route::post('/save_edit/{id}','QuotationController#save_quote_edited');
Controller
public function save_quote_edited(Request $request){
dd(json_decode($request->getContent(), true));
}
To process forms you should not be calling $request->getContent() you should be calling $request->all() to get all parameters, $request->get('foo') or $request->foo to get a single parameter, or $request->get(['foo','bar','baz') to get multiple parameters.
And for bonus points if you used Laravel's Form Request Validation you could call $request->validated() and get only the parameters which passed the validation checks.
Your route requires a parameter of "id" but you do not have that parameter in your controller method.
Route::post('/save_edit/{id}','QuotationController#save_quote_edited');
Try :
public function save_quote_edited(Request $request, $id){
*** insert code here ***
}

Sending post data from Joomla to CodeIgniter

I have a system implemented in CodeIgniter, I am trying to send some data in a text area of Rsform component via POST to the url referring to my CodeIgniter system, I have tried usign AJAX request to send the post data using the following code
<script>
alert("jsc");
var data;
data='test from joomla!';
$.ajax({
type: "POST",
url : 'http://localhost/cii/index.php/login/getNews/',
data: {news:data},
cache: false,
success: function(html){
alert(html);
}
});
getNews controller:
function getNews() {
//print_r($this->session->userdata);
header('Access-Control-Allow-Origin: *');
echo "news is ".$news=$_POST['news'];
$data = array ( 'username' => "null", 'is_logged_in' => false, 'news'=>$news);
$this->session->set_userdata($data); //var_dump($_POST); //
print_r($this->session->userdata); session_start(); echo session_id();
}
but it failed, is there any other options ?
Use something like Firebug in mozilla firefox to observe what data is being posted to the app to check if your ajax call is working.
Then in your codeigniter controller method, simply put this code to see if the data is getting to it.
function getNews()
{
foreach($_POST as $key => $val)
{
$options[$key] = $this->input->post($key);
}
var_dump($options);
}

Resources