Submit POST data from controller - laravel

I am trying to implement Payhere payment gateway (Local gateway based in Sri Lanka). As per their documentation we could submit data as below.
<html>
<body>
<form method="post" action="https://sandbox.payhere.lk/pay/checkout">
<input type="hidden" name="merchant_id" value="121XXXX"> <!-- Replace your Merchant ID -->
<input type="hidden" name="return_url" value="http://sample.com/return">
<input type="hidden" name="cancel_url" value="http://sample.com/cancel">
<input type="hidden" name="notify_url" value="http://sample.com/notify">
<br><br>Item Details<br>
<input type="text" name="order_id" value="ItemNo12345">
<input type="text" name="items" value="Door bell wireless"><br>
<input type="text" name="currency" value="LKR">
<input type="text" name="amount" value="1000">
<br><br>Customer Details<br>
<input type="text" name="first_name" value="Saman">
<input type="text" name="last_name" value="Perera"><br>
<input type="text" name="email" value="samanp#gmail.com">
<input type="text" name="phone" value="0771234567"><br>
<input type="text" name="address" value="No.1, Galle Road">
<input type="text" name="city" value="Colombo">
<input type="hidden" name="country" value="Sri Lanka"><br><br>
<input type="submit" value="Buy Now">
</form>
</body>
</html>
This will redirect to url "https://sandbox.payhere.lk/pay/checkout" and opens a widow to submit card details.
But what I want to do is, send related POST data from a controller without a view (Same function as above, but through controller when after an database insertion done)
Any suggestion how to do this. I have tried using HTTP client, but since above gateway redirect to external url and popsup a window that's collect data.
$client = new GuzzleHttp\Client();
$response = $client->request('POST', 'https://sandbox.payhere.lk/pay/checkout', [
'form_params' => [
"merchant_id" => '1218XXX',
"return_url" => route('admin.dashboard'),
"cancel_url" => 'key-app.test',
"notify_url" => route('notify'),
"order_id" => '1',
"items" => 'Test',
"currency" => 'LKR',
"amount" => '50.00',
"first_name" => 'Arafath',
"last_name" => 'a',
"email" => 'mhmaarafath#gmail.com',
"phone" => '0765245237',
"address" => 'Mount Lavinia',
"city" => 'Colombo',
"country" => 'Sri Lanka',
]
]);
return redirect('https://sandbox.payhere.lk/pay/checkout');

First point you can't make a Guzzle request here since you need to open a new window here. (instead of Guzzle you can use HTTP client )
Yo can do something like below to accomplish your requirement
Get all related data from db inside controller and then return a view with that data where that view has the payhere form and you can hide the form with css. payhereCheckout ()
Now submit the form via JQuery or JS . What you have to do is just click form submit button via JS or JQuery. Just put a small loader or something which may show the user to that the server is processing the request.
I'll provide some codes how you need to achieve this. I have not used this process to PayHere but all the payment gateways in SL use a form submission .So that process should same.Here is the example code.
Controller
class PayHereChekoutControler extends Controller
{
public function payhereCheckout () {
$userData = UserDataModel::find(Auth::id());
$email = $userData->email;
$firstName = $userData->first_name;
//Other required paramas here or just pass the collection to view and get the required feilds there.
return view('payhere_hidden_checkout', compact(
'first_name',
'email',
));
}
}
web.php
Route::get('payhere-payment,'[PayHereChekoutControler::class, 'payhereCheckout']);
payhere_hidden_checkout.blade.php
<form id="payhere" style="display:none" method="post" action="https://sandbox.payhere.lk/pay/checkout">
<input type="text" name="first_name" value="{{$first_name}}">
<input type="text" name="email" value="{{$email}}">
<input type="submit" value="Buy Now">
</form>
<script>
$(document).ready(function () { // Now the DOM is ready
//Start loader or something here. You don't need to hide the loader because once form submitted it will redirect to payhere
setTimeout(() => {
$('form#payhere').submit();
}, 500)
});
</script>
I have not used this for Payhere but I have implemented this to WEBXPAY. Both the gateways use same process.
Hope this will make a scene to your requirement.

Related

i want to send data from one view to another Laravel view

i have two views, view-1 and view-2.
view-1 has form, which will store data temporary.
i want to get data from view-1 and send it to view-2, which has user profile, where temporary data from view-1 will be shown.
how we can achieve it in Laravel, i know we can store data in SQL
and then fetch it, but how to do it without storing to SQL.
my code:
view: 1
<form >
<div class="form-group">
<label class="col-form-label" >Date</label>
<input type="text" name="sdate" class="form-control">
<input type="submit" class="btn btn-primary" value="Add date" >
</div>
</form>
view 2 Controller:
public function report2($id)
{
$teacher = Teacher::teacher($id);
return View('teachers.report2' ,compact('teacher','today','sdate'));
}
Route:
Route::get('teachers/{id}/report2', 'TeachersController#report2');
Use session, for example in view1 you pass variable of date do this on your controller of view 1
session(['sdate' => $request->sdate]);
and then you can get the value of the session in your controller or view by calling this
$date = session('sdate');
further reading see the docs
i was able to do it using simple php;
in view 1 i added this code:
<form action="report2" method="get">
Date: <input type="text" name="today" placeholder="Date of Birth" class="datepicker form-control"><br>
<input type="submit">
</form>
Laravel view 2:
<?php echo $_GET["today"]; ?><br>

Parsing data from blade form to controller using request

I want to parsing my label name="predictDataTemp" in form into my controller, I already set the value form my label, but when I want to request the data still null
content.blade.php
<div class="form-group" align="center">
<label for="exampleResult" name="result">Result</label>
<label for="examplePredict" id="predictData" class="form-control">
<input type="hidden" name="predictDataTemp">
</label>
</div>
controller
public function result(Request $request){
$this->validate($request,[
'mCalories'=>'required',
'mCholesterol'=>'required',
'mFat'=>'required',
'mProtein'=>'required',
'mSugars'=>'required'
]);
$item= array();
array_push($item,array('Calories'=>$request->mCalories,'Cholesterol'=>$request->mCholesterol,'Fat'=>$request->mFat,'Protein'=>$request->mProtein,'Sugars'=>$request->mSugars,'Predict'=>$request->predictDataTemp));
return json_encode($item);
}
Your input has no value.
If you want to give it a value with jQuery (looking at your previous comments)
Give the input an id
<input type="hidden" name="predictDataTemp" id="predictDataTemp">
Then assign it in jQuery
$('#predictDataTemp').val('pass value here');
label don't have name attribute, it has only two attribute for and form so you can pass value in hidden input tag, Read this article
Instead
<label type="text" for="examplePredict" id="predictData" name="predictDataTemp" class="form-control"></label>
Use this
<label type="text" for="examplePredict" class="form-control"></label>
<input type="hidden" name="predictDataTemp" id="predictData" value="something">

Thymeleaf form with path variable

I have a form with a method get and with an action. When I submit the form, the action parameter contains id as a standard parameter like ?id=1. How do I pass this parameter as path variable?
<form method="get" th:action="#{/mycontroller/}">
<input type="text" id="id" name="id"/>
<input type="submit"/>
</form>
Your html:
<form id="myForm" method="get" th:action="#{/mycontroller/}">
<input type="text" id="id" name="id"/>
<input type="submit"/>
</form>
And then with JQuery you could do something like this:
var $form = $( '#myForm' );
var $idField = $( "#id" );
$form.submit( function( event ) {
// respects th:action="#{/mycontroller/}" and appends id
$form.attr( 'action', $form.attr('action') + $idField.val() );
// otherwise ?id=xx
$idField.prop( "disabled", true );
// submits the form in the normal way !
return;
});

How to include headers in an ajax post request to web api

Hey guys I am having an issue I am a little confused with as I am new to dealing with Web API's. I am trying to run a POST from an html page to my web api to create a user. In the post method though it checks for authentication based on headers of the users id. How would I go about including a header when I send my ajax post. Right now I am getting the forbidden status response, so I know the ajax is actually hitting the method.
Here is my ajax post call:
$(function () {
var $users = $("#users");
$("#postForm").submit(function (event) {
event.preventDefault();
var $form = $(this),
firstName = $form.find("input[name='firstName']").val(),
lastName = $form.find("input[name='lastName']").val(),
email = $form.find("input[name='email']").val(),
password = $form.find("input[name='password']").val(),
url = $form.attr("action");
var posting = $.post(url, { firstName: firstName, lastName: lastName, email: email, password: password });
posting.done(function (data) {
var content = $(data).find("#content");
$("#result").empty().append(content);
});
});
});
and this is my html:
form action="http://localhost:24500/api/User" id="postForm">
<input type="text" name="firstName" placeholder="First Name">
<input type="text" name="lastName" placeholder="Last Name">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Post User">
</form>
<div id="result"></div>
You simply need to use the more flexible .ajax() function. It allows you to specify username and password for basic authentication as configuration parameters.
The documentation - https://api.jquery.com/jQuery.ajax/

Codeigniter Cart: How to add multiple items with ajax and jquery

I'm building a ajax based shopping cart with Codeigniter, and the add / remove functions work perfectly. I am now trying to add an option for adding multiple items, and can't get it to work.
Here's the markup I'm using. I'm not sure if it's the best design, but it's working with the non-ajax function, so I guess it should be fine.
<form action="cart/add_multiple" method="post" accept-charset="utf-8">
<input type="hidden" name="items[0][id]" value="3571310" />
<input type="hidden" name="items[0][qty]" value="1" />
<input type="hidden" name="items[0][price]" value="59.00" />
<input type="hidden" name="items[0][name]" value="London" />
<input type="hidden" name="items[0][heb_name]" value="לונדון" />
<input type="hidden" name="items[0][full_price]" value="59.00" />
<input type="hidden" name="items[0][discount_price]" value="59.00" />
<input type="hidden" name="items[1][id]" value="7397903" />
<input type="hidden" name="items[1][qty]" value="1" />
<input type="hidden" name="items[1][price]" value="29.00" />
<input type="hidden" name="items[1][name]" value="London Triple" />
<input type="hidden" name="items[1][heb_name]" value="לונדון טריפל" />
<input type="hidden" name="items[1][full_price]" value="29.00" />
<input type="hidden" name="items[1][discount_price]" value="29.00" />
<input type="submit" name="add_multi" value="add to cart" /></form>
The ajax script is as follows:
$(document).ready(function() {
$(document).on("submit", "div#winning_combo_small form", function () { //catches every click on the submit button of the "add to cart" form
var items = $(this).serialize();
alert(items);
$.post(base_url + "cart/add_multiple", {items: items, ajax: '1' },
function(data){
if (data =='true')
{ // Interact with returned data
$.get(base_url + "cart", function(cart){ // Get the contents of the url cart/show_cart
$("#cart_sidebar").html(cart);
})
$.get(base_url + "cart/count_items", function(items){
$("#cart_items").html(items);
})
}
});
return false;
})
});
But it's not working, because the add_multiple function receives the data as a string, not an array. Do I have to decode the data somehow to convert it to an array? Do the Hebrew characters get in the way and mess it all up?
I should say that when posting the form the regular way, without ajax, the items are added to the cart and all works well. So what is the difference between the regular post and the ajax post?
Well, I got it to work, though I'm not sure if it's the most elegant way.
Here's what I did:
In the ajax script, I changed var items = $(this).serialize(); to var items = $(this).serializeArray();. I now get an array instead of a string, but it's not the format I need to insert into the cart. So I looped over this array to create an array in the desired format, and used that new array to insert into the cart.
This is my add_multiple function under the cart controller:
function add_multiple()
{
$items = $this->input->post('items');
$ajax = $this->input->post('ajax');
// Check if user has javascript enabled
if($ajax != '1'){
$this->cart->insert($items); //if posted the regular non-ajax way, the fields will be in an array in the correct format
echo 'false';
redirect('cart'); // If javascript is not enabled, reload the page with new data
}else{
$i = 0;
foreach($items as $key=>$form_field)
{
$field_name = $form_field['name'];
$from_char = strrpos($field_name, '[') +1 ;
$length = strlen($field_name)-$from_char-1;
$field = substr($field_name,$from_char,$length);
$data[$i][$field] = $form_field['value'];
if ($field == "discount_price") $i+=1; // I know 'discount price' is always the last field
}
$this->cart->insert($data);
echo 'true'; // If javascript is enabled, return true, so the cart gets updated
}
}

Resources