jQuery don't work inside PHP echo - php

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.

Related

making multiple divs with a link opening php pages

I have the following script. It's making divs with the username on it, works fine until the href part, the php page opens with user=$user (the variable doesn't take it's value)
For example $user='george' in the div id and inside getElementById, but in href user=$user? why?
Thanks in advance,
<script>
$(document).ready(function(){
for(i = 0; i < 1; i++) {
$('body').append('<div id="div'+'<?php echo $user; ?>'+'"/>'); //$user='george'
document.getElementById('div'+'<?php echo $user; ?>'+'').innerHTML=
'<?php echo $user; //$user='george'
echo '<a href="account_show_to_members.php?user=$user"> //$user=$user WRONG
Visit!</a>'; ?> ';
}
});
</script>
The problem is that php wont process inline variables in a string with single quotes, nor escaped characters like \n. The first place you should start is changing this:
echo '<a href="account_show_to_members.php?user=$user"> //$user=$user WRONG
Visit!</a>';
to this:
echo "<a href='account_show_to_members.php?user=$user'>Visit!</a>";
definitely look into some formatting standards though, this code is kind of a mess.
EDIT: just for the sake of avoiding confusion, here's how it should look altogether:
<script>
$(document).ready(function(){
for(i = 0; i < 1; i++) {
$('body').append('<div id="div<?php echo $user; ?>"/>');
document.getElementById('div<?php echo $user; ?>').innerHTML = '<?php echo $user." Visit!"; ?>';
}
});
</script>
This can probably be written directly to the dom too, without passing it through javascript. Saves a lot of overhead and complication. Not trying to be a jerk, just giving friendly advice.

How to pass variable from PHP to JS, perform math on the variable then output to an on page element [duplicate]

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>");.

How can I use input Box ID from PHP to JavaScript?

My JavaScript function works fine, but I have problems getting different ids from the PHP input box.
JavaScript
window.onload = function()
{
new JsDatePick({
useMode:2,
target:"inputField1", //HERE I WOULD LIKE TO PASS DIFFERENT ID ex. "inputField1"+ "i"
dateFormat:"%Y-%M-%d",
yearsRange:[1978,2120],
limitToToday:false,
cellColorScheme:"beige",
imgPath:"main/img/",
weekStartDay:1
});
My PHP input box for loop
<div class = "start_date" >
<strong><label for="start_date">Start Date</label></strong>
<br/><br/>
<?php
for($k=1;$k<=$textboxindex;$k++)
{
echo "<input type=\"text\" class='textboxsize' id= \"inputField1\" name=\"start_date[]\" value=\"$start_date\" />";
echo "<br/>";
}
?>
</div>
It works fine, but I would like to have different ID names to use in the JavaScript function. Any ideas?
This doesn't work...
echo "<input type=\"text\" class='textboxsize' id= \"inputField+$k\" name=\"start_date[]\" value=\"$start_date\" />";
Any help will be appreciated.
It's most likely with JsDatePick widget. Its target parameter takes a single ID of an element, therefore you'd have to wrap the JS code in a loop and initiate a separate instance of the widget for each field ID.
Assuming your input field indexing starts with 1:
window.onload = function()
{
var i = <?=$totalNumberOfInputs;?>
for(j=1;j<=i;j++) {
new JsDatePick({
useMode:2,
target:"inputField" + j, //HERE I WOULD LIKE TO PASS DIFFERENT ID ex. "inputField1" + j
dateFormat:"%Y-%M-%d",
yearsRange:[1978,2120],
limitToToday:false,
cellColorScheme:"beige",
imgPath:"main/img/",
weekStartDay:1
});
}
}
You don't need to put the + sign to concatenate strings within double quotes (it's dot, by the way).
Change:
id= \"inputField+$k\" name=...
To:
id=\"inputfield$k\" name=...
What is screwing it up is the "+" sign. PHP uses "." to concatenate strings. ECHO out $k properly and you shouldn't have any trouble
//this is doesn't work
echo "<input type=\"text\" class='textboxsize' id= \"inputField$k\" name=\"start_date[]\" value=\"$start_date\" />";
just remove that + sign.

passing PHP string to JavaScript: unterminated string literal

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.

Inserting a string inside of a javascript defined in PHP

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.

Categories