Show image from API in laravel - ajax

I want to show an image from API using laravel, I already get the image URL from response, but when I want to show it to the data table, the image URL keeps the base URL and I don't want that
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Config;
use Session;
class VehicleController extends Controller
{
public function index(){
return view('pages/vehicle', [
"title" => "Vehicle"
]);
}
public function getCategory() {
$client = new Client();
$response = $client->request(
'GET',
Config::get('constants.API_URL').Config::get('constants.vehicle').'/category',
['headers' =>
[
'Accept' => 'aplication/json',
]
]
)->getBody()->getContents();
return json_decode($response)->data;
}
public function getVehicles(){
$client = new Client();
$user = Session::get('sessionuser');
$response = $client->request(
'GET',
Config::get('constants.API_URL').Config::get('constants.vehicle'),
['headers' =>
[
'Accept' => 'aplication/json',
'Authorization' => $user->token
]
]
)->getBody()->getContents();
return json_decode($response)->data;
}
}
Route
Route::get('/category', [VehicleController::class, 'getCategory'])->name('vehicle.category');
Route::get('/listvehicle', [VehicleController::class, 'getVehicles']);
DataTable
const getVehicleData = () => {
tableCategory = $('#table-kendaraan').DataTable({
destroy: true,
ajax: {
url: `${base_url}/listvehicle`,
dataSrc: '',
type: 'GET',
error: function(response) {
toastr.error('Error get data : ' + response.statusText)
}
},
columns: [
{
data: function (data, type, row, meta) {
return meta.row + meta.settings._iDisplayStart + 1;
},
},
{
"render": function (data, type, JsonResultRow, meta) {
return '<img src="'+JsonResultRow.qr_code+'">';
}
},
{ data: 'name' },
{ data: 'm_transport_categories.type' },
]
})
}
the variable $base_url is variable that getting the base URL which is localhost.
The URL of image keeps returning the localhost URL like this
so it should be returning the base URL from API, how to do that?
Nb : I already get the response directly from JS not using controller, but the URL of image show something like this localhosturl/baseapiurl/uploads... and I'm running this project using PHP artisan serve

Related

laravel using jQuery Ajax | Ajax Cart

I'm Trying to Save The Product into The Database By Clicking On Add To Cart
But It's Not Adding I Also Use Ajax `
I Want To Add The Cart To DataBase And It's Not Adding.
This is The Error That I cant Add Any Product To The Cart Because Of It
message: "Call to undefined method App\User\Cart::where()", exception: "Error",…
enter image description here
Model Page.
class Cart extends Model
{
use HasFactory; I
protected $table = 'carts';
protected $fillable = [
'user_id',
'prod_id',
'prod_qty',
];
}
Controller page.
public function addToCart(Request $request)
{
$product_qty = $request->input('product_qty');
$product_id = $request->input ('product_id');
if(Auth::check())
{
$prod_check = Product::where('id',$product_id)->first();
if($prod_check)
{
if(Cart::where('prod_id',$product_id)->where('user_id',Auth::id())->exists())
{
return response()->json(['status' => $prod_check->pname." Already Added to cart"]);
}
else
{
$cartItem - new Cart();
$cartItem->user_id = Auth::id();
$cartItem->prod_qty = $product_qty;
$cartItem->save();
return response()->json(['status' => $prod_check->pname." Added to cart"]);
}
}
}
else{
return response()->json(['status' => "Login to Continue"]);
}
}
javascript page.
This Is MY First Time To Use Ajax And Sure That Every Thing Is Correct I Want Know Why Its Not Add
$('.addToCartBtn').click(function (e) {
e.preventDefault();
var product_id = $(this).closest('.product_data').find('.prod_id').val();
var product_qty = $(this).closest('.product_data').find('.qty-input').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: "POST",
url: "/add-to-cart",
data: {
'product_id': product_id,
'product_qty': product_qty,
},
success: function (response) {
alert(response.status);
}
});
// alert(product_id);
// alert(product_qty);
// // alert ("test ") ;
});
Route:
Route::middleware(['auth'])->group(function () {
Route::post('/add-to-cart', [App\Http\Controllers\User\indexController::class, 'addToCart' ]);});
So why this error occurs, how can I fix it?`
This look like an error in importation like App\Models\Cart not like this?
verify if you had added use App\Models\Cart;

How to solve SyntaxError: Unexpected token < in JSON at position 0 in Paypal checkout in Laravel

I am doing Paypal integration in Laravel. I have used composer require srmklive/paypal to install the srmklive/paypal package in this project.
When I press the PayPal button, I get this error:
Here is my code:
code from blade file:
paypal.Buttons({
createOrder: function(data, actions) {
return fetch('api/paypal/order/create/', {
method: 'post',
body:JSON.stringify({
"value":100
})
}).then(function(res) {
return res.json();
}).then(function(orderData) {
return orderData.id;
});
},
onApprove: function(data, actions) {
return fetch('/api/paypal/order/capture/', {
method: 'post',
body: JSON.stringify({
orderID: data.orderID
})
}).then(function(res) {
return res.json();
}).then(function(orderData) {
var errorDetail = Array.isArray(orderData.details) && orderData.details[0];
if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
return actions.restart();
}
if (errorDetail) {
var msg = 'Sorry, your transaction could not be processed.';
return alert(msg); // Show a failure message (try to avoid alerts in production environments)
}
});
}
}).render('#paypal-button-container');
code from paymentController:
class PaymentController extends Controller
{
public function create(Request $request){
$data = json_decode($request->getContent(), true);
$provider = \PayPal::setProvider();
$provider->setApiCredentials(config('paypal'));
$token = $provider->getAccessToken();
$provider->setAccessToken($token);
$price = Plan::getSubscriptionPrice($data['value']);
$description = Plan::getSubscriptionDescription($data['value']);
$order = $provider->createOrder([
"intent" => "CAPTURE",
"purchase_units" => [
[
"amount" => [
"currency_code" => "USD",
"value" => $price
],
"description" => $description
]
]
]);
return response()->json($order);
}
public function capture(Request $request) {
$data = json_decode($request->getContent(), true);
$orderId = $data['orderID'];
$provider = \PayPal::setProvider();
$provider->setApiCredentials(config('paypal'));
$token = $provider->getAccessToken();
$provider->setAccessToken($token);
$result = $provider->capturePaymentOrder($orderId);
return response()->json($result);
}
}
How can I solve this error?
The route api/paypal/order/create/ is returning/outputting text that is not JSON, such as an HTML error page or something else that begins with an HTML tag.
The route must only output JSON, and must contain a valid id from the PayPal API.

how to solve paypal login tab missing when integrate with paypal

I want to do paypal integration in Laravel. I have use composer require srmklive/paypal to install the srmklive/paypal package for my project. I get 404 error when I want to press the PayPal button. The popup paypal login tab will missing. Then I inspect the network I get the error like image given.
Here is my code:
class PaymentController extends Controller
{
public function create(Request $request){
$data = json_decode($request->getContent(), true);
$provider = \PayPal::setProvider();
$provider->setApiCredentials(config('paypal'));
$token = $provider->getAccessToken();
$provider->setAccessToken($token);
$plan = $provider->createOrder([
"intent" => "CAPTURE",
"purchase_units" => [
[
"amount" => [
"currency_code" => "USD",
"value" => "30"
],
"description" => "Item 1"
]
]
]);
return response()->json($plan);
}
public function capture(Request $request) {
$data = json_decode($request->getContent(), true);
$orderId = $data['orderID'];
$provider = \PayPal::setProvider();
$provider->setApiCredentials(config('paypal'));
$token = $provider->getAccessToken();
$provider->setAccessToken($token);
$result = $provider->capturePaymentOrder($orderId);
return response()->json($result);
}
}
Here is the code from blade file
paypal.Buttons({
createOrder: function(data, actions) {
return fetch('api/paypal/order/create/', {
method: 'post',
body:JSON.stringify({
"value":30
})
}).then(function(res) {
return res.json();
}).then(function(orderData) {
return orderData.id;
});
},
onApprove: function(data, actions) {
return fetch('/api/paypal/order/capture/', {
method: 'post',
body: JSON.stringify({
orderID: data.orderID
})
}).then(function(res) {
return res.json();
}).then(function(orderData) {
var errorDetail = Array.isArray(orderData.details) && orderData.details[0];
if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
return actions.restart(); // Recoverable state, per:
}
if (errorDetail) {
var msg = 'Sorry, your transaction could not be processed.';
return alert(msg);
}
});
}
}).render('#paypal-button-container');
The error show like image given.
Does anyone know how to solve it?
Does the route api/paypal/order/create/ exist on your server? From the error message, it's returning a 404.
The route must exist (no 404) and successfully output a JSON response with an id obtained from the PayPal API.

Symfony 5 / Request Response : Get data with Ajax

when I try to get data in ajax, the returned object is empty
I send the id of the data I want to get in js :
function selectMessage(id) {
$.ajax({
url: '{{ path('back_translation_update') }}',
method: 'GET',
data: {id: id}
}).done(function (response) {
console.log(response)
})
}
$('.updateMessage').click(function (evt) {
evt.stopPropagation()
selectMessage($(this).data('id'))
})
in the controller I look for the data to return :
/**
* #Route("/update", name="back_translation_update", methods="GET|POST")
*/
public function getById(Request $request): Response
{
if ($request->isXMLHttpRequest()) {
$id = $request->get('id');
// dd($id);
$message = $this->translationService->getTranslationById($id);
// return new JsonResponse(['data' => $message]);
$response = new Response();
$response->setContent(json_encode([
'data' => $message,
]));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
I use a service because with the repository I get an error: getById () must be an instance of Symfony\Component\HttpFoundation\Response
with :
$repositoryMessage = $this->em->getRepository(TranslationMessage::class);
$message = $repositoryMessage->findOneBy(['id' => $id]);
so the service will look in the database:
public function getTranslationById($translation_id)
{
$query = $this->em->createQueryBuilder()
->from(TranslationMessage::class,'message')
->select('message')
->where('message.id = ?1')
->setParameter(1, $translation_id);
$message = $query->getQuery()->getResult();
// dd($message);
return $message;
}
all the dd() give the expected values:
into getById(): the id of the row sought
into getTranslationById(): the sought object
but in the XHR, data contains an empty object: uh:
same with a new JsonResponse, commented here
what did I miss? help
Use Aurowire to get messageRepository object and use $this->json() to return JsonResponse
/**
* #Route("/update", name="back_translation_update", methods="GET|POST")
*/
public function getById(Request $request, TranslationMessageRepository $messageRepository): JsonResponse
{
$id = $request->query->get('id');
$message = $messageRepository->find($id);
if(!$message) { return new NotFoundHttpException(); }
return $this->json([
'success' => true,
'data' => $message
]);
}
Define success function instead of done function
function selectMessage(id) {
$.ajax({
url: "{{ path('back_translation_update') }}",
method: 'GET',
data: { id: id }
success: function(data) {
console.log(data)
}
})
}

getting 500 server error while sending data to database through controller from vue

I am trying to send some data from my vue component to database using a laravel controller. To avoid blank input error, I already made all my table columns nullable except the ID. Still when I am trying to send the data using post method, i am getting error 500.
Here is my vue method:
addRecord(){
fetch('api/video_call', {
method: 'post',
body: JSON.stringify(this.call_detail),
headers: {
'content-type': 'application/json'
}
})
.then(res => res.json())
.then( data=> {
this.call_detail.receiver_caller_id = '';
this.call_detail.sender_caller_id = '';
this.call_detail.receiver_id= '';
this.call_detail.sender_id= '';
this.call_detail.call_received='';
alert('Test Done');
this.fetchCallDetail();
})
.catch(err => console.log(err));
}
}
here is the data that I am returning from vue:
data(){
return {
users: [],
call_details: [],
call_detail: {
id: '',
receiver_caller_id: '',
sender_caller_id: '',
receiver_id: '',
sender_id: '',
call_received: ''
},
call_detail_id: '',
pagination: {},
call_allowed: false
}
}
Here is my route in api.php
Route::post('video_call', 'VideoCallController#store');
And finally here is the store function in controller:
public function store(Request $request)
{
$record = $request->isMethod('put')?VideoCall::findOrFail($request->call_detail_id):new VideoCall;
$record->id= $request->input('call_detail_id');
$record->receiver_id= $request->input('receiver_id');
$record->sender_id= $request->input('sender_id');
$record->sender_call_id= $request->input('sender_call_id');
$record->receiver_call_id= $request->input('receiver_call_id');
$record->call_recieved=$request->input('call_received');
if($record->save())
{
return new VideoCallResource($record);
}
}
I used this methods in my previous apps to send data from vue to database and it worked just fine. In this app it is returning error.

Resources