How can I pass RESULT from javascript to laravel function as amount? - javascript

I want to save this result as amount, when I do console.log(result); I see that know what number I put in input, but how to save it in Laravel function?
function makeOffer(nftid) {
swal({
title: "Do you want to make offer?",
text: "Enter amount",
input: 'text',
type: 'warning',
showCancelButton: true,
showConfirmButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
}).then((result) => {
if (result) {
axios.post("/myaccount/makeoffer/" + nftid).then(response => {
window.location.reload();
});
}
});
}
public function makeOffer($id, Request $request){
$nft=NFT::where('id','=',$id)->first();
if($nft->status=='pending') {
$nft_auction = new NftAuctions();
$nft_auction->nft_id = $nft->id;
$nft_auction->owner_id = $nft->user->id;
$nft_auction->buyer_id = Auth::id();
$nft_auction->amount = "there should be amount";
$nft_auction->status = 'pending';
$nft_auction->save();
return back();
}
else{
abort(404);
}
}

Axios' .post() method takes 2 arguments; the URL and the data you want to send to the backend, so adjust it to:
axios.post("/myaccount/makeoffer/" + nftid, {'amount': result})
.then(response => {
window.location.reload();
});
Then, in your backend, you can access this as $request->input('amount'):
public function makeOffer($id, Request $request){
$nft = NFT::find($id);
if($nft->status == 'pending') {
$nftAuction = new NftAuctions();
// ...
$nftAuction->amount = $request->input('amount');
// ...
$nftAuction->save();
return back();
}
}
Some notes:
Model::where('id', '=', $id)->first() can be shortened to Model::find($id).
Model names are PascalCase and singular: NFT should be Nft, and NftAuctions should be NftAuction
Documentation:
Axios .post() method
Laravel: Retrieving Input

Related

Display notification pop-up box on open-source CRM

I am using a vtiger Crm system and I would like to use the pop up notification to display my own messages. I wrote an event handler that triggers after model save, in this handler I would like to call the notification box with my own message.
Here is a working example that is from the 'Products' module handlers, this code was pre-written, it checks if there were duplicate item numbers and shows a message 'LBL_DUPLICATE_item_number' in the pop-up box
class Products_DuplicateItemNumber_Handler
{
/**
* EditViewPreSave handler function.
*
* #param App\EventHandler $eventHandler
*/
public function editViewPreSave(App\EventHandler $eventHandler)
{
$recordModel = $eventHandler->getRecordModel();
$response = ['result' => true];
$fieldModel = $recordModel->getModule()->getFieldByName('item_number');
if ($fieldModel->isViewable() && ($item_number = $recordModel->get('item_number'))) {
$queryGenerator = new \App\QueryGenerator($recordModel->getModuleName());
$queryGenerator->setStateCondition('All');
$queryGenerator->setFields(['id'])->permissions = false;
$queryGenerator->addCondition($fieldModel->getName(), $item_number, 'e');
if ($recordModel->getId()) {
$queryGenerator->addCondition('id', $recordModel->getId(), 'n');
}
if ($queryGenerator->createQuery()->exists()) {
$response = [
'result' => false,
'hoverField' => 'item_number',
'message' => App\Language::translate('LBL_DUPLICATE_item_number', $recordModel->getModuleName())
];
}
}
return $response;
}
}
However, when i try to return $respone in 'editViewPreSave' of another module, nothing happens.
After some digging around i found out that the system uses 'Pnotify' library to show the pop up message, and i belive it's being called in a js file called 'edit.js' in this path 'public_html/layouts/basic/modules/Vtiger/resources'
preSaveValidation: function (form) {
const aDeferred = $.Deferred();
if (form.find('#preSaveValidation').val()) {
document.progressLoader = $.progressIndicator({
message: app.vtranslate('JS_SAVE_LOADER_INFO'),
position: 'html',
blockInfo: {
enabled: true
}
});
let formData = new FormData(form[0]);
formData.append('mode', 'preSaveValidation');
AppConnector.request({
async: false,
url: 'index.php',
type: 'POST',
data: formData,
processData: false,
contentType: false
})
.done((data) => {
document.progressLoader.progressIndicator({ mode: 'hide' });
let response = data.result;
for (let i = 0; i < response.length; i++) {
if (response[i].result !== true) {
app.showNotify({
text: response[i].message ? response[i].message : app.vtranslate('JS_ERROR'),
type: 'error'
});
if (response[i].hoverField != undefined) {
form.find('[name="' + response[i].hoverField + '"]').focus();
}
}
}
aDeferred.resolve(data.result.length <= 0);
})
.fail((textStatus, errorThrown) => {
document.progressLoader.progressIndicator({ mode: 'hide' });
app.showNotify({
text: app.vtranslate('JS_ERROR'),
type: 'error'
});
app.errorLog(textStatus, errorThrown);
aDeferred.resolve(false);
});
} else {
aDeferred.resolve(true);
}
return aDeferred.promise();
},
I believe that 'app.showNotify' is the function called to display the pop-up box, yet i'm not sure how to replicate the code for my own use, i would like to know the best approach to do this

Axios send too multiples request after submiting the form

I started working on small project using Laravel and Nuxt Js, so i have created a small for to add users in the database. every thing is going well, i have a small issue, my axios script send multiple request like a loop :
this is the full code :
<script>
import $ from 'jquery'
import Swal from 'sweetalert2'
import toastr from 'toastr'
import Vue from 'vue'
Vue.component('pagination', require('laravel-vue-pagination'))
export default {
layout: 'app',
data () {
return {
laravelData: {},
formFields: {},
search: null,
refresh: false
}
},
watch: {
refresh () {
this.store()
this.refresh = false
}
},
mounted () {
$('a.just-kidding').hide()
this.index(1)
},
methods: {
index (page = 1) {
this.$axios.$get('/customer?page=' + page).then((response) => {
this.laravelData = response
this.refresh = true
})
},
store () {
const formData = $('#add-customer').serialize()
return this.$axios.$post('/customer/store', formData).then((response) => {
this.refresh = true
})
},
find () {
if (this.search === '') {
this.index()
} else {
this.$axios.$get('/customer/find?customer=' + this.search).then((response) => {
this.laravelData = response
})
}
},
destroy (customerId) {
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.value) {
// this.$Progress.start();
this.$axios.$get('/customer/destroy?customer=' + customerId).then((response) => {
if (response.success) {
toastr.success(response.error, 'Ahoy Hoy !!', { 'positionClass': 'toast-top-left' })
this.refresh = true
} else {
toastr.error(response.error, 'Owh :( !!', { 'positionClass': 'toast-top-left' })
}
})
// this.$Progress.finish();
}
})
}
}
}
</script>
and here is my controller :
public function store(Request $request)
{
DB::transaction(function () use ($request){
$customerQuery = Customer::create($request->post('general'))->id;
$shippingInfos = array_merge(array('customer_id' => $customerQuery), $request->post('address'));
$shippingQuery = Shipping::create($shippingInfos);
return true;
});
}
i have created a Middleware page called cors in my laravel,
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
}
}
watch: {
refresh () {
this.store()
this.refresh = false
}
},
This will cause an infinite loop, because you're changing this.refresh in the watcher function that's monitoring this.refresh, which will re-trigger the watch function, which will change it, which will trigger the watcher, which will change it, which will trigger the watcher, which will change it, which will trigger the watcher, which will change it, which will trigger the watcher, which will change it...
You get the point.

Asp.Net MVC Javascript functions not working in Razor if statement

I'm returning View from my action after post event and doing some javascript things in view. But javascript function calls not working in razor if statement.
$.post("#Url.Action("Login", "Account")",
accountObject,
function(result) {
$.unblockUI();
if (result.isSuccess) {
var object = #Html.Raw(Json.Encode(#Model.CrmIntegrationModel));
$.post("#Url.Action("File")",
object,
function(resultData) {
#if (!Model.IsFileViewModelEmpty)
{
var model = Model.UploadFileViewModel.PortalEntity as Task;
if (!Model.UploadFileViewModel.HasError)
{
#:alert("Worked! ");
if (model != null)
{
var task = model;
if (task.State != State.Open)
{
<text>
$.blockUI({ target: '#uploadPanel', message: null });
$(swal({
title: "Warning",
text:
"File can not be uploaded for task that status is not open.",
type: "warning",
confirmButtonClass: "btn-warning",
confirmButtonText: "OK"
}));
</text>
}
else
{
#: LoadDocumentTypes();
}
}
else
{
#: LoadDocumentTypes();
}
}
else
{
<text>
$.blockUI({ message: null });
$(swal({
title: "Warning",
text: '#Html.Raw(Model.UploadFileViewModel.ErrorMessage)',
type: "warning",
allowOutsideClick: false,
showConfirmButton: false
}));
</text>
}
}
});
}
});
When I passif (!Model.UploadFileViewModel.HasError) statement as true my #:alert("Worked !"); not working. Also below lines #: LoadDocumentTypes(); function call not working. How can I resolve this problem ?

Uncaught (in promise) cancel using SweetAlert2

how do I properly escape the cancel button without throwing an error when using promises? My code throws an alert confirmation with a required checkbox. the code executes as it should to the user, but it throws an error in the console window:
Uncaught (in promise) cancel
//validation logic all passes...Now proceed to...
else
{
//determine and parse Discounts
var myLookup = document.getElementsByName("myLookup")[0].value;
$.post( "findthem.php", {myLookup: myLookup })
.done(function(json_data){
var theResponse1 = $.parseJSON(json_data);
myDiscountRate = theResponse1['ourDiscountFound'];
}).then( function(callback){
priceRate = priceRate * (1 - (.01 * myDiscountRate));
newRate = priceRate.toFixed(2);
}
swal({
title: "Confirm",
input: 'checkbox',
inputValue: 0,
type: "warning",
inputPlaceholder: 'I agree to Your new Rate is :'+newRate,
showCancelButton: true,
confirmButtonText: 'Confirm',
showLoaderOnConfirm: true,
preConfirm: function(result) {
return new Promise(function(resolve, reject) {
if (result) {
$.post("my.php", {
Data: data
})
.done(
function(json_data) {
var data_array = $.parseJSON(json_data);
var moreDetails = '';
var resulting = 'error';
var details = "Transaction Declined"
if (data_array["trxApproved"] == true) {
resulting = 'success';
details = "Confirmed"
moreDetails = "<br>Approved<b>" + data_array["approved"] + "</b>" +
"<br>Details Code: <b>" + data_array["detailsCode"] + "</b>";
}
swal({
type: resulting,
title: details,
html: "<h1>Details: </h1>" + data_array["messagetext"] + moreDetails
});
}
);
resolve();
} else {
reject('You must agree to our Terms & Conditions ');
}
});
},
allowOutsideClick: false
}).then(function(json_data) {
})
});
Update (Jan 2017): This issue has been fixed in v7: v7 upgrade guide ↗
You need to add a rejection handler to the Promise. Alternatively, you can use .catch(swal.noop) as a quick way to simply suppress the errors:
swal('...')
.catch(swal.noop);
PS. the package you're using is called SweetAlert2, not SweetAlert. In future questions please mention it so you can get more relevant answers.
SweetAlert2 rejects the result promise when the cancel button is pressed. You can handle that:
swal({
…
}).then(function(json_data) {
…
}, function(dismiss) {
if (dismiss === 'cancel') { // you might also handle 'close' or 'timer' if you used those
// ignore
} else {
throw dismiss;
}
})
If you don't need to do anything with the json_data, you might also use the catch method.
new Promise(function(resolve, reject) { is not necessary. $.post() returns a jQuery promise object.
Possible solution substitutes Promise.reject() for new Promise() constructor; removed .then() that was placed as an option to first swal() call; pattern appears to expect a Promise to be returned from preConfirm, though not certain what value is expected to be returned from .done() other than json_data.
swal({
title: "Confirm",
input: 'checkbox',
inputValue: 0,
type: "warning",
inputPlaceholder: 'I agree to ',
showCancelButton: true,
confirmButtonText: 'Confirm',
showLoaderOnConfirm: true,
preConfirm: function(result) {
if (result) {
return $.post("my.php", {
Data: data
})
.done(
function(json_data) {
var data_array = $.parseJSON(json_data);
var moreDetails = '';
var resulting = 'error';
var details = "Transaction Declined"
if (data_array["trxApproved"] == true) {
resulting = 'success';
details = "Confirmed"
moreDetails = "<br>Approved<b>" + data_array["approved"] + "</b>" +
"<br>Details Code: <b>" + data_array["detailsCode"] + "</b>";
}
swal({
type: resulting,
title: details,
html: "<h1>Details: </h1>" + data_array["messagetext"] + moreDetails
});
}
);
} else {
return Promise.reject('You must agree to our Terms & Conditions ');
}
},
allowOutsideClick: false
});
you will need to catch the action for cancel
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then(function(json_data) {
//delete item
}, function(dismiss) {
if (dismiss === 'cancel' || dismiss === 'close') {
// ignore
}
})
Adding catch(swal.noop); at the end swal function will solve this problem
For example:
swal({
}).then(function() {
}).catch(swal.noop);

SweetAlert2 Update Counter for User Feedback

Is there a way to update the text on SweetAlert2 alert to show the number of rows that have been processed in a a really long javascript loop? Unfortunately people have been leaving the page and then only half the rows get saved.
I thought I might be able to use jQuery type syntax, but not sure what the proper select might be.
$('#rowsprocessed').text(count);
swal({
title: 'Save Order.',
input: 'checkbox',
inputValue: 0,
inputPlaceholder: 'Remove Zero(s) Quantity Item(s) Before Saving the Order?',
html: 'For large templates this may take a few moments. This message will automatically close when the process is complete.',
type: 'info',
showCancelButton: true,
confirmButtonText: 'Submit',
showLoaderOnConfirm: true,
preConfirm: function(checkbox) {
return new Promise(function(resolve, reject) {
removeZeros = checkbox;
setTimeout(function() {
swal.showLoading();
$.post("/components/com_sails/views/neworderform/saveOrderHeader.php",
{
orderid: orderid,
accountid: accountid,
buyerid: buyerid,
vendorid: vendorid,
ponumber: ponumber,
specialinstr: specialinstr,
orderDate: orderDate,
shipDate: shipDate,
cancelDate: cancelDate
},
function (result) {
if (result.return == 1) {
// assign order id to holder field
$('#orderInput').jqxInput('val', result.ordernbr);
// loop through our rows and save depending on the removeZero marker
var rows = $('#jqxgrid').jqxGrid('getdisplayrows');
var rowsToRemove = [];
var linessaved = 0;
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
// get row info for delete
if ((removeZeros == 1) && row['quantity'] == 0) {
rowsToRemove.push(row.uid);
}
// run database update
$.ajax({
type: 'POST',
url: '/components/com_sails/views/neworderform/saveOrderLine.php',
data: {
orderid: result.ordernbr,
removezeros: removeZeros,
rowdata: row
},
success: function (rowSaveData) {
// alert('rowSaveData ' + rowSaveData.return + " " + rowSaveData.isbn + " " + rowSaveData.action + " " + rowSaveData.msg + " row.uid: " + row.uid);
// if there is a problem what do we do????
if (rowSaveData.return == 1) {
$('#rowsprocessed').text(i);
}
if (rowSaveData.return == -1) {
// add to error message?
}
},
datatype: 'json',
async: false});
}
if (removeZeros == 1) {
// delete our zero rows
var commit = $("#jqxgrid").jqxGrid('deleterow', rowsToRemove);
$('#jqxgrid').jqxGrid('render');
lastselectedrow = -1;
}
// set save marker??
isDirty = false;
}
else {
// there was an error saving the header
// need to get this logged
alert('Error Saving Order. Details: ' + result.msg);
}
}, "json");
resolve();
}, 2000);
});
},
allowOutsideClick: false
}).then(function() {
swal({
type: 'success',
title: 'Order saved',
html: '<b><div id="rowsprocessed">0</div></b> rows saved.',
timer: 4000
});
})
Absolutely you can, you just pass in an additional element with your {html: "..."} that you can use as a means of updating the user.
Something Like:
{
...
html: 'For large templates this may take a few moments. This message will automatically close when the process is complete.<br/><span class="swal2- status"></span>',
...
}
And then use this syntax to update:
var $status = $('.swal2-status');
$status.html("I'm an update");
See the example here:
https://jsfiddle.net/1mvnxp3L/

Categories

Resources