...

View Full Version : to read variable from php for JS



zodehala
03-11-2010, 05:18 PM
this is my x.js file



function validatePhone(fld) {
var error = "";
var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');

if (fld.value == "") {
error = "You didn't enter a phone number.\n";
fld.style.background = 'Yellow';
} else if (isNaN(parseInt(stripped))) {
error = "The phone number contains illegal characters.\n";
fld.style.background = 'Yellow';
} else if (!(stripped.length == 10)) {
error = "i wanna read a variable from php )e.g : $a .\n";
fld.style.background = 'Yellow';
}
return error;
}


x.php is my php page like following



<?php
$a = aaaaaaaaaaaaa;
$b = bbbbbbbbbbbbbbbb;

Fou-Lu
03-11-2010, 05:31 PM
Nope, PHP and Javascript are not compatable together; one is a server side language while the other is client side. Using Javascript you can create an AJAX request to a PHP page for its new variable information.

Aside from that, if the data is not dynamic you can generate the javascript itself using php and include it in as if it were javascript:
CustomJS.php


<?php

header("Content-type: text/javascript");

$a = aaaaaaaaaaaaa;
$b = bbbbbbbbbbbbbbbb;
?>

function validatePhone(fld) {
var error = "";
var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');

if (fld.value == "") {
error = "You didn't enter a phone number.\n";
fld.style.background = 'Yellow';
} else if (isNaN(parseInt(stripped))) {
error = "The phone number contains illegal characters.\n";
fld.style.background = 'Yellow';
} else if (!(stripped.length == 10)) {
error = <?php echo $a . PHP_EOL;?>
fld.style.background = 'Yellow';
}
return error;
}




<head>
<script type="text/javascript" src="path/to/CustomJS.php"></script>

zodehala
03-12-2010, 09:18 AM
i tried to do it like you said but it did not run correctly

could you do it please instead of me . (it is in attachment)

Goldfish
03-12-2010, 09:43 AM
$a = aaaaa; cannot work, has to be either

$a = 12345;
or
$a = "aaaaa";

I wouldn´t echo '' the entire page, better use print <<<END



<?php
$a = 12345;
header("Content-type: text/javascript");

print <<<END
function validatePhone(fld) {
var error = "";
var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');

if (fld.value == "") {
error = "You didn't enter a phone number.\n";
fld.style.background = 'Yellow';
} else if (isNaN(parseInt(stripped))) {
error = "The phone number contains illegal characters.\n";
fld.style.background = 'Yellow';
} else if (!(stripped.length == 10)) {
error = "$a .\n";
fld.style.background = 'Yellow';
}
return error;
}
END;
?>


Make sure the line containing END; has no spaces or anything else in that line.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum