How to access a variable used in java script from jsp page? - javascript

I am using ajax in my web page.I want to access a variable used in java script function (in head section of html) by a jsp page.Jsp page is retrieving data from database using that variable.
How can i do that?
Please help me.

if you need the call data you will set & or have a var that's empty before hand. what I realized is that ajax localizes even declared new var's the best way i've found is to append to a existing. Now with the new string and or literal array / object
<script>
function s(e){
alert(e);
}
var a = '';
//Jquery Version
$.get('test.php',function(data){
a += data;
s(a);
});
// Javascript Version
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
a += ajaxRequest.responseText;
s(a);
}
}
ajaxRequest.open("GET", "test.php" , true);
ajaxRequest.send(null);
}
$(function(){
ajaxFunction();
});
//-->
</script>

You can do it by adding new jsp file, flow will be like this :
Create new jsp file like databaseOperation.jsp which will contain your code for retrieving database record.
Through javascript function, call databaseOperation.jsp file and pass your javascript varible.
Access this variable in your jsp file and retrieve the required code from DB.

You can simply do this by making a ajax call and passing that variable with ajax request
<script>
var id=1;
$.get("yourpage?id="+id,function(){
//get this id serverside using `get`
})
</script>

You have to change your approach to get this done. We cannot set javascript variable value to the the database code which is written in the jsp file. This is because, the database code will be rendered from the serverside and only the html will be sent to the client.
You can achieve this by having a Controller(Servlet) with this database code with asynchronous support and in your jsp file, call this controller through javascript ajax and manipulate the HTML DOM for your requirement.

Related

How to call a JavaScript function declared in a PHP file? [duplicate]

I want to know is it possible to call a php function within javascript, only and only when a condition is true. For example
<script type="text/javascript">
if (foo==bar)
{
phpFunction(); call the php function
}
</script>
Is there any means of doing this.. If so let me know. Thanks
PHP is server side and Javascript is client so not really (yes I know there is some server side JS). What you could do is use Ajax and make a call to a PHP page to get some results.
The PHP function cannot be called in the way that you have illustrated above. However you can call a PHP script using AJAX, code is as shown below. Also you can find a simple example here. Let me know if you need further clarification
Using Jquery
<script type="text/javascript" src="./jquery-1.4.2.js"></script>
<script type="text/javascript">
function compute() {
var params="session=123";
$.post('myphpscript.php',params,function(data){
alert(data);//for testing if data is being fetched
var myObject = eval('(' + data + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
});
}
</script>
Barebones Javascript Alternative
<script type="text/javascript">
function compute() {
var params="session=123"
var xmlHttp;
var addend_1=document.getElementById("par_1").value;
var addend_2=document.getElementById("par_2").value;
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("No Ajax for YOU!");
return false;
}
}
}
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4) {
ret_value=xmlHttp.responseText;
var myObject = eval('(' + ret_value + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
}
}
xmlHttp.open("POST", "http://yoururl/getjs.php", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(params);
}
</script>
No that's not possible. PHP code runs before (server-side) javascript (client-side)
The other answers have it right.
However, there is a library, XAJAX, that helps simulate the act of calling a PHP function from JavaScript, using AJAX and a particularly designed PHP library.
It's a little complicated, and it would be much easier to learn to use $.get and $.post in jQuery, since they are better designed and simpler, and once you get your head around how they work, you won't feel the need to call PHP from JavaScript directly.
PHP always runs before the page loads. JavaScript always runs after the page loads. They never run in tandem.
The closest solution is to use AJAX or a browser redirect to call another .php file from the server.

Ajax refresh does not refresh the Java script

I have a JSP page that refreshes every 5 seconds Using ajax.
The page i am calling having javascript that is not getting refreshed .
Please tell me how to achieve that.
Below is the code i am using to refresh that page .
refresh is the name of the div where i am displaying the data.
<script type="text/javascript">
function AutoRefresh() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("No AJAX");
return false;
}
}
}
xmlHttp.onreadystatechange = function () {
//alert("hi");
if (xmlHttp.readyState == 4) {
document.getElementById('TotalRoutes').innerHTML = xmlHttp.responseText;
setTimeout('AutoRefresh()', 10 * 1000); // JavaScript function calls AutoRefresh() every 3 seconds
}
}
xmlHttp.open("GET", "QAGENIE.jsp", true);
xmlHttp.send(null);
}
</script>
Here js files in the QAGENIE.jsp page is not getting refreshed on the ajax call
I think you are not calling AutoRefresh function first time. so nothing will be execute. and if you are calling from outside of your code which you gave here, then please post whole web page code in question.
setTimeout(AutoRefresh,5000); for every 5 seconds
if (xmlhttp.readyState==4 && xmlhttp.status==200)
window.onload = AutoRefresh();
When you call document.getElementById('TotalRoutes').innerHTML=xmlHttp.responseText;, script tags inside the "QAGENIE.jsp" are not executed, that's why:
js files in the QAGENIE.jsp page is not getting refreshed.
Since the question is tagged with jQuery, you could try $.ajax and $.html. Like this:
function AutoRefresh(){
$.ajax({
url:"QAGENIE.jsp"
})
.done(function(response){
$("#TotalRoutes").html(response);
setTimeout(AutoRefresh,10*1000);
});
}
AutoRefresh(); //call this to trigger the first call
$.html automatically parses and executes script tags in the response HTML.
There is 1 more thing to notice is browser cache, if your js files are cacheable (as it usually does by the cache response header from server), the js files may be served from the cached. If you need to always refresh with new js files, ensure your js files are not returned with a cache header, or try to append a random string at the end of the script tags. Like this:
<script src="yourFile.js?[randomstring]"></script>

Getting remote html page fails give me the php code itself instead, how to fix?

Well the problem is simple I need the javascript to get content of remote webpage, because there is no way to do it directly I am doing it from local php file and ajax in the java script just like this
The php file:
"getpage.php?url=http://stackoverflow.com" '
The php code :
<?php
$htm = file_get_contents($_GET['url']);
echo $htm; ?>
This code get content of the html page I direct him too.
The AJAX code :
function makeAJAXObject() {
var ajaxRequest;
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
return false;
}
}
}
return ajaxRequest;
}
'
And I call him latter in my script like this :
window.ajax = makeAJAXObject();
window.ajax.open("GET","getpage.php"+ queryString, true);
The problem is than I do
alert(window.ajax.responseText);
instead giving me the content of the url I asked him too Its give me the actual php script that I wrote above.
This script works on localhost just fine, but I need it to work form local computer without reuploading to any server, there is away to do it ?
Edit :
The php file is on the pc, I am building a win 8 app , it's not like I have a url or something.
You need to check your remote server configuration to make sure that PHP file are processed by the server. Make sure mod_php is installed in apache and you have the proper AddType to process php files.
See this question: why are my php files showing as plain text?
Also, this is a HUGE security issue, you need to check what is requested and/or whitelist it.
What if I call
getpage.php?url=/etc/passwd
getpage.php?url=/your/secret/file
Because you don't do any checks, you would simply return the results to me ...

SQL query using AJAX in Wordpress theme

I'm attempting to use AJAX to insert data into a database, but am unable to connect to the .php file on the server end. I'm thinking this is due to the fact that this is all run on Wordpress, so my normal url path to the .php file might not be correct.
Here is my setup:
Template file:
$('#newsletter-register').submit(function(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
alert(ajaxRequest.responseText);
}
}
ajaxRequest.open("GET", "register_newsletter.php", true);
ajaxRequest.send(null);
});
'#newsletter-register' is form that the user will use to submit his/her information. The alert when the ajaxRequest is at readyState 4 is thrown correctly, but will an empty value.
My php is a simple echo returning a string to signal that the connection is correct (presently I'm just trying to see if the files are correctly calling eachother).
I'm thinking it must be the url path to register_newsletter.php as I've tried placing the code within the template file, outside, etc.
My javascript file is located in /theme/assets/js/code.js where as my template files (including the register_newsletter.php file) in /theme.
Any ideas?
I had this type of issue yesterday. In my situation the page would only be accessed from
www.site.com/aFolder/
The script was stored in my
'/wp-content/themes/themeName/processForm.php'
folder.
and the URL I used was:
../wp-content/themes/themeName/processForm.php
My JS was simply in the head of the main header.php file, but note that the URL I had to use was relative to the URL the page the script was accessed from.
Does that shed any light on things?
EDIT:
As troubleshooting steps, try ensuring you can access your php file from it's absolute URL, and have a look in firebug to see what link is being called when you fire the ajax request to see if it matches up with what you expect.

Return script content that has src attribute

i am having a bit of a problem here and i don't even know if it is possible at all, here's my dilema:
I have this script code:
<script id='script1' src='http://link.to.js'></script>
While using firebug, i can clearly see that the script has bee loaded between those tags, like this
<script id='script1' src='http://link.to.js'>
function something(){
alert('hi');}
</script>
What i want to do is, by means of another script, get the content between those tags, something like
var x = document.getElementById('script1').innerHtml;
document.getElementById('somedividhere').innerHtml = x;
That works perfectly WHEN the code is already part of the html, not when its loaded from src.
I have been looking for this for hours and i have not found any hint, hope someone can help me on this.
I think Firebug only shows you that for convenience sake. If you want to get the code from the script, you'll have to use AJAX.
You could do something like this:
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var scriptcontent = ajaxRequest.responseText;
//Do something with the content
}
}
ajaxRequest.open("GET", document.getElementById('script1').src, true);
ajaxRequest.send(null);
}
Just a few notes:
This will only work for scripts
located on your site due to the
same origin
policy.
I took the ajax code from this
site
and modified it.
This would be a lot
easier with
jQuery

Categories