I would like to know that how can i set javascript variable in side Jsp code.
<script type='text/javascript' >
var result;
$.ajax({
type: 'GET',
url: '/api/report/test',
dataType: 'text',
success: function(data) {
result= data;
}
});
var dataTable = <%
out.print(result);
%>
</script>
Above is my Jsp code.In there i call my REST service to fetch data and print on the page.But when i try to set result variable its gave me error.I would like to know that is there any ways to call ajax method inside JSP code or how can i set java script variable inside JSP code.
No, you cannot. The JSP part is serverside, the javascript is client side.
You can only set values serverside if you push them via ajax, but then you will have four steps:
Render page with javascript(JSP)
Ajax call to JSP page(Javascript)
Process values serverside(JSP) and return output
Process returned output from JSP to user(JavaScript)
The javascript parts are purely clientside and will be executed by browser. Your server cant do anything with it. as far as your server is concerned its just text.
The JSP parts are server side and run by the server. Whatever the output it compiles is sent to the user.
You cannot "cross" over.
Related
So my goal is to use PHP to get data from a PostGreSQL database. I want to use this data in a separate javascript file so I can display it on the screen a certain way that I have my website configured. All the tutorials that I have seen online just puts a script tag inside the PHP file but I cannot do that because my website display javascript code is in the separate file. I just need the numbers to be in the javascript file that I got from the PHP file that got its data from the PostGreSQL database. How can I do this?
I just need help with the means to get to the ends because I have researched on my own but it is always not exactly what I want.
PHP:
<?php
$myPDO = new PDO('pgsql:host=myHost; dbname=myDBName', 'myUsername', 'myPassword');
?>
$result = $myPDO->query("SELECT * FROM table WHERE id = 'someID'");
Now I want to use this row's values in another javascript file. How can I do this?
You could use Ajax for this.
You could so something like this in your JS file:
$.ajax({
type: "GET",
url: 'FILENAME.php',
success: function(data){
alert(data);
}
});
and then in your FILENAME.PHP just return the values.
Your JS should then pull through whatever has been returned, in this case, your database query.
Your JS file needs to request the data from your PHP controller, via an AJAX request. You can then manipulate the returned data object whichever way you like.
We have mainly two methods to pass php value to javascript variable
Simple variable method at the time of first page load
<script>
var js_variable = <?php echo $data_php_variable; ?> ;
//this is working only at the first time of the page load
//you can also parse the data to any format
</script>
Use AJAX call to trigger a PHP request and manipulate return PHP value in JS
$.ajax({
type: "GET", //get or post method
url: 'FILENAME.php', //php request url
data :{}, //optional ,you can send data with request
success: function(res){
// this 'res' variable is the php return data in the form of js data
console.log(res);
}
});
ajax method is more dynamic ,it can use any time request handling
use the javascript ajax to call a php api
pass your data at php in your view file , use something like:
var phpData = JSON.parse("<?php echo json_encode($data)); ?>");
I need to load a page where that page needs to display some values with a dynamic pagination. So to load the values I have a rest call, In that rest call I am returning a json object. In the browser console I am able to see the json output. Now My issue is I am getting the response on $document.ready() function. Now I am trying to display the json object values in the HTML which is not happening.
JavaScript:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url : "http://localhost:8080/school-service/school/list/students/1/1",
type: "GET",
dataType: "json",
}).done( function(studentList) {
console.log("AJAX request success:" +studentList.pageNumber);
}).fail( function(jqXHR, textStatus) {
console.log("AJAX request failed with status:" + textStatus);
});
});
</script>
HTML:
<img onclick='previousPage("${studentList.pageNumber}", "${studentList.pageCount}")' src="${context}/images/previous.png">
<c:forEach var="i" begin="1" end="${studentList.pageCount}">
${i}
</c:forEach>
<img onclick='nextPage("${studentList.pageNumber}", "${studentList.pageCount}")' src="${context}/images/next.png"/>
Can anyone please help me that how can I display the json response object value in HTML.
I think you can't because the code you want to replace in your page is belong to a server-side language (i guess asp) and server-side code will be compiled before javascript execution so you'll not found the tags those tags.
So, if I understand what you are trying to do, you are trying to get the value from your AJAX request and include the returned value from .done in the html?
If that is the case, check this link out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
If you are returning a JSON object from .done, you will need to parse the JSON object into a string in order to place it in the DOM. From that point, you will need to decide where it should be placed. For example, you can create a div and say $('that-div').append(returned value).
Another approach could be having a default value in the html, and on .done, replace the html by calling .html on your response. But to do that you will need to grab a reference of $(this).
I hope this helps, if not let me know where my gaps are and we can go over this in a different way.
The code which you write is a server side code with JSTL, and it is not available when the AJAX response is returned.
JSP page will be converted to HTML.
The HTML page will call the server by using AJAX.
The returned response is a JSON which is received in a Javascrip Object.
You need to do some javascrip work to make your a tags
You need to write some Javascript code to render the returned response.
Try this instead
int pageCount = studentList.pageNumber;
Then in your html simply do this
<c:forEach var="i" begin="1" end=studentList.pageNumber>
i
</c:forEach>
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+'');
});
...
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.
How can I send just one element from browser to server fast and without reloading browser page?
Is there an AJAX way to do this, that is a NON-FILE method? The opposite of ".load"?
.load works great sending a single element from server to browser without page reload.
How to do the opposite direction?
Browser is JavaScript.
Server is vxworks with windmarks.
PRESENT METHOD THAT WORKS BUT RELOADS PAGE:
Presently, the browser element is and I use submit to send it to the server, but this takes too long and reloads the browser page.
The element's innerHTML contains data formatted as a vxworks WINDMARK.
(When the vxworks server receives this submission, it reads the windmark and copies it to a 'C' string for backend software to process.)
If you're using jQuery and PHP then something like this should work:
JS:
$.ajax('doServerSuff.php?action1=saveLog', function() {
// do stuff after server received the data
});
PHP (doServerStuff.php):
<?php
if ($_GET['action1'] == 'saveLog') {
//do stuff
}
?>
You can get and send data using jQuery. using something like this:
$.post('urlfromserver',browserdata,function(datafromserver){
//do stuff
})
if you let me put a little bit more, it's a good idea to use JSON to send/receive data to/from server. Having that in mind, you can do something like:
$.post('urlfromserver',{browserdata: JSON.stringify(browserdata)},function(datafromserver){
javascriptObject = jQuery.parseJSON(datafromserver)
//do stuff
})
And in your PHP code, it would be as simple as using json_encode to send data to javascript and json_decode to receive data from javascript
UPDATE
Obtaining the data in the server should be as simple as requesting the object via post or get depending on your send method, and parsing the JSON.
In PHP, this is an example of obtaining data using the above code:
$dataFromBrowser = json_decode($_POST['browserdata'])
Use $.post in jQuery to send the data.
The load intruction can also be used to transmit data to the server:
$().load("url", {limit: 25}, function(){
//transmission finished
});
In this example the parameter limit with the value 25 wil be transmitted to the server.
Taken from:http://api.jquery.com/load/
You can simply do with the ajax call like this
$.ajax({
type: "POST",
url: "yourpage.php?id=someValue",
success:function(data){
//do some stuff here
});
I got it working. Here is the corrected JavaScript, from the above answer.
Here is how to change a single element at the server.
This is also an example of how to write to a vxworks windmark string at a vxworks web server, without reloading the page.
NOTE: no URL is specified, so that the same page is used.
$.ajax({
type: "POST",
url: "?general_page_to_MM_data_1_windmark=CCCCCCCCCCCCCC",
success:function(data_from_server){
}});