example (this is not working)
location.href = 'freecreate?fname=+fname+"&Mnumber="+Mnumber+"&sitename="+sitename';
Add double quotes(") after fname= , Use this:
location.href = "freecreate?fname="+fname+"&Mnumber="+Mnumber+"&sitename="+sitename;
If you are working with php variables just Declare them,
assign values and append them
using . operator
See the example below:
<?php
$fname="bhansa";
$Mnumber ="number";
$sitename ="stack";
echo "<script>window.location = 'freecreate?fname=".$fname."+&Mnumber=".$Mnumber."+&sitename=".$sitename."'</script>";
?>
Use #Dhara Parmar's method if you want to use in javascript.
Related
I am still new, so please forgive me if this question is too trivial or the issue has already been discussed. I didnt find anything specific, which led me to open a new question. That said, here is how it goes:
Im passing values from my database into data-attributes in order to use them in javascript to alter the width of certain elements (i.e. graphs). The element that should be altered according to the retrieved value is a p-Tag (together with others it sits inside a foreach):
<span class="fdpg-nut-vline"><p class="fdpg-nut-graph" id="graph" data-somedat="<?php echo "'" . $value['Nu_Val'] . "%'" ?>"></p></span>
The value of the data-attribute with the name "somedat" I want to use in js, like so:
var somevar = document.getElementById('graph').getAttribute("data-somedat");
document.getElementById("graph").style.width = somevar;
What I did?
I checked whether the format of the value is right. I therefore set a 'static' variable var somevartest = '20%'; and used it in the code above. It worked and the graph changed accordingly.
I checked if the value is passed into the data-attribute: (1) in the sourcode (its there!) and afterwards included an alert which shows me the value in the right format aswell (i.e. 'x%').
What is it that Im not getting? How can I solve my problem?
The proper way to pass data from PHP to JavaScript is using a JSON string.
PHP:
<?php
$arr = get_from_database_as_array(...);
// at end of page before your scripts:
echo "<script>";
echo "var data = " . json_encode($arr, true) . ";";
echo "</script>";
HTML:
<script>
console.log(data);
document.getElementById("elem1").style.width = data["elem1"] + "px";
document.getElementById("elem2").style.width = data["elem2"] + "px";
// and so on.
</script>
So basically, I am copying content of one div to other like this
$("#button").click(function() {
var a = $("#div1").html()
$("#div2").html(a);
I want the variable 'a' to change all the occurrence of a character/string and copy it to div2.
$("#button").click(function() {
var a = $("#div1").html().replace("$money","$cash");
$("#div2").html(a);
So, basically, I want the replace the occurrence of '$money' with '$cash' and store it inside test1. The above code copies the exact content but does not replace '$money' with '$cash'.
What am I doing wrong?
Escape back to PHP to substitute variables into the Javascript.
$("#button").click(function() {
var a = $("#div1").html().replace(/<?php echo preg_quote($money); ?>/g, <?php echo json_encode($cash); ?>);
$("#div2").html(a);
});
You need to use a regexp with the global modifier to perform multiple replacements.
repeating response as #Barmar, but removing the php part to simplify
$("#button").click(function() {
var a = $("#div1").html().replace(/money/g,"cash");
$("#div2").html(a);
});
I have the following PHP code. It creates multiple variables using $a; for example: $numtoken1.
$sql ="SELECT token, dispositivo FROM dispositivos WHERE idcliente=1";
mysql_select_db('localiza');
$retval = mysql_query( $sql, $conn );
$num_rows = mysql_num_rows($retval);
while($row = mysql_fetch_array($retval, MYSQL_BOTH))
{
$numtoken['$a']=$row['token'];
$numdispositivo['$a']=$row['dispositivo'];
$a=$a++;
}
Using JavaScript, I want to call all the PHP variables using that code, but it only get the last $a number.
My question is: In a JavaScript loop, how can I dynamically insert the value for $a? Because in the above PHP, I have multiple values for $a.
var accessToken = "<?= $numtoken['$a']; ?>"a;
var deviceID = "<?= $numdispositivo['$a']; ?>";
I suggest JSON:
var accesstoken = JSON.parse("<?= json_encode($numtoken); ?>");
var deviceID = JSON.parse("<?= json_encode($numdispositivo); ?>");
So the first thing I noticed when looking at this is that you are wrapping $a in single quotes (') instead of double quotes (") this means that instead of evaluating $a the key in the array will be the string "$a", so you'll be overwriting the value in each iteration of the while loop. See - http://php.net/manual/en/language.types.string.php#language.types.string.parsing for more info.
That being said the actual answer to your question varies, but the simplest method might be to use the json_encode function to convert your arrays into json objects.
var accessTokenArr = <?php print json_encode($numtoken); ?>
var deviceIdArr = <?php print json_encode($numdispositivo); ?>
Then you can iterate over the values in those arrays and do whatever you want to with the values. Fair warning - you may need to tweak that code a little as I haven't tested it to make sure it plays nicely.
I have a javascript function in which am trying to send some data to another php script. I have to send an array of values to the php script. I am trying to append : to each value in the javascript function so that I can use implode to get the array values in my php script. This is the javascript function I have.
$("#update-form").submit(function(e) {
$passdata = "";
<?php
for ($i=1; $i <= $total_columns - 1 ; $i++) {
printf('$passdata+=$("#slider%d").val().:;' . PHP_EOL, $i);
}
?>
if ($(this).is(':not([data-submit="true"])'))
{
$('form').append('<input type="hidden" name="foo" value="'+$passdata+'">');
$('form').data('submit', 'true').submit();
e.preventDefault();
return false;
}
})
I used printf('$passdata+=$("#slider%d").val().:;' . PHP_EOL, $i); However, I am not able to see the variable in php script. I also tried,
printf('$passdata+=$("#slider%d").val()+=:;' . PHP_EOL, $i);
How can I append : to the variable in my javascript function?
Look at what it generates in the client, is that valid JavaScript?
$passdata+=$("#slider1").val().:;
JavaScript does not do string concatenation that way.
$passdata+=$("#slider1").val() + ":";
If I were you, I would use an array and join()
$passdata.push($("#slider1").val());
and than make it a string
var myValue = $passdata.join(":");
Even better, do not use PHP to generate the JavaScript! Just add a class on the elements and use a single selector with map();
$(".myCommonClass").map( function(){ return this.value; }).get().join(":");
Or just post multiple form element names to the server and handle the multiple values on the server like forms always work.
Rather than hacking around this abomination, why not just do something like this:
Add a class to all of your sliders. Then:
$(".sliderClassNameHere").map(function(x) {return x.value;}).get().join(":");
Alternatively... just submit the sliders...?
Why not use json? In PHP you use json_encode(), put it in hidden input's value, and then in javascript you use function json_decode() on that value. That's what json is for.
i want to acheive this :
for (i = <?php echo $current_i ?> /*then I get augmented in javascript */;i<max;i++){
$('#anyid****')./* my actions goes here */
}
here i want to put the counter I of the javascript in the selector
how could i do that ???
Sorry i don't know PHP but i hope you wanted to do something like below
for (i = <?php echo $current_i ?> ;i<max;i++){
$('#div'+i)/*do the rest*/
}
the + is for concatenation, i hope it is same in PHP. Also you could cast i to string.
Just for OP's understanding
in line 2 $('#div'+i) i is a integer type and others $(#div) are of type string. For jquery needs a string selector to retrieve a matching dom node and for that i needs to also be casted/converted to a string variable so that it could concatenate/add/attach with the prefix string which is in this example #div. in c# you add 2 strings like this var result = "#div" + i.ToString(); and i did not know PHP equivalent for + in c#,hence a sorry at the start of post. Now do you understand?
for (i = <?php echo $current_i ?> /*then I get augmented in javascript */;i<max;i++){
$('#anyid' + i)./* my actions goes here */
}
you can just concatenate it to the string of your selector.
That's not very "jQuery-ish". Assuming the elements have IDs with a continuing part and are in order, you can give every element a common class and use slice [docs] and each [docs]:
$('.commonClass').slice(<?php echo $current_i ?>, max + 1).each(...
You could provide better solutions if you explain more about your problem. E.g. giving each element an increasing ID does not seem to be a deliberate solution.
P.S.: I wouldn't put the PHP variable there either, maybe assign the value to a JavaScript variable first.
it would be a lot cleaner if you split up the php and javascript like this.
js_var.php
<?php
$phpvars = array(
'max' => 12,
'fop' => 22
);
function phpvar($key = NULL){
global $phpvars;
return ($key)
? json_encode($phpvars[$key])
: json_encode($phpvars);
}
?>
usage
<?php include('phpvars.php');?>
<script type="text/javascript">
window.phpvars = <?=phpvar()?>;
var max = phpvars.max;
for (var i=0;i<max;i++){
console.log(i);
}
console.log(php);
</script>