jQuery syntax in Laravel View - javascript

My code in my View (Laravel framework):
...
var d_from = $('#date_from').val();
$('#total-invoices').html('{{ App\Output_Detail::getTotalInvoices(' + d_from + ') }}');
...
$('#total-invoices') is a HTML Label component.
I have a syntax error in my above code above: ..(' + d_from + ')..
If I put a static variable, the return from my Model function is working fine:
{{ App\Output_Detail::getTotalInvoices("2015-11-03") }}

You're mixing JavaScript and PHP here. PHP is a server side language, which means it is processed on your server. JavaScript is a client-side language, which is run on the client's browser. So your PHP will be parsed BEFORE your JavaScript. You're trying to use a JavaScript variable d_from inside PHP, but that variable won't be declared until PHP is done and the HTML is sent to the client's browser.
As far as a solution goes -- whatever value you're populating the #date_from input with you could also drop into this getTotalInvoices method. If that value isn't available until it hits the client-side, you'll need to make an AJAX call back to the server to run this method.

You cannot have the backend code depend on the front end code in that way.
When your page loads, all the PHP Laravel code gets executed on the Server machine.
Then, all Javascript code gets executed on the resulting page on the clients machine. That will be your computer or the users computers.
So, getTotalInvoces is receiving the string literally as ' + d_from + '.
If you need to get the values after a page has been loaded, you will need to make an ajax call to the server.

I solved my issue:
...
// ajax
$.get('{{ URL::to('employee/ajax_Total_Invoices') }}?date_from=' + $('#date_from').val(), function(data){
// success data
$('#total-invoices').html(''+data+'');
});
...

Related

Getting value from a console.log to html

The function I have written works fine and the value correctly writes to my terminal onSubmit, however I'm struggling to piece together why this code isn't updating my html.
router.post('/index', function(req, res, next) {
// ...Get form values, do calculations to get toCost value.
console.log('$' + toCost);
$(document).ready(function() {
var output = document.getElementById('cost');
output.innerHTML = toCost;
});
res.location('/');
res.redirect('/');
})
I receive the following error and jquery is loading fine.
$ is not defined
Admittedly this is an over-engineered node/express app. The code snippet lives wrapped in a route file, inside a post request.
How do I get my value onto the html?
Jade layout
extends layout
block content
form(...)
div#cost
The normal way to do this would be as follows:
router.post('/index', function(req, res) { <<< 'next' removed (only needed if using middleware)
// ...Get form values, do calculations to get toCost value.
console.log('$' + toCost);
res.render('indexTemplate', {cost: toCost}); <<< pass toCost through to jade as 'cost'
});
Then in your jade file for the indexTemplate you can reference the 'cost' variable passed in like this:
indexTemplate.jade:
extends layout
block content
form(...)
div#cost #{cost} <<< adds the cost variable to page
Then the value of toCost will appear in the resulting page.
No jQuery is required on the server side.
jQuery is made for DOM manipulations and there's no DOM on a server.
Try using 'jsdom'.
jQuery is made for client side scripting, not for server-side client manipulations.
It seems that you're trying to make changes on client-side from your backend. It doesn't work that way.
You could create a variable on backend for storing calculation result. And get this value by get query from client-side
You're tring to reach DOM (that is on client side) from NodeJS on a server side. It doesn't work that way.

Set Session value using Javascript and retrieving the same using razor umbraco

I have written following code let say in Page 1
<a Onclick="setSessionValue()" href="page2"></a>
<script type="text/javascript">
function setSessionValue()
{
var selectedCarNoideId = "1026";
'<%Session["BannerNoideID"] = "'+ selectedCarNoideId +'";%>'
alert('<%=Session["BannerNoideID"]%>');
}
</script>
And now retrieving session value on other page (Scripting File .chtml) using following code.
<h2>Session-:#Session["BannerNoideID"] </h2>;
In the Page 1 alert PopUp displays "1026" as session value
But In Page 2 tag display following value as a output of session .
"Session-:'+ selectedCarNoideId +'"
Am I missing any thing ?
You're mixing javascript and server-side code in such a way that the javascript isn't being evaluatd as you expect.
The Server side session variable is literally being set to '+ selectedCarNoideId +' as the page is being rendered. Javascript in this case is doing nothing to set the session value.
Although why you're getting the alert message to display 1026 is anyone's guess - is the BannerNoideID session variable being set elsewhere as well perhaps?
If you're trying to save a variable generated client-side with Javascript in the session on the server, you will need to submit it.
One way to do it would be to create a simple MVC Controller (WebAPI by default is sessionless) and then POST the value to it using Ajax or a form post.
Alternatively, you could pass the id through on the QueryString to the next page or something like that - that approach is probably the simplest.
Without knowing more about your setup, workflow and business logic I can't really suggest much more.

making a loop with jquery, Ajax and PHP

i want to make a loop in jquery, Ajax and PHP.
my pages are:
shop.php
do_ajax.php
in the shop.php are variable $p_productid is 1 and $j_productid is $p_productid
var j_productid = <?= $p_productid ?>;
now i do j_productid++ so the output from $j_productid is 2
now i'm posting this with ajax to do_ajax.php
in the do_ajax.php are variable $pa_productid is $_POST['$j_productid'];
now i can place this on html, but i want to set this value in too the variable on $p_productid on shop.php
how i need to do this?
there is working a swipe system in this case so only with php it isnt working i need to work with jquery that's why am i doing this on this way. i got an another solution without AJAX but i want that you cant see on the client side the webpage is refreshing.
JQUERY
wipeLeft: function() {
var j_ProductId = <?= $g_ProductId ?>;
var j_Swiped = 1;
if (j_ProductId < <?= $l_LastProduct ?>){
j_ProductId++
//document.swiping.productid.value = j_ProductId;
//document.swiping.submit();
$.ajax({
url: 'do_ajax.php',
type: 'POST',
data: { swipe : j_Swiped,
productid : j_ProductId},
success: function (data) {
$('.product').html(data);
}
});
}
}
do_ajax.php
if(!empty($_POST['swipe'])){
$l_ProductId = $_POST['productid'];
echo $l_ProductId;
}
You need to understand that the JavaScript (even if generated dynamically by PHP) is not running the same time that PHP is running. Your workflow will be something like this:
PHP script (shop.php) is invoked
PHP script generates output, HTML and JS mixed.
These are all in server side until the web server sends the output to client (browser)
In browser HTML displays and JS runs with starting values that you generated previously by PHP. But in this time, PHP has been finished, not running anymore. PHP variables are not alive anymore.
JS interacts with the user in browser, we can say it's running continuously.
Triggered by an action (swipe) JS sends an (ajax) request from client side to server side. This request transfers the new value to server side, and invokes another PHP script (do_ajax.php). You do whatever you want with the new value (process it and or store it) in server side. You need to understand that you are in a completely disjunct scope in PHP than in your first PHP script. (distinct in time too)
If you want to be sure that, in case of a page reload, the (product ID) value will be the updated value, you need to store it somewhere (user session, key-value store, database, or any persistent) when you get it in server side (so in do_ajax.php) and later load this value in the beginning of your shop.php script ...which will pass it to the JS, and so on. The workflow starts again.

Passing data from PHP to JS and JS to PHP

Hi I'm trying to learn PHP and javascript, therefore I tried to do an exercise about passing data but I didn't understand the js function and currently unable to do anything.
Here is the code
php-code.php
$v1=$_GET['v1'];
$v2=$_GET['v2'];
$v3=$_GET['v3'];
//Some operations about them
echo $output;
my-js.js
var v1 = $('#v1 option:selected').val();
var v2 = $('#v2 option:selected').val();
var v3 = $('#v3 option:selected').val();
//This is where I want to pass these variables to my php file and get the output
//But i don't know how
js-execute.php
//this is where my js gets the variables at first
PHP is a server-side language while JavaScript is a client-side one. This means that PHP will be executed when someone requests a page, but the browser will only get the result of the PHP code. On the other hand, JavaScript is sent to the browser and the browser will execute it at the appropriate time (when the page loads or when an event happens). That's why if you look at the source code of a page, you will be able to see the JavaScript code, but never the PHP code.
If you want to pass values from JavaScript to PHP, you will need to make a remote call to a PHP file. PHP isn't like JavaScript – once it's done running its code, it won't be able to respond to anything without a reload of the page.
The easiest way to send something to a PHP file and fetching the result with JavaScript can probably be achieved with JQuery. It has a function $.get which will fetch a given URL. Just be sure to properly validate the input on the server side – never trust user input.
JavaScript (using JQuery to send v1, v2 and v3 to page.php)
function requestPage(v1, v2, v3) {
$.get('page.php', {'v1':v1, 'v2':v2, 'v3':v3}, function(data) {
alert(data);
});
}
PHP (a trivial example)
// Be sure to properly validate input!
if(isset($_GET['v1']) && is_scalar($_GET['v1'])) {
echo strrev($_GET['v1']);
}

grails gsp javascript integration, how to escape variables?

I have a gsp page (template) where I need to include some javascript. In the example below, how would I get the remoteFunction to understand, the moneyTransId will be set by the javascript function? MoneyTransId comes out fine in the alert, but I can't get it to work in the remoteFunction, and apparently need to escape it somehow.
<script type="text/javascript">
function confirmVoid(moneyTransId) {
var r = confirm("Please confirm the void");
if (r == true) {
alert("ID is: " +moneyTransId);
${remoteFunction(action:"voidTransaction", id:moneyTransId)};
...
Use the following syntax:
${remoteFunction(action:'voidTransaction', params:'\'id=\'+moneyTransId')};
This way, you won't mix server-side code with client-side code.
Hope this helps.
Server side variables and statements can not read client side (javascript) variables.
Server side code runs first, then html and javascript get generated and sent to the client (browser). Then the browser renders HTML and runs javascript. Hope this helps your thought process.
Dmitry.

Categories

Resources