I just found myself in an odd position trying to put a string inside of javascript, that is defined in a php. The code I'm going to post isn't that actual code, but its the situation I'm in.
$script = "
var someVar = \"<input type='text' onchange='callScript('problem here') />' \";
";
so as you see, I'm setting a javascript variable that has html elements in it. the html element has an onchange event that is set to call a function that takes a string as a parameter. How would i insert that parameter?
I think if you call addslashes() on the string before inserting it into the variable, you should be fine as to escaping any possible unsafe characters, so:
$script = "var someVar = \"<input type='text' onchange='callScript(\\\"".addslashes($problem_here)."\\\") />' \";
Use String.fromCharCode:
$script = "
var someVar = \"<input type='text' onchange='callScript(\" + String.fromCharCode(34) + \"problem here\" + String.fromCharCode(34) + \") />' \";
";
Generated JavaScript would be:
var someVar = "<input type='text' onchange='callScript(" + String.fromCharCode(34) + "problem here" + String.fromCharCode(34) + ") />' \";
which evaluates to someVar being the string
<input type='text' onchange='callScript("problem here") />'
Try
$script = "
var someVar = \"<input type='text' onchange='callScript(\"problem here\")' />\" ";
Ideally your JavaScript will be inside a view file, so you won't print it out with PHP, more the other way around:
var jsVar = <?php echo json _encode($phpstring); ?>;
Or the shorter:
var jsVar = <?=json_encode($phpstring)?>;
Json encode will make sure the string is printed in a way that it will be read properly by JS.
http://php.net/manual/en/function.json-encode.php
In general, stay away from addslashes. Do what Robin Winslow said (I'm new here so I guess I can't reply directly) and use json_encode.
However, you'd still need to html-escape your that string in JS. Look into something like jQuery's templating system if you're generating HTML with JS.
Related
Value of $qty is in my database. I've read few similar questions and I already added $(document).ready but it's still not working.
echo "<div class='sp-quantity'>
<div class='sp-minus fff'><a class='ddd' href='#' data-multi='-1'>-</a></div>
<div class='col-xs-3 sp-input'>
<input type='text' class='quntity-input form-control qty' pid='$bookid' id='qty-$bookid' value='$qty'/>
</div>
<div class='sp-plus fff'><a class='ddd' href='#' data-multi='1'>+</a></div>
</div>";
echo "<script>";
echo "$(document).ready(function(){";
echo "$('.ddd').on('click', function() {";
echo "var $button = $(this);";
echo "var $input = $button.closest('.sp-quantity').find('input.quntity-input');";
echo "$input.val(function(i, value) {";
echo "return +value + (1 * +$button.data('multi'));";
echo "});";
echo "});";
echo "});";
echo "</script>";
You're getting your PHP & Javascript variable syntax confused. PHP uses $ as the start of every variable name. Javascript doesn't, plus jquery uses $ in a special way. On top of that, PHP does automatic string substitution of anything starting with a $ that can be a valid variable name as long as the string uses " instead of '. So the result of your code is:
<script>
$(document).ready(function(){
$('.ddd').on('click', function() {
var $button = $(this);
var $input = $button.closest('.sp-quantity').find('input.quntity-input');
$input.val(function(i, value) {
return +value + (1 * +$button.data('multi'));
});
});
});
</script>
$button and $input will be substituted with the contents of the PHP variables of those names. I suspect that's not what you want - though I have done things like that at times myself. What I think you want is:
<script>
$(document).ready(function(){
$('.ddd').on('click', function() {
var button = $(this);
var input = button.closest('.sp-quantity').find('input.quntity-input');
input.val(function(i, value) {
return +value + (1 * + button.data('multi'));
});
});
});
</script>
Two other suggestions:
1 - If you have absolutely no PHP values within a bunch of Javascript (or plain HTML) echo lines, you can exit out of PHP code mode by using ?> and not use echo and avoid any issues of string substitution.
2 - Personally, I prefer using {$string} for my variables inside strings as it makes the substitution more obvious and sometimes less ambiguous.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to access PHP variables from within JavaScript?
I am trying to pass a variable from mySQL to PHP then to JavaScript to perform some math on it then have the result displayed on page in a specific area (in a <p> element with a specific ID assigned to it). Is this possible or is there an easier solution?
Thanks!
I already know how to get the variable from MySQL to PHP just having trouble on what to do after that.
Here is my updated code after reading responses. Still not working but I am sure I'm doing something wrong!
<p id="p_id"><?php echo $price; ?></p>
<input type="radio" group="radio_group" value="Reduce 10%" onclick="radio_click();" />
<script type="text/javascript">
var price = <?php echo $price; ?>;
function radio_click() {
var target = document.GetElementById('p_id');
var final_number; // this will be variable your store the final number in
final_number = price * .9;
target.innerHTML = final_number;
}
</script>
In short, you have to pass the variable to the <script> tag as a string in a JavaScript friendly format (quotes and stuff).
<?php
$variable = 5;
$javaScriptAccessible = '
<script type="text/javascript">
var javaScriptAccessible = "'. $variable . '";
</script>
';
echo $javaScriptAccesible;
Also, you could JSON it:
<?php
$variable = 5;
$javaScriptAccessible = '
<script type="text/javascript">
var javaScriptAccessible = '. json_encode($variable) .';
</script>
';
echo $javaScriptAccessible;
With JSON, the quotes would be appended automatically.
Here you can see both in action: http://codepad.viper-7.com/Jyfw31
Update:
Here are more refined and, I think, better to understand examples: http://codepad.viper-7.com/1cloyB
Only thing you have to do, is use it on your radio buttons / elements.
I'd strongly suggest going with JSON, because it actually stands for JavaScript Object Notation, it has libraries in, probably, every single programming language on planet, and is specifically designed to pass JS data from one environment to other.
http://php.net/manual/en/function.json-encode.php here you can see multiple options you're able to pass in order to render it differently.
Just output the variable from PHP into a <script> item. Then set the innerHTML property of your <p> based on your calculation. You can put this into a function and call it from your radio button's onclick.
<p id="p_id"><!-- Your value will be inserted here --></p>
<input type="radio" group="radio_group" value="some_value" onclick="radio_click();" />
<script type="text/javascript">
var your_number = <?php echo $php_number; ?>;
function radio_click() {
var target = document.GetElementById('p_id');
var final_number; // this will be variable your store the final number in
// do your math here using your_number variable
target.innerHTML = final_number;
}
</script>
To pass the data from PHP to JavaScript, just echo it.
For example, say you want to display the data in a message box:
$data="something";
echo "<script>";
// Do the maths
echo 'var = ' . $data . ' + 1';
echo 'document.write("<p id=\"someID\">" + var + "</p>");' // PHP code writing Javascript code to write HTML code. Wow.
echo "</script>";
If you want to display the data on click of a radio button:
<input type="radio" onClick="someFunction();">
<?php
echo "<script>function someFunction() {";
// Do the maths
echo 'var = ' . $data . ' + 1';
echo 'document.write("<p id=\"someID\">" + var + "</p>");' // PHP code writing Javascript code to write HTML code. Wow.
echo "}</script>";
?>
*Edit: If the <p> tag already exists, use document.GetElementById(\"someID\").innerHTML = var; instead of document.write("<p id=\"someID\">" + var + "</p>");.
i am assigning PHP var to my javascript var and sending to PHP file through
ajax-jQuery, but my php variable contains newline chars which
i have replaced with <br>
e.g. $values1 = 'abc<br>pqr<br>xyz'; $values2 = 'xyz<br>lmn';
javascript - var data = 'val1=<?php echo $values; ?>&val2=<?php echo $values2; ?>';
and then ajax script to post data to PHP file
but when i print this data on console it is giving me error- SyntaxError: unterminated string literal.
Can anyone help ?
Your JS code:
var data = 'val1=<?php echo $values1; ?>&val2=<?php echo $values2; ?>';
Will give Javascript syntax error if one or more of your PHP variables $values1 OR $values2 contain single quote ' in them.
Make sure your PHP variable don't contain single quotes in them by replacing all single quotes to something else otherwise use double quotes " to create JS var like this:
var data = "val1=<?php echo $values1; ?>&val2=<?php echo $values2; ?>";
Provided PHP variables don't contain double quotes.
First of all, you have a typo, that might cause an error:
// --------------------------------v
var data = 'val1=<?php echo $values1; ?>&val2=<?php echo $values2; ?>';
Then, I suggest you to use object as data parameter for Ajax request:
var data = {
val1: '<?php echo $values1; ?>',
val2: '<?php echo $values2; ?>'
};
Also it is better to escape single quotes ' in both $values1 and $values2 variables.
Try using <br /> instead of <br>. Just guessing here, no testing.
I am sending a form with a notes field to an Oracle database and then displaying the notes. New notes can be added, and they will be appended to the previous note.
The problem I have is with the newline that I am inserting at the beginning of each notes update. I am sending notes updates to the database with a javascript in this manner: oldNote + "\n" + date + " " + username + ": " + newNote;.
This is the php part:
echo "<input class='button' type='button' id='Save' name='saveInteraction' onclick=\"saveInteractionInfo('$oldNote', '$date', '$username', '$interactionId', '$seqNum');\" value='Update'/>";
This is the entire javascript function:
function saveInteractionInfo(oldNote, date, username, interactionId, seqNum) {
var formData = {};
formData['interactionId'] = interactionId;
formData['seqNum'] = seqNum;
formData['notes'] = oldNote + "\n" + date + " " + username + ": " + document.all.notes.value;
trxId = readCookie("transactionId");
if(trxId)
formData["transactionId"] = trxId;
var respFunc = function(par1,par2,par3,par4) { postUpdateInteractionNotesResponseHandler(par1,par2,par3,par4); };
var errorFunc = function(reqId) { return showErrorCaseHandler(reqId); };
ajaxPostRequest("Interactions.php",formData,"Update Interaction Notes.","subExtra",respFunc,errorFunc);
}
Updating the notes works at it should, but when trying to update it for the second time I get an error in Firebug: unterminated string literal: saveInteractionInfo('Test, where saveInteractionInfo is the function I am passing the notes to and 'Test' is the form value. So the error occurs when the newline is passed to the function.
Any suggestions how I could get this working?
UPDATE So the problem is that the $oldNote has line breaks (\n) in it, which stops it from passing the data to the javascript function.
The tag now:
<input class='button' type='button' id='Save' name='saveInteraction' onclick="saveInteractionInfo('fdsfsfsf
dfdfdf
gdfgdg', '13/09/2011 16:11:13', 'blaha01', '7038245', '2');" value='Update'/>
The tag as it should be:
<input class='button' type='button' id='Save' name='saveInteraction' onclick="saveInteractionInfo('fdsfsfsfdfdfdfgdfgdg', '13/09/2011 16:11:13', 'blaha01', '7038245', '2');" value='Update'/>
Any other suggestions?
Replace the newlines by \\n using an RE, in PHP:
$oldNote = preg_replace('/\n/g', "\\n", $oldNote);
EDIT
Did you already handle characters such as '>' and '&'? If not, also use $oldNote = htmlentities($oldNote);. Otherwise, a " will break your code.
Maybe one or more of your PHP variables ($oldNote eg) has a single quote in it. When you write out the javascript you get:
onclick=\"saveInteractionInfo('Test''
Which would cause the JS to be invalid.
Suggest you change the onclick to take the single quote and wrap the php vars in \":
onclick='saveInteractionInfo(\"$oldNote\", ...
The solution was similar to the one posted by Rob W:
$oldNote = str_replace("\r\n", "\\n", $oldNote);
Using this
`$(function(){$(".signaler").click(function(){var element=$(this);var I = element.attr("id");var page = $('#page').attr('value');var info = "id="+I+"& page="+ page;$("#signaler"+I).hide();$("#load"+I).html('<img class="think" src="load.gif" >');$.ajax({type:"POST",url:"signaler.php",data:info,success:function(){$("#load"+I).empty();$("#ok"+I).fadeIn(200).show();}});return false;});});`
but have a form with hidden inputs only so i can echo current user info into it, was wondering if I could put it straight into jquery? Working fine though.
With a form you would use the following
var page=$('#page').attr('value');
I would like to set the id with php echoing user name/id..
Something like var id=$('<?php echo $user/$id... ?>');
If someone could point out the right jquery syntax, would be very greatful!
var id = $(<?= $_POST["whatever_it_was"] ?>)
pretty much what you used as an example...
<?php echo $user . '/' . $id ?>
As long as the file in question is being parsed as php by the server that is...
Firstly you should get the value of a form input using the val() method:
$('input#id').val();
Then on the PHP side if you POST to the page using AJAX then do:
'var id=$('<?php echo $_POST['user'] . '/' . $_POST['id'] ?>')';
What you have is essentially a string you wish to use for somewhere in you jQuery. Well in that case what you have is essentially correct. If in your PHP file you do (notice the quotation marks:
var id = "<?php echo $yourId ?>";
You can then use that variable (which holds your PHP string) normally. The following would for example select the element with the id in the variable id:
$('#' + id)