How to pass JavaScript variables to Laravel route parameter - javascript

How can I pass JavaScript variables to Laravel route?
This is my route
Route::get('user/checkout/id={id}&subscription_id={subscription_id}&access_token={access_token}', [CheckoutController::class, 'checkout_after'])->name('user.checkout_after');
This is my js, but the problem is I get undifined variable error for the subscription_id. Other 2 parameters ok.
onApprove: function(data, actions) {
<?php echo $subscription_id ?> = data.subscriptionID;
window.location.href = "{{ route('user.checkout_after', ['id' => $plan->id, 'subscription_id' => $subscription_id, 'access_token' => $access_token]) }}";
}

Related

AlpineJS pass an array from php to x-init

I am currently working on a project that involves utilizing PHP and MySQL for data retrieval, and Alpine.js for dynamic front-end interactions. My goal is to pass the array returned from my data fetch in MySQL to the x-init function in Alpine.js, as I am relatively new to using this JavaScript framework. I would like to include what I have accomplished so far:
data.php
<?php
function dbConn() {
// some database connection here using PDO...
}
function getPosts() {
return db()->query('SELECT u.username,p.* FROM users u JOIN posts p on u.id = p.user_id')->fetchAll(PDO::FETCH_ASSOC);
}
index.php
<?php
$results = getPosts();
print("<pre>".print_r($results,true)."</pre>");
?>
<div x-data="posting()" x-init="fetchPost(<?php json_encode($results); ?>)">
<template x-for="post in posts" :key="post.id">
<h2 x-text="post.title"></h2>
<p x-text="post.content"></p>
</template>
</div>
app.js
document.addEventListener("alpine:init", () => {
Alpine.data("posting", () => ({
fetchPost: (data) => {
this.posts = data;
console.log(this.posts);
},
posts: [],
}));
});
Here is the result on my console and above is my array structure:
thank you in advance!
You almost got it right. You forgot to use echo.
<div x-data="posting()" x-init="fetchPost(<?php echo htmlspecialchars(json_encode($results), ENT_QUOTES, 'UTF-8', true) ?>)">

How to validate X-editable request in laravel (Server side)

I've managed to get x-editable (https://vitalets.github.io/x-editable/) to work with a page, in so far as when I click on a field, it displays inline and I can edit it, and I'm able to successfully submit to a POST URI.
The idea here is that I'm sending three key-value pairs:
array:3 [▼
"name" => "name"
"value" => "mathematics"
"pk" => "1"
]
and my update() method catches the array, and it successfully updates the record in the database. But I'm failing to validate the data.
This is how my controller looks:
public function update(Request $request)
{
//
$id = $request->pk;
$subject = Subject::findOrFail($id);
$rules = array (
'name' => 'bail|required|max:20|unique:subjects,name,'.$id
);
This validation pass easily even if I try to fail it
$validator = Validator::make ( $request->all(), $rules );
if ($validator->fails ()) {
return response()->json ( array (
'errors' => $validator->getMessageBag ()->toArray ()
) );
} else {
$subject->update([$request->name => $request->value]);
}
return response ()->json ( $subject );
}
So it's as if I'm somehow not passing the "correct" Request object to validate()? There is no form submission, but the documentation clearly states that:
Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.1
Route:
Route::post('/subjects/update/', 'SubjectsController#update');
script:
$('#subjects').editable({
container:'body',
selector:'td.name',
type:'post',
dataType:'JSON',
validate:function(value){
if ($.trim(value) === '') {
return "Field is required";
}
}
});
1https://laravel.com/docs/5.4/validation#quick-ajax-requests-and-validation
If I'm not mistaken, name is the field to be edited (the DB column), and value is, well, the value. It looks like you are updating the name column, so you have to validate the uniqueness of the value in the request, not the "name".
Also, I'd suggest you use the validate method of your controller (provided by the ValidatesRequests trait):
public function update(Request $request)
{
$id = $request->pk;
$subject = Subject::findOrFail($id);
$this->validate($request, [
'name' => 'required', // this should be the column to update
'value' => 'bail|required|max:20|unique:subjects,name,'.$id
];
$subject->update([$request->name => $request->value]);
return $subject;
}
Here validate will automatically reject with a 422 code and the validation errors in the JSON response. If it passes, it will continue with the update. (return $subject also returns a JSON representation of the object in the response.)

Page not redirecting after stripe checkout

I'm trying to add a stripe checkout button to my Leadpages landing page and after somebody completes a successful payment they're supposed to be redirected...but that redirect is not happening and I have no idea why.
Here's my page: http://snapstories.leadpages.co/test/... it's using test keys right now so you can test the checkout with Stripe's demo Visa number: 4242424242424242 and any expiry / security code...you'll see that you don't get redirected anywhere.
The demo-stripe.php script is supposed to send a 'success' response to my front-end code which triggers the redirect but that 'success' response is not being sent.
Here's the demo-stripe.php code:
<?php
require_once('./stripe/init.php');
$stripe = array(
"secret_key" => "sk_test_******",
"publishable_key" => "pk_test_******"
);
\Stripe\Stripe::setApiKey($stripe['secret_key']);
// Get the credit card details submitted by the form
$token = $_GET['stripeToken'];
$email = $_GET['stripeEmail'];
$callback = $_GET['callback'];
try {
$customer = \Stripe\Customer::create(array(
"source" => $token,
"email" => $email
));
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => 100,
'currency' => 'usd'
));
header('Content-type: application/json');
$response_array['status'] = 'success';
echo $callback.'('.json_encode($response_array).')';
return 1;
}
catch ( \Stripe\Error\Card $e) {
// Since it's a decline, \Stripe\Error\Card will be caught
}
?>
Here's the front-end code:
<script src="https://checkout.stripe.com/checkout.js"></script>
<script>
var handler = StripeCheckout.configure({
key: 'pk_test_*****',
image: 'imagefile.png',
locale: 'auto',
token: function(token) {
$.ajax({
type: "POST",
dataType: 'jsonp',
url: "https://snapstories.co/demo-stripe.php",
data: { stripeToken: token.id, stripeEmail: token.email},
success: function(data) {
window.location.href = "http//www.google.com";
},
});
}
});
document.getElementsByClassName('w-f73e4cf1-859d-e3e4-97af-8efccae7644a')[0].addEventListener('click', function(e) {
// Open Checkout with further options:
handler.open({
name: 'Testing',
description: 'testing',
amount: 100
});
e.preventDefault();
});
// Close Checkout on page navigation:
window.addEventListener('popstate', function() {
handler.close();
});
</script>
I'm guessing your front-end code doesn't get to the success function.
Web console returns:
ReferenceError: $ is not defined
It looks like you're using the jQuery command $.ajax(), but I can't see where you've loaded the jQuery library. Try and load it above the script that uses it and see what happens
Be sure to double check the Stripe Checkout requirements. It seems, based on the link you posted, that you're using the HTTP protocol. Stripe Checkout requires you use the HTTPS protocol. That means if you're not using an ssl certificate on your page using Checkout, your page isn't going to return a token nor will it execute any further.

Route and Post parameter in the Yii2 with ajax

I call AJAX-request in my jQuery-script. I have created the controller (AjaxController) and method actionRequest inside this. JQuery sends this request:
jQuery.ajax({
url: location.origin + '/web/index.php?r=ajax/request',
async: false,
type: 'POST',
data: {'param': 32},
dataType: 'json',
success: function(data) {result = data}
});
and this code is in controller's script:
public function actionRequest() {
$param = Yii::$app->request->post('param');
echo json_encode($param);
}
Controller has accepts this option and send its back. JavaScript displays this option (result) with the help of "alert()". If I send it with GET methods, then all works correctly and window displays "32". But if I change this request into the "POST", window displays "undefined". If I send request to my PHP-script (path: /web/php), then all works correctly too. And if I will delete all code from my controller and leave only:
<?php
$param = $_POST['param'];
echo json_encode($param);
?>
and ask the script directly, then all works correctly too...
There are all signs which mean that error is in the framework, when I use AJAX-method POST. Because if I write this code inside my controller:
$root = $_SERVER['DOCUMENT_ROOT'];
$file = fopen($root . '/text.txt', 'w');
fwrite($file, '1');
fclose($file);
then I send GET-request, and code is completed and create file in the root directory on the site. But if I change request into the POST, then file is not created.
Source of my controller:
<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
use yii\helpers\Html;
class AjaxController extends Controller {
public function behaviors() {
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
public function actions() {
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionIndex() {
return '';
}
public function actionRequest() {
$param = Yii::$app->request->post('param');
echo json_encode($param);
}
}
?>
My UrlManager:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'suffix' => '/',
'rules' => [
'' => 'site/index',
'register' => 'site/register'
]
]
Based on your UrlManager settings, try to change your ajax url to this instead.
url: location.origin + '/ajax/request/',
Just append the controller name, action name, and trailing forward slash.
The reasons are
you set enablePrettyUrl to true
showScriptName to false
suffix to /
I have tested this and it works for both GET and POST type.
Just remember to change the function to obtain GET and POST param accordingly.

how to return an html with javascript method with twig render method

i want to render a controller when clicking on button i use this javascript method
function getPopoverContent(input) {
return {{ render(controller("LeymaxReserveBundle:Reserve:showAddReserveModal",{'iduser': user.id,'token':'1238','idreserve':'0'})) }};
}
but it causes an Illegal exception ,and same thing with quotes ::
return "{{ render(controller("LeymaxReserveBundle:Reserve:showAddReserveModal",{'iduser': user.id,'token':'1238','idreserve':'0'})) }}";
here is my acion::
public function showAddReserveModalAction($iduser, $token, $idreserve) {
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('LeymaxContactBundle:User')->find($iduser);
return $this->render('LeymaxReserveBundle:Reserve:addReserveModal.html.twig', array(
'user' => $user,
'token' => $token,
));
}
how can do it?
U should use :
return "{{ render(controller('LeymaxReserveBundle:Reserve:showAddReserveModal',{'iduser': user.id,'token':'1238','idreserve':'0'})) }}";
U are now breaking up your javascript at the moment :
return "aaaa"bbbb"aaaa"; <-- invalid syntax

Categories