set value of input with php variable - javascript

Im trying to do something really simple I know I should probably be using ajax but I'm just doing some quick tests.
so I have a display.php file with some variable and I want to display the PHP variable in the input text by using document.getElementbyID.value = myVariable
//PHP
<?php
$name = 'Patrick';
?>
//HTML
First Name: <input type="text" id = "fname" name="fname" value="" >
//JS
<script type="text/javascript">
var f = <?php echo($name); ?>;
document.getElementById("fname").value = f;`
</script>
I keep getting the error Uncaught ReferenceError: Patrick is not defined
Not really sure whats wrong with my code it looks pretty simple but it don't want to put the value "Patrick" in the input box.
Tried different ways of writing it with '' or using json_encode but didnt change anything still getting same error.

Uncaught ReferenceError: Patrick is not defined
That's because the resulting javascript is:
var f = Patrick;
Which means set f to the contents of the variable Patrick.
Since there is no variable defined that is named Patrick you'll get the uncaught reference error.
You need to put Patrick in quotes like so:
var f = "Patrick"; // <-- Note the "
Note, since you want to pass data from PHP to JavaScript, a better way would be to use JSON like this:
var f = <?php echo json_encode((string)$data); ?>;
This allows you to pass more complex types of data¹ AND you'll get proper escaped strings.
Proper escaped strings? If the user input is Test " (note the double quote) a primitive approach will break because the resulting javascript will be:
var f = "Test "";
This is not only a bug, but a security issue since user input could contain arbitrary javascript that would get executed.
¹ just remove the (string) cast.

Related

Javascript or jquery change fields value by name

I use these codes to change the value of a field. Only the first two lines run, I tried the rest of the code but it did not work and sometimes the message "Uncaught ReferenceError: $ is not defined" is displayed on the console.
document.getElementsByName('tmcp_textfield_6').value = Pak;
document.getElementById("tmcp_textfield_116202d52cbd078").value = Pak;
$("input[name='tmcp_textfield_6']").val(Pak);
document.getElementsByName("tmcp_textfield_6").value = 100;
document.getElementByname("tmcp_textfield_6").value = "100";
$("input[name='tmcp_textfield_6']").val(Pak);
Find the Working Script here, I think you should switch quotes, where double quotes use single, and where single quotes, use double.
var Pak = "Test"
$('input[name="tmcp_textfield_6"]').val(Pak)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="tmcp_textfield_6">
Be sure you've also included the jquery file to whatever page you need it to work on

Storing php value in javascript variable

I am trying to store php value in my javascript variable. But this code is giving me syntax error. Is the code correct ?
var b = <?php echo $tagValue;?>;
alert("B is " +b);
You have to make sure that your webserver interprets that file as a php file. then you have to adapt your code, because it looks like you could have an error in your js code in the end:
var b = "<?php echo $tagValue;?>";
alert("B is " +b);
(I have added quotes). Does not apply, if you are sure that $tagValue is only numeric.
In case you don't really know what kind of value your $tagValue is or you simply want to make sure you won't fail you should use json_encode($tagValue):
var b = <?php echo json_encode($tagValue);?>;
alert("B is " +b);
Please note that in case $tagValue is an array/object your js-alert won't be very usefull :)
Easiest way i've found to do it without worrying about character escaping or XSS is to convert the contents of the variable to JSON. All it takes is to echo json_encode($tagValue); instead of echo $tagValue;
make a function maybe can help u.
this is an example
// your php code
$tagValue = 'value';
getValue($tagValue);

assigning php return value to a javascript variable

I have a database form on a MySql table on which I have a javascript function to populate the options of a select tag. Those options are fetched from a table of clients who have a status of either "Active" or "Inactive", and the return values are of those clients where their status is active. In the event an order is loaded where the client status is inactive, I'm trying to add a handler for inactive clients. The form loads from a php script that left joins the client table to the main table, where clientId in the main table is equal to Id in the client table. So, I have the name and id of the client fetched outside of the function to populate the options list, regardless of their status.
There is one line that is causing me fits. I have searched this site and others and have found many solutions, but none have worked for me so far. This is the line:
var txt = <?php echo $row[`clients`.'name']; ?> ;
What is returned in Chrome and Firefox debuggers is, "Uncaught syntax error: Unexpected token <". The debugger shows: var txt = <br />
I've tried enclosing the php script in single quotes, double quotes, and without quotes, and still no luck. Any thoughts, anyone?
About an hour later--> I found a workaround. I tried all of your suggestions, but none worked in this instance. var_dump and json_encode confirmed what I knew already, that the returned data was valid. Regardless of any of the variations in syntax, they all returned the same error. What I did was to apply the same syntax as above, but in a hidden input:
<input type="text" id="cName" hidden value="<?php echo $row[`clients`.'name']?>" />
Then changed the javascript code to this:
var txt = document.getElementById('cName').value;
Everything else works perfectly. Of course, I still have lingering thoughts about the use of backticks, and would prefer that I had a better, and safer code. As I mentioned somewhere, I simply copied the sql syntax directly from phpMyAdmin. In this instance, if I substitute single quotes for the backticks, the input returns nothing. Well, thanks all. If anyone wants to contribute more, I'll be glad to hear about it.
That's illegal PHP syntax, and very dangerous syntax in general. Try doing a var_dump($row) to see exactly what's in that array. Probably you want something more like
var txt = <?php echo json_encode($row['clients.name']); ?>;
instead.
Note the use of json_encode(). This will ENSURE that whatever you're spitting out in the JS code block is actually syntactically valid javascript.
e.g. consider what'd happen if you ended up with
var txt = Miles O'Brien;
^^^^^--undefined variable;
^--- another undefined var
^--- start of a string
^^^^^^^---unterminated string.
with json_encode(), you end up with
var txt = "Miles O'Brien";
and everything's a-ok.
var txt = "<?php echo $row['clients']['name']; ?>";
var txt = <?php echo $row[`clients`.'name']; ?> ;
Consider how PHP parses this:
var txt = is to be output directly to the client.
Enter PHP mode.
echo the following expression.
Evaluate $row[`clients`.'name'].
First we need to determine the array index, which is the concatenation of `clients` and 'name'.
Backtick in PHP is the execution operator, identical to shell_exec(). So PHP attempts to execute the shell command clients, which probably fails because that isn't what you intended and it doesn't exist. Consequently, at this stage, PHP outputs an HTML error message, starting with a line break <br />.
Your client now has var txt = <br /> (you can verify this by inspecting the HTML source of the page returned to your browser), which it attempts to evaluate in its JavaScript context. This gives rise to the "unexpected token" error that you have witnessed.
As others have mentioned, you probably meant to do something like $row['clients']['name'] or $row['clients.name'] instead—but without seeing the rest of your PHP, it's impossible to be sure. Also, as #MarcB has observed, you need to be certain that the resulting output is valid JavaScript and may wish to use a function like json_encode() to suitably escape the value.
The error comes from the fact that your return value (a string in javascript) must be in quotes.
Single quotes will take whatever is between them literally, escapes (like \n ) will not be interpreted, with double quotes they will.
var txt = "<?php echo $row['clients']['name']; ?>";
is what you want
Change this
var txt = <?php echo $row['clients'.'name']; ?> ;
to this:
var txt = <?php echo $row['clients']['name']; ?> ;

Catching php mysql variable in javascript

Im wondering how to catch mysql row in javascript, i tried to do that this way:
var x = <?php
mysql_connect(Not important);
mysql_select_db(not important);
$zapytanie = "SELECT (times) FROM dane WHERE email='$email'";
$idzapytania = mysql_query($zapytanie);
$wiersz = mysql_fetch_row($idzapytania);
echo $wiersz[0];
mysql_close (notimportant);
?>;
alert(x);
But this is not working. Any solutions? Sorry if this questions seems to be lame but i not the best in php/js, but have few things to do.
You should enclose the output of PHP in single quotes if you want it to be treated as a string in javascript. Like this:
var x = '<?php
mysql_connect(Not important);
mysql_select_db(not important);
$zapytanie = "SELECT (times) FROM dane WHERE email=\'$email\'";
$idzapytania = mysql_query($zapytanie);
$wiersz = mysql_fetch_row($idzapytania);
echo $wiersz[0];
mysql_close (notimportant);
?>';
Or alternatively, replace echo $wiersz[0]; for echo "'". $wiersz[0] ."'";
Try this
<?php
mysql_connect(Not important);
mysql_select_db(not important);
$zapytanie = "SELECT (times) FROM dane WHERE email='$email'";
$idzapytania = mysql_query($zapytanie);
$wiersz = mysql_fetch_row($idzapytania);
$w=$wiersz[0];
mysql_close (notimportant);
?>;
<script>
var x =<?php echo $w ?>
alert(x);
</script>
If you want to pass an array from PHP to jquery/javascript, the best way would be using JSON. Pseudocode:
var x=JSON.parse(<?php echo json_encode($array); ?>);
<script type="text/javascript">
setVariables('<?php echo $tag_name ?>', '<?php echo $client_id ?>');
</script>
and then creating that function in your .js file to utilize those values and do what you need.
function setVariables(name, id){
var tag_name = name
var client_id = id
//Operations that need these values.
}
write bundles to javascript!
Personally whenever transferring initilisation data from PHP to the client I find it best to combine the data into an array, and use casting and json_encode (as per Helpful's answer) to make a final structure that is nice and easy to use on the JavaScript side. This saves echoing different variables all over the place, and will automatically handle any type and escape syntax that is required i.e. wrapping strings with quotes, or back-slashing internal quotes in strings.
<?php
$export = array();
mysql_connect(Not important);
mysql_select_db(not important);
$zapytanie = "SELECT (times) FROM dane WHERE email='$email'";
$idzapytania = mysql_query($zapytanie);
$wiersz = mysql_fetch_row($idzapytania);
mysql_close (notimportant);
$export['x'] = !empty($wiersz[0]) ? $wiersz[0] : 'default';
?>
var data = <?php echo json_encode((object) $export); ?>;
Obviously the above is a little overkill for just one small value, however, if there ever became more than one value — something that could quite easily happen after further coding — it would be very easy to extend:
$export['x'] = !empty($wiersz[0]) ? $wiersz[0] : 'default';
$export['something_else'] = 54321;
Then all you need do to access these values in JavaScript is:
data.x
data.something_else
why use an array and why cast to an object?
The reason why I use an associative Array on the PHP side is because I find writing to arrays cleaner in PHP than Objects — not a huge fan of the -> notation. Also instantiating an Array is easier and seemingly more native than an Object in many versions of PHP. I then cast to an object before writing to JavaScript because I find the opposite is true in JavaScript, it's easier and nicer to read when accessing objects rather than arrays. This is all personal taste however.
NOTE: When defining your keys in the $export array you should be wary to keep to standard variable naming conventions i.e. either use camelCase/interCaps or convert spaces to underscores. Whilst you can get away with using any characters, even spaces, it will mean accessing the data from the JavaScript side becomes more cumbersome.
another thing to bear in mind
When setting variables in JavaScript it's often seen as a bad thing to pollute the global namespace. This basically means writing variables at the top level of run-time, that attach to themselves to global Object (usually Window), so that they are accessible by every bit of JavaScript code that runs in that execution. It is seen as bad because unless you use a likely unique variable name, collisions with other code can occur i.e. if both bits of code rely on the same global variable.
If you just output your data var at the top of your script it will become part of the global namespace, and using something as bland as data would be a prime example of something to avoid. It may not matter at all for small projects that aren't going to be extended or worked on by multiple coders, but it is always a good idea to get into the habit of avoiding this.
You can of course just use a variable name that is more unique to your project e.g. myProjectData, or if you have an over-arching namespace that defines your project i.e. examples of which would be jQuery, JSON, console; you could attach it to that e.g. Project.data.
However, if you wanted a more general approach you can also do this by wrapping your JavaScript code in an anonymous function.
<?php
$export = array();
$export['random_value'] = 'Where\'s my monkey?';
?>
(function( data ){
/// data will only be available inside this function
/// or to other sub functions defined inside this function.
console.log(data.random_value);
})(<?php echo json_encode((object) $export); ?>);
With the above code you should end up with your JavaScript always having a nice bundle of values to access, properly escaped and formatted, that have come straight from PHP in an easy way, and that doesn't pollute the global namespace.
WARNING: Obviously it should be noted that if you use the above anonymous wrapper method and you call in any other script files within your page, they wont be able to access data unless you pass the object to that code in some way. This is why people often prefer to have an over-arching namespace object for their project i.e. MyProject.data. However you do not necessarily have to do this — due to the benefit of having all your values bundled up in a singular JavaScript object — because passing it to other code is as simple as sending one variable as a parameter to a function i.e. other.code(data)

js, make a json object a string - the easy way?

I have tried lots of different ways, and using many diffent PHP and JS functions to try to achieve this.
Hoe to i turn this json object ;
"lines" : ["text line 1<br/>","text line 2<br/>","text line 3<br/>","text line 4<br/>"]
Into this string, so that i can add to a HTMl div
text line 1<br/> text line 2<br/> text line 3<br/> text line 4<br/>
No, quotes, brackets or anything else.
In it's simplest form all i have is stringify;
lines = JSON.stringify(obj.lines)
but the above outputs, brackets, quotes, and commas
Sorry if this is a simple and silly question, but i h (finishing now (embarrassed!)) ave searched everywhere for a simple answers. Nothing stands out.
Check out Array.join:
var html = obj.lines.join("");
Example: http://jsfiddle.net/VXbs7/
You have a JSON string. You need to parse it into a data structure, then get the array of strings, and loop over them (outputting as you go).
If you're doing this from javascript, it's quite easy. JSON is native to javascript and can be interpreted as an object quite simply. It looks like you only have half your JSON object pasted in your question though. A whole JSON object is wrapped in [] or {} (unless it's just a string or number type, but then it's not an object).
Anyway, if you're in PHP - you can easily json_decode() this string and loop it like so:
<?php
$arr = json_decode($json_string, true); //true makes it an array instead of object
foreach ($arr['lines'] as $line)
{
echo $line;
}
If you're trying to accomplish it in javascript (in the browser), it's also quite easy (assuming your string is stored in a php variable, and that you're using jquery for dom manipulation)
<script type="text/javascript">
var obj = <?= $json_string; ?>,
mydiv = $('#mydiv);
for (key in obj['lines'])
{
var line = obj['lines'][key];
mydiv.append(line);
}
</script>
both of those should give you the output you're looking for

Categories