Parameter is not sent to Laravel route in Ajax - javascript

I'm working with Laravel 5.8 and I wanted to apply a discount code system for my site.
So I tried sending data with Ajax like this:
$.ajax({
type: 'POST',
url: baseurl + 'discount/register',
data: {
coupon_code: finalDiscountValue,
course_id: itemCourse,
},
dataType: "json",
success: function (data) {
if(data == 99) {
swal("Wrong discount code");
} else if (data == 130) {
window.location.href = {!! json_encode(route('myCourseList')) !!}
} else{
window.location.href = {!! json_encode(route('payCourseRegistrationWithDiscount', ['course'=>$item->cor_id,'value'=>$data['cartValueDiscountedWithCode'] ?? ''])) !!}
}
}
});
Now my problem is $data['cartValueDiscountedWithCode'] which does not send to the defined route name.
And this is because $data is returned in Ajax and it's type is different from the other variable which is $item->cor_id and is Laravel based variable.
Here is how I return $data in the Controller:
public function registerWithDiscount()
{
$courseId = request('course_id');
$findCourse = Course::find($courseId);
$getCoursePrice = $findCourse->cor_price;
if ( request('course_id') == null ) {
return 97; // The input was empty
}
...
$data['cartValueDiscountedWithCode'] = $getCoursePrice - $value_discounted;
$data['discountedPrice'] = $value_discounted;
$data['coupon_id'] = $coupon->id;
$data['coupon_name'] = $coupon->name;
if($data['discountedPrice'] >= $getCoursePrice){
$this->registerDiscountFree($courseId,$data['cartValueDiscountedWithCode']);
session()->flash('registrationMessage', 'Your registration is completed');
return 130; // if the discount code makes the course free
}else{
return $data; // if the remainer balance still needs to pay
}
}

You can try this:
let url = "{{ route('payCourseRegistrationWithDiscount',['course'=>$item->cor_id,'value'=>':cartValueDiscountedWithCode']) }}";
url = url.replace(':cartValueDiscountedWithCode', data.cartValueDiscountedWithCode);
window.location.href = url;
You can't pass the ajax response value like that.
Instead, add a string inside route and later repalce with response value

what you will have to do is add the parameter as optional {value?}example
and then add the in blade
window.location.href = {{route('payCourseRegistrationWithDiscount', ['course'=>$item->cor_id]) }}}+'/'+data.cartValueDiscountedWithCode

Related

laravel, ajax call from input to controller function 500 error

I'm not sure what's happening with this but when my ajax call is made to my php controller method, I'm getting a 500 error and I'm wondering if it's possibly a data type error or just simply syntax.
The value I'm passing from my form input through tha ajax call and into my function is being passed into a url endpoint in my service.php file.
The ajax itself is calling the function successfully but I can't verify the results from my $searchResults in the function because it seems to fail at the point of passing.
I started typing Test into my input with a breakpoint in the browser and it showed the value for my input as "T". Should I need to strip quotes or anything like that if it's being used in the query of the endpoint?
What else does it look like I could be doing wrong here?a
service.php
public function getSearch($query)
{
return $this->get("/search/search?query={$query}" );
}
I also set a new route for the controller and function
Route::post('autocomplete','Controller#autoComplete');
controller.php
public function autoComplete(Request $request)
{
$search_result = $request->search_result;
$service = new service();
//$search_result = "test"; /*this hard coded value works for passing*/
$searchResults = $service->getSearch($search_result);
return $searchResults;
}
view.blade.php
$('#productInput').on('input', function(){
if($(this).val() === ''){
return;
}else{
const searchResult = $(this).val();
$.ajax({ url: '/account/autocomplete',
data: {
'search_result':searchResult
},
type: 'POST',
success: function(response){
console.log(response);
}
});
}
});
Add this to your head
<meta name="csrf-token" content="{{ csrf_token() }}">
and pass the token to ajax:
$('#productInput').on('input', function(){
if($(this).val() === ''){
return;
}else{
const searchResult = $(this).val();
$.ajax({ url: '/account/autocomplete',
data: {
'search_result':searchResult
},
"_token": "{{ csrf_token() }}", // **** THIS LINE IS ADDED ***** //
type: 'POST',
success: function(response){
console.log(response);
}
});
}
});
I take the ajax part from this answer, so thanks to Deepak saini. If this answer solved your problem, give his answer a plus.

Display js code in php method ajax

I run the PHP code by ajax method with the click of a button.
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
}
});
});
I would like the file.php to be able to run the js code, for example:
if ($time < $_SESSION['time']) {
[...]
}
else {
echo '<script>alert("lol");</script>';
}
And that when the button .btn_ranking on the page is pressed, an 'lol' alert will be displayed. If it is possible?
you can echo a response to the AJAX call and then run the JS according to the response..
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time },
success: function (data) {
if(data==1){
//do this
}else if(data==2){
//do that
alert('LOOL');
}
}
});
});
PHP CODE:
if ($time < $_SESSION['time']) {
echo '1';
}
else {
echo '2';
}
You can't said to a server-side script to use javascript.
What you have to do is to handle the return of you'r ajax and ask to you'r front-side script to alert it. Something like that :
file.php :
if ($time < $_SESSION['time']) {
[...]
}
else {
echo 'lol';
exit();
}
Front-side :
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
},
success : function(data) {
alert(data);
}
});
});
When you used ajax for call php script, everything will be print in the return of the php code will be return to the HTTP repsonse and so be on the Ajax return function as params.
Ok .. First change your js code to handle answer from php script:
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time }
success: function(data) {
console.log(data);
// check if it is true/false, show up alert
}
});
});
Then change php script (file.php), something like that:
$response = [];
if ($time < $_SESSION['time']) {
$response['data'] = false;
}
else {
$response['data'] = true;
}
return json_encode($response);
Something like that is the idea :) When u send ajax with POST method get variables from there, not from $_SESSION :)
U can see good example here

Laravel form select onChange value save to databse via AJAX

I have a dropdown list generated by the following code in controller (FocalController.php):
$focalData = DB::table('role_users')->orderBy('users.id','DESC')
->leftJoin('users', function($join){
$join->on('role_users.user_id', '=', 'users.id');
$join->on('role_users.role_id', '=', DB::raw("'1'"));
})
->select('users.id',DB::raw('CONCAT(users.name) AS focal'))
->groupBy('users.id')
->get();
foreach($focalData as $data):
$focals[$data->id] = $data->focal;
endforeach;
in the view, I have the following block generating the drop-down list:
{!! Form::select('focal', [''=>'select focal']+ collect($focals)->toArray() , $project_focal, array('class' => 'form-control','onchange'=>'changeFocal(this, '.$project->id.')' ))!!}
I want to submit the drop-down value onChange and save the value using AJAX.
My ajax for the form submission is following:
function changeFocal(e,project_id) {
var focal_id = $("#e").val();
var project_id = $("#project_id").val();
$.ajax({
type: "PUT",
data: "focal_id=" + e + "&project_id=" + project_id,
url: "{{ URL::to('admin/focal') }}",
success:function(data){
console.log(data);$("#msg").html("New Focal Assigned.");
}
});
}
My route is:
Route::post('admin/focal/','FocalController#saveFocal');
the saveFocal function in my FocalController is:
public function saveFocal(Request $request){
$focal_id = $request->focal_id;
$project_id = $request->project_id;
$project = Project::find('idea_id', $project_id)
->update([
'focal' => $focal_id,
'updated_at' => \Carbon\Carbon::now()->toDateTimeString(),
]);
#\App\Common::createAccessLog($project->focal, "Update Project Focal for Project#" . $project->idea_id . "(" . $project->name . ")");
return view('admin/focal');
}
I am getting the following error in console:
Can anyone please tell me what am I doing wrong and how can I save the select data to database with ajax along with a success message.
Use POST instead of PUT
Also make sure the route you are sending your request to is valid and exists
Below are few corrections:
function changeFocal(e,project_id) {
var focal_id = $(e).val(); //correction
var project_id = $("#project_id").val();
$.ajax({
type: "PUT",
data: "focal_id=" + focal_id + "&project_id=" + project_id, //correction
url: "{{ URL::to('admin/focal') }}",
success:function(data){
console.log(data);$("#msg").html("New Focal Assigned.");
}
});
}
Ude where Clause instead find
Project::where(
find works on primary key

PHP Get POST Value from Ajax to PHP with 2 condition

Assume I have 2 textbox, that's serial_no10 and serial_no12. That 2 textbox appear not simultaneously depends on case
1 PHP file for checking the SN.
1 DIV status to display the data.
jQuery Ajax
var serial_no10 = $("#serial_no10").val();
var serial_no12 = $("#serial_no12").val();
$.ajax(
{
type: "POST",
url: "chk_dvd_part_no.php",
data: 'serial_no10='+ serial_no10 +'&serial_no12='+ serial_no12,
success: function(msg)
{
$("#status").ajaxComplete(function(event, request, settings)
{
}
}
}
HTML
<div id="status"></div>
PHP File
if(!empty($_POST['serial_no12']))
{
echo "Serial No 12";
}
else if(!empty($_POST['serial_no10']))
{
echo "Serial No 10";
}
Now I'm facing the problem when get POST from textbox serial_no_12, the value is undefined. But if get POST from textbox serial_no_10, I got the value.
Is that something wrong with that PHP code? Or I do something that should not be.
You have to just empty the variables before filling up. As if value is not reset then last value computed would remain in variavar
serial_no10 = $("#serial_no10").val();
var serial_no12 = $("#serial_no12").val();ble
change it with
var serial_no10='';
var serial_no12='';
serial_no10 = $("#serial_no10").val();
serial_no12 = $("#serial_no12").val();
Noww do things it will all good
Give your form tag an id if it has no anyone. and than do something like this.
var form = $("#form_id").serialize();
$.ajax({
type: "POST",
url: "chk_dvd_part_no.php",
data: form,
success:function(msg)
{
$("#status").ajaxComplete(function(event, request, settings)
{
//do your stuff
});
}
});
and in php file get your post variable by its name, suppose you have 2 inputs name serial_no10 and serial_no12
now do your php code like this.
if( isset($_POST['serial_no10']) && $_POST['serial_no10'] != '' ){
echo 'Serial No 10';
}
if( isset($_POST['serial_no12']) && $_POST['serial_no12'] != '' ){
echo 'Serial No 12';
}

$.parseJSON Unexpected Character

I'm trying to send data from an html data attribute on a span element and receive it with Ajax and then process it with php and mysql and return the new value to my data attribute in html, but I'm getting a error that says "$.parseJSON unexpected character", can someone please look over my code to see if I'm processing the data correctly as I'm new to working with JSON.
HTML / PHP
<span data-object=
'{"art_id":"<?php echo $row['art_id'];?>",
"art_featured":"<?php echo $row['art_featured'];?>"}'
class="icon-small star-color"></span>
<!-- art_id and art_featured are both int and art_featured will be either 1 or 0 -->
jQuery / Ajax
$("span[class*='star']").on('click', function () {
var data = $.parseJSON($(this).data('object'));
var $this = $(this);
$.ajax({
type: "POST",
url : "ajax-feature.php",
data: {art_id: data.art_id,art_featured: data.art_featured}
}).done(function(result) {
data.art_featured = result;
$this.data('object', JSON.stringify( data ));
});
});
PHP / mySQL
if($_POST['art_featured']==1) {
$sql_articles = "UPDATE `app_articles` SET `art_featured` = 0 WHERE `art_id` =".$_POST['art_id'];
$result = array('art_id' => $_POST['art_id'], 'art_featured' => 0);
echo json_encode($result);
}
else if($_POST['art_featured']==0){
$sql_articles = "UPDATE `app_articles` SET `art_featured` = 1 WHERE `art_id` =".$_POST['art_id'];
$result = array('art_id' => $_POST['art_id'], 'art_featured' => 1);
echo json_encode($result);
}
if(query($sql_articles)) {
}
else {
}
You don't need to use $.parseJSON, jQuery does that for you.
$("span[class*='star']").on('click', function () {
var data = $(this).data('object');
var $this = $(this);
$.ajax({
type: "POST",
url : "ajax-feature.php",
data: {art_id: data.art_id,art_featured: data.art_featured}
}).done(function(result) {
data.art_featured = result;
$this.data('object', data);
});
});
You also don't need to stringify it later.

Categories