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

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.

Related

How to run PHP code in a JavaScript Function?

I am trying to make a function to open a webpage in the same tab as the one you are coming from, (think clicking on a bookmark in a tab). I have the page I want to go to and I know the PHP code to do what I want,
<?php
header("Location: example.php")
?>
I am wondering if there is a way for me to run PHP code in JavaScript so I can do what I want?
(Before anyone asks why I don't just run the code this way, it's because the situation I am in requires me to run the code through a JavaScript function)
You don't need PHP for page redirection. You can simply do this in pure javascript.
function gotoExample() {
window.location.href = './example.php';
}
Mixing PHP and javascript introduces complication to your code. Avoid that if possible.
There are various ways on how you can run a php script inside a js function. One way is via ajax.
//some js logic here
if (foo) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhttp.open("GET", "http://foo.bar/path/to/a/script.php", true);
xhttp.send();
}
What happens on the above code is that when foo evaluates to true, than a XMLHttpRequest is called and a server side script written in php is executed.
However, in your case, it It is better to just handle a redirect on the client side rather than relying on PHP.
if (foo) {
window.location.href = 'http://foo.bar/path/to/a/script.php';
}
There are various ways on how to issue a redirect via js. The interned is huge. You'll find it with just a couple of searches.

AJAX xmlhttp.send() not working

I'm a complete and utter AJAX noob and have been sitting with the same problem for the last 5 hours.
My script code
<script language='javascript'>
function upvote(id ,username)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
}
};
xmlhttp.open("GET", "vote.php?id=" +id+"&username=" +username, true);
xmlhttp.send();
}
</script>
My onclick link,
<a href='javascript:void(0)' onclick='upvote($id,$username)'></a>
$_GET is used to retrieve parameters sent via the URL of the page. For example
../vote.php?id=3&username=anor
My php file works perfect when i tried that.
I don't think there's anything wrong with the PHP anyway. For some reason however, xmlhttp.send(params) is still not sending the required variables to the vote.php file. I tried post AJAX request but it didn't work either.
edit them
If php file
$id = '1';
$username = 'suman';
echo '';
?>
If this is part of your PHP code
onclick='upvote($id, $username)'
it won't work. It should be
onclick='upvote($id, "$username")'
instead. Let's see the example that you posted: $id=3 and $username=anor. This would result in
onclick='upvote(3, anor)'
As long as there is no Javascript variable with the name anor, this would be equivalent to
onclick='upvote(3, undefined)'
Do you get that?
PS: The upvote function itself seems to be fine

Writing in another file with javascript

I have a php script (just for calculation) and a html file. Let's say the php file has finished its calculation and the solution is 10. The following line is in the body of the just mentioned html file:
<div id="here"></div>
Now I want the php file to write the 10 into the html. I thought of adding a few lines of javascript at the end of the php to make the job. The question is if this is even possible with something like (index.html).getElementById(here).innerHTML or something. Both files are in the same folder and setting the proper permission shouldn't be a problem.
I know I could put everything in one file but this is part of a bigger project. I just adapted my problem on this simple example to avoid that you need to read plenty of lines.
Your Script should look like this to get response from PHP
<script>
function loadDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("here").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "yourphp.php?q=" + str, true);
xmlhttp.send();
}
</script>
Hope this solves your problem
ref: http://www.w3schools.com/ajax/ajax_php.asp
PHP is server-side and Javascript is client-side. I don't recommend you to use embedded PHP but you should take a look at Ajax Requests.
Here's some documentation

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

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.

How can I open a JSON file in JavaScript without jQuery?

I am writing some code in JavaScript. In this code i want to read a json file. This file will be loaded from an URL.
How can I get the contains of this JSON file in an object in JavaScript?
This is for example my JSON file located at ../json/main.json:
{"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]}
and i want to use it in my table.js file like this:
for (var i in mainStore)
{
document.write('<tr class="columnHeaders">');
document.write('<td >'+ mainStore[i]['vehicle'] + '</td>');
document.write('<td >'+ mainStore[i]['description'] + '</td>');
document.write('</tr>');
}
Here's an example that doesn't require jQuery:
function loadJSON(path, success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
Call it as:
loadJSON('my-file.json',
function(data) { console.log(data); },
function(xhr) { console.error(xhr); }
);
XHR can be used to open files, but then you're basically making it hard on yourself because jQuery makes this a lot easier for you. $.getJSON() makes this so easy to do. I'd rather want to call a single line than trying to get a whole code block working, but that's up to you...
Why i dont want to use jQuery is because the person i am working for doesn't want it because he is afraid of the speed of the script.
If he can't properly profile native VS jQuery, he shouldn't even be programming native code.
Being afraid means he doesn't know what he is doing. If you plan to go for performance, you actually need to know how to see how to make certain pieces of code faster. If you are only just thinking that jQuery is slow, then you are walking into the wrong roads...
JSON has nothing to do with jQuery.
There is nothing wrong with the code you have now.
To store the variable mainStore, it is a variable in that json.
You should store that json to a variable:
var myJSON = {"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]};
var mainStore = myJSON.mainStore;
//.. rest of your code.
I understand that by "reading a json file" you mean making the request to the url that returns json content. If so, then can you explain why you don't want to use jQuery for this purpose? It has $.ajax function that is perfectly suitable for this and covers the browsers' differences.
If you want to read the file then you have to do it server-side, e.g. php and provide it somehow to the dom (there are different methods) so js can use it. Reading file from disk with js is not possible.
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(xhttp.responseText)
}
};
xhttp.open("GET", "./user.json");
xhttp.send();
}
Naming using the linux filename structure
You can store the responseText to a variable or whatever you want to do with it

Categories