/    Sign up×
Community /Pin to ProfileBookmark

simple way to call php function from javascript

Hello, I understand js is on client side and php is on server side. I am looking for a simple solution to call a php function in javascript
without going throught the fuzz of Ajax, post…
I got a code like this from SO:

[CODE]
<script>
function phpadd() {
var phpadd= <?php add(1,2);?> //call the php add function
alert(phpadd) // result in undefined
}
</script>

<?php
function add($a,$b){
$c=$a+$b;
return $c;
}
?>
<button onclick=’phpadd()’>add</button>

[/CODE]

The poster claims it works but it doesn’t for me. And I don’t understand how it would possibly work. Can someone point it out either ways? Thanks.

to post a comment
JavaScript

18 Comments(s)

Copy linkTweet thisAlerts:
@rootSep 25.2017 — Your order is wrong.

You can't use PHP functions until you have had them parse, so a change like [code=php]<?php
function add($a,$b){
$c=$a+$b;
return $c;
}
?>
<script>
function phpadd() {
var phpadd = <?php add(1,2);?> //call the php add function
alert(phpadd);
</script>

<button onclick='phpadd()'>add</button>[/code]
Copy linkTweet thisAlerts:
@rich1812authorSep 25.2017 — Thanks for the reply.

So it is possible to do this without Ajax?

I tried your code exactly the way it is, the alert box never comes up tho. ?
Copy linkTweet thisAlerts:
@SempervivumSep 25.2017 — There is the closing "}" missing when defining the function phpadd().
Copy linkTweet thisAlerts:
@rich1812authorSep 25.2017 — Ah, I also found out that this line

var phpadd = <?php add(1,2);?> //call the php add function

should be

var phpadd = <?php echo add(1,2); ?> // missing echo ?

Thanks for your help.
Copy linkTweet thisAlerts:
@ScrapersNbotsJun 21.2018 — Your ALL wrong. I had been pulling my hair out over this and then figured it out. You forgot the double quotes "

Its not

var phpadd= <?php echo add(1,2);?>; //call the php add function

its ...

<script>

function phpadd() {

var phpadd= "<?php echo add(1,2);?>"; //call the php add function

alert(phpadd) // result in undefined

}

</script>
Copy linkTweet thisAlerts:
@rootJun 21.2018 — Sorry but... Double quotes or not, makes no difference, when you &lt;?php echo add(1,2);?&gt; to the variable that will be made in JavaScript, if the return is a number then it will be a real number in javascript but in your case, you made it a string.

As you were not clear in your original post, showing a mix of JavaScript and PHP, it wasn't clear if you were understanding things and when you threw Ajax in to the mix, it was very clear that you were not understanding the technology one bit.

So when you want a decisive answer, it is best to always make it clear what it is the function is really meant to do.

So in the case of your example to which I posted, here is the code you would need &lt;?php
function add($a,$b){
$c=$a+$b;
return $c;
}
?&gt;
&lt;script&gt;
function phpadd() {
var padd = &lt;?php echo add(1,2);?&gt;; // call function to insert value
alert(padd);
&lt;/script&gt;

&lt;button onclick='phpadd()'&gt;add&lt;/button&gt;


AND a golden rule of programming is you NEVER call a variable the came name as the function you are using OR use reserved words or key words that the language you program in uses.
Copy linkTweet thisAlerts:
@wbportJun 21.2018 — NEVER call a variable the [b]s[/b]ame name as the function you are using
Copy linkTweet thisAlerts:
@ckurirNov 26.2018 — What if I like to replace the constants in the function call with variables?

Like

var x=3;

var y=5;

and do a call like <?php echo add(x,y);?>;

Is there a simple work around for this?
Copy linkTweet thisAlerts:
@rootNov 27.2018 — @ckurir#1598291 Please don't hijack others threads.

If you have a question about the thread, start your own thread but post a URL to the post you refer to on this site.
Copy linkTweet thisAlerts:
@NogDogNov 27.2018 — @ckurir#1598291 Yest there's a simple solution: use a JavaScript function instead of a PHP function. PHP runs on the server before any JavaScript ever even thinks about running on the browser.
Copy linkTweet thisAlerts:
@PeterPan_321Nov 29.2018 — @ckurir#1598291 It is possible to put multiple java script variables into an HTML form who's SUBMIT button calls a PHP function. I think its easier than trying to cajole a way to replace PHP variables directly from you Javascript code. If it IS possible, I think the code would look pretty ugly. In fact I find that the more I want to seamlessly combine javascript and PHP variables, the more convoluted the code becomes, and quite often I hit a roadblock. So either generate 'hidden' values in a form, or another possibility is to use cookies to hold variables. Cookies are available to both javascript and PHP. I often use cookies, for example, to ensure that at the end of an email form which POSTs to PHP code, the browser is returned to the last page they were visiting.

BUT... accessing cookies in PHP is at least as tricky as accessing form variables from a PHP $_POST array, so you'll have to research that method on your own a bit if it sounds workable, and definitely start a new thread for anything related to that subject.
Copy linkTweet thisAlerts:
@NogDogNov 29.2018 — If you _really_ need to access something on the server side while remaining in the current page, then AJAX is the way to go, whether you like it or not; and there are enough basic JavaScript AJAX libraries/scripts out there you can use to make it pretty simple. (I.e.: you don't necessarily need to load all of JQuery. ? )
Copy linkTweet thisAlerts:
@rootNov 30.2018 — You don't need JQuery at all.
Copy linkTweet thisAlerts:
@sevenTopoJan 26.2019 — what if i want to passt a javascript parametre to my php function like this ?


<?php

function add($a,$b){

$c=$a+$b;

return $c;

}

?>

<script>

function phpadd(e,f) {

var padd = <?php echo add(e,f);?>; // call function to insert value

alert(padd);

</script>

<button onclick='phpadd()'>add</button>
Copy linkTweet thisAlerts:
@rootJan 27.2019 — WHY??? on earth would you be passing something back to the server to put through a function?

Anyway, you can't just write PHP and JavaScript and HTML like that and expect it to work, you are basically not understanding the technologies and how they work and work together...

Start with HTML, then add CSS, then learn JavaScript and the AJAX part of JavaScript and then PHP and then all the other stuff like JQuery.
Copy linkTweet thisAlerts:
@esperance20009Feb 12.2019 — انواع پروفیل ام دی اف عبارت اند از : اسکوتی , تاشو PVC , دیوارپوش , قرنیز 6.7 سانت , قرنیز 8.7 سانت , قرنیز و آب بند , لب پله , میانه , میت , نبشی ثابت , پروفیل , تاشو , اسکوتی , پاراوان , پروفیل , ستون , لبه پله , لبه , گرده و …

https://ageshop.ir/product-category/mdf-profil/
Copy linkTweet thisAlerts:
@dangquanghaiSep 01.2019 — It works if I write all in the same file php like this

test.php ------------------------------------------

<?php

function add($a,$b){

$c=$a+$b;

return $c;

}

?>

<!DOCTYPE html>

<html>

<head lang="vi">

<meta charset="UTF-8"/>

<title> php basic </title>

</head>

<body>

<button onclick='phpadd()'>add</button>

<script type="text/javascript" >

function phpadd()

{

var padd = <?php echo add(1,2);?>; // call function to insert value

alert(padd);

}

</script>

</body>

</html>

------------------------------------------
But it did not work if i move JavaScript in to separated file like this

test.php -------------------------------------

<?php

function add($a,$b){

$c=$a+$b;

return $c;

}

?>

<!DOCTYPE html>

<html>

<head lang="vi">

<meta charset="UTF-8"/>

<title> php basic </title>

</head>

<body>

<button onclick='phpadd()'>add</button>

<script type="text/javascript" src="js/MyJS/test.js"></script>

</body>

</html>

test.js------------------------------------

function phpadd()

{

var padd = <?php echo add(1,2);?>; // the error appear here

alert(padd);

}
----------------------------------


Please help me!
Copy linkTweet thisAlerts:
@meowucmeJan 24.2020 — @dangquanghai#1608201 If you look at the page source (Ctrl + U on chrome and I think any other browser) on the file that has the php and JavaScript, you will see that it says:

``<i>
</i>function phpadd()
{
var padd = 3; // call function to insert value
alert(padd)
}<i>
</i>
``


That is because php is run on the server side, before JavaScript is loaded, meaning the php function is only called once when the page loads and not each time the JavaScript function is called. That is why functions that accept parameters cannot return the result of a php function passing the parameters into the php function. I hope this helped you understand why your code is not working.
×

Success!

Help @rich1812 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...