Gündoğdu Yakıcı Gündoğdu Yakıcı - 1 year ago 128
Javascript Question

How to write php code inside javascript?

My problem How to write php code inside javascript? How Can I do this ?
Thanks for your answers.

I want to write PHP code;

<?php if($this->session->userdata('kullaniciadi') == "") {echo "tiklama";} ?>

My JavaScript Codes;

new DC.Button({styles:"right_button tiklama <--- HERE",text:"Right",onClick:function(){self.onRightButtonClick();

Answer Source

PHP is a server-side language that executes on the server before the page even loads and JavaScript is a client-side language that executes on the browser. Hence, there's no way to write PHP in JavaScript, because the don't serve the same purpose.

If you want to contact a PHP page via JavaScript you'd better use an AJAX request.

Example use of an AJAX request:

    xhttp = new XMLHttpRequest,

xhttp.onreadystatechange = function() {
    if (yhttp.readyState === 4 && yhttp.status === 200) {
        response = xhttp.responseText // This variable contains the response from PHP
xhttp.open("POST", "YourPhpFile.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("number=" + number);

In YourPhpFile.php:

In this file, do the calculations you want to do and echo something that will identify if the operation succeeded or failed. Whatever you put after echo will be passed on to JavaScript:

echo "Success!"; // This string will be passed on to JavaScript

Then in JavaScript, after response = xhttp.responseText make a check and execute the appropriate code for your case.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download