pass a variable to a JavaScript function [duplicate] - php

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I have a button in my php page :
<button id="myButton">Delete me</button>
and in that page I have a variable which I want to pass to a JavaScript function, and this is my JS code :
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {
//Here I'll use the variable
}
})
});
</script>
How can I do that ?

I think you might be wanting to put a variable through PHP on your button and pass it to your function using jQuery data. Check this out:
<button data-confirmed="<?php echo $confirmed; ?>" id="myButton">Delete me</button>
And in your js:
$(function() {
$('#myButton').on('click', function(e){
// get jquery object access to the button
var $thisButton = $(this);
// this gets that data directly from the HTML
var confirmed = $thisButton.data('confirmed');
if(confirmed) {
//Here I'll use the variable
}
})
});
Basically, you can access variables in javascript using this method if you are interpolating PHP vars directly on the page. If this isn't what you are looking for, please let me know in comments.

<button id="myButton">Delete me</button>
<input type="hidden" name="variable" id="variable" value=2>
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {=
alert(document.getElementById('variable').value);
//Here I'll use the variable
}
})
});

You can declare the variable outside the click event like so:
$(function() {
var confirmed = true;
$('#MyButton').confirmOn('click', function() {
if(confirmed) {
// do stuff
}
});
});

Assuming you're talking about passing php variables to Javascript, you can do this when writing to the page, ex:
<?php
$passThis = 'Passing'
?>
<script language="javascript" type="text/javascript">
var sStr = "My name is <?php echo $passThis ?>.";
document.write(sStr);
</script>
You could also get integer values, doing something like
$integerValue = 5;
var int = "<?php echo $integerValue; ?>";
int = parseInt(int);
By modifying this, you could use it to pass more types of variables, so assuming you have something like this:
<?php
$text = 'someText';
?>
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {
//Here I'll use the variable
}
})
});
</script>
you could do
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {
console.log("<?php echo $text ?>");
}
})
});
</script>
to make Javascript alert 'someText'.

Related

Passing sql string variable into javascript function

I am trying to pass a string from a query into a javascript function.
An integer will pass into the function but string will not.
echo "<a href='#' onclick='delete_game({$title});'
class='btn'>Delete</a>";
<script type='text/javascript'>
function delete_game(title){
var answer = confirm('Really?');
if(answer){
window.location = 'delete.php?id=' + title;
}
}
</script>
I expected the javascript function to be executed, but instead nothing happens.
Why don't you use ajax for this? As mentioned in comments mix PHP/JS isn't good.
In your HTML, you can do something like
I'm assuming that you are using Blade.
Delete Game
Then in your javascript, you do this using jQuery:
function deleteGame(title){
var answer = confirm('Really?');
if(answer){
$.ajax({
url : "your-php-file.php",
type : 'post',
data : {
title : title
}
})
.done(function(msg){
$("#result").html(msg);
})
.fail(function(error){
console.log(error);
});
}
}
In your PHP you process receiving the data from post $_POST
$title = $_POST['title'];
You can understand better the Ajax function of jQuery here.
A few things:
I would change window.location to window.location.href
Change your echo to:
echo "Delete";
Check if $title is set
var_dump($title);
If you'd like to make it a bit cleaner and are prepared to use jQuery:
Delete
<script type='text/javascript'>
$(document).on('click', '#delete', function () {
var title = $(this).data('title');
var answer = confirm('Really?');
if (answer){
window.location.href = 'delete.php?id=' + title;
}
});
</script>

Is it possible to insert php variables into your js code? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
passing variables from php to javascript
I'm dynamically generating a list. I want to make each row hover on mouseover and clickable to a link. I want the link to pass the id of the content of the row.
Basically:
foreach ($courses as $cid=>cinfo){
$univ = $cinfo['univ'];
$desc = $cinfo['desc'];
$size = $cinfo['size'];
$start = $cinfo['start'];
print "<div class='rc_desc' id='rc_desc$cid'>"."$desc<br/>"."<b>$univ</b><br/>".
"<span>Number of students</span>: $size<br/>".
"<span>Started at</span>: ".date('F d, Y',strtotime($start))."<br/>".
}
<script>
$(function ()
{
$('#rc_desc$cid').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc$cid').click(function ()
{
$(location).attr('href','student.php?$cid');
});
});
</script>
The issue is in the js/jquery. I want to be able to grab the $cid and pass it to the student.php page upon click. The php code above works but the js won't of course. I know the fundamental of client-side vs server-side languages. This question doesn't warrant a lecture. I know I cannot do this exactly, but it is what I want to happen ultimately. Any thoughts on how I can achieve this simply? Thanks in advance my friends!
Yes, if you include the <script> section in your PHP code, you can do something similar to the following:
<script>
var foo = <?php echo $foo; ?>;
</script>
In your case, you would be looking into the following code structure:
<script>
$(function () {
$('#rc_desc<?php echo $cid ?>').hover(function () {
$(this).toggleClass('.tr');
});
$('#rc_desc<?php echo $cid ?>').click(function () {
$(location).attr('href', 'student.php?<?php echo $cid ?>');
});
});
</script>
The reason why this is possible is because although the Javascript is run on the client-side, it's processed on the server-side first prior to being presented on the page. Thus, it'll replace all necessary instances of $cid with the one you have included.
Enjoy and good luck!
EDIT:
<script>
$(function () {
$('.rc_desc').hover(function () {
$(this).toggleClass('.tr ');
});
$('.rc_desc').click(function () {
$(location).attr('href', 'student.php?' + $(this).attr('id').split('rc_desc')[1]);
});
});
</script>
You can do it like this :
$(location).attr('href','<?php echo $cid ?>');
The javascript code doesn't know it comes from php, it appears as a constant (a literal) for it.
Yes it is possible. All you have to do is put your <?PHP echo $cid; ?> in where you need it
<script>
$(function ()
{
$('#rc_desc<?PHP echo $cid; ?>').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc$cid').click(function ()
{
$(location).attr('href','student.php?<?PHP echo $cid; ?>');
});
});
This is possible because by the time the scrip is put into the page the cid has already been replaced by the string on the server. Since PHP is server driven, before it spits back the html/script it will be just like you put it in yourself.
There is almost no way to actually communicate PHP and JavaScript. However, the best and simplest way is to set the ID within an attribute. The new HTML5 data attributes would be perfect.
For example, have a anchor tag with
<span data-id="22">some event</a>
and then:
$(this).attr('href','student.php?'+$(this).attr('data-id'));
Or just use
<?php echo $id; ?>
if it is not external JS file
Try this code
foreach ($courses as $cid=>cinfo){
$univ = $cinfo['univ'];
$desc = $cinfo['desc'];
$size = $cinfo['size'];
$start = $cinfo['start'];
print "<div class='rc_desc' data-id='$cid' id='rc_desc$cid'>"."$desc<br/>"."<b>$univ</b><br/>".
"<span>Number of students</span>: $size<br/>".
"<span>Started at</span>: ".date('F d, Y',strtotime($start))."<br/>".
}
<script>
$(function ()
{
$('#rc_desc$cid').hover(function ()
{
$(this).toggleClass('.tr');
});
$('.rc_desc').click(function ()
{
$(location).attr('href','student.php?' + $(this).attr("data-id"));
// if you want to redirect the page do this
// window.location.href = 'student.php?' + $(this).attr("data-id");
});
});
</script>
I think you block should be :
<script>
$(function ()
{
<?php foreach($courses as $cid=>cinfo) : ?>
$('#rc_desc<?php echo $cid; ?>').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc<?php echo $cid; ?>').click(function ()
{
$(location).attr('href','student.php?<?php echo $cid; ?>');
});
";?>
<?php endforeach; ?>
});
</script>
UPDATE
But you don't really need to do this, you have
"<div class='rc_desc' data-id='$cid' id='rc_desc$cid'>"."$desc<br/>"."<b>$univ</b><br/>".
"<span>Number of students</span>: $size<br/>".
"<span>Started at</span>: ".date('F d, Y',strtotime($start))."<br/>".
You can try this
$(function (){
$('.rc_desc').hover(function ()
{
$(this).toggleClass('.tr');
});
$('.rc_desc').click(function ()
{
attrId = $(this).attr("data-id");
$(location).attr('href','student.php?'+id);
});
});

pass php array to jquery function

I got a page with a form to fill it with custormers info. I got previous custormers data stored in a php array. With a dropdownlist users can fill the form with my stored data.
what i have is a jquery function that triggers when the value changes and inside that function i whould like to update the form values with my stored data (in my php array).
Problem is that i dont know how to pass my php array to the jquery function, any idea ??
this is how i fill the array:
$contador_acompanantes = 0;
foreach ($acompanantes->Persona as $acomp)
{
$numero = $acomp->Numero;
$apellidos = $acomp->Apellidos;
$nombre = $acomp->Nombre;
$ACOMPANANTES[$contador_acompanantes] = $ficha_acomp;
$contador_acompanantes++;
}
got my select object:
<select name="acompanante_anterior" id="acompanante_anterior">
<option value="1" selected>Acompañante</option>
<option value="2">acompanante1</option>
<option value="2">acompanante2</option>
</select>
and this is my code for the jquery function (it is in the same .php page)
<script type="text/javascript">
$(document).ready(function()
{
$('#acompanante_anterior').on('change', function()
{
});
});
</script>
var arrayFromPHP = <?php echo json_encode($phpArray); ?>;
$.each(arrayFromPHP, function (i, elem) {
// do your stuff
});
You'll likely want to use json_encode, embed the JSON in the page, and parse it with JSON-js. Using this method, you should be aware of escaping </script>, quotes, and other entities. Also, standard security concerns apply. Demo here: http://jsfiddle.net/imsky/fjEgj/
HTML:
<select><option>---</option><option>Hello</option><option>World</option></select>
<script type="text/javascript">
var encoded_json_from_php = '{"Hello":[1,2,3], "World":[4,5,6]}';
var json = JSON.parse(encoded_json_from_php);
</script>
jQuery:
$(function() {
$("select").change(function() {
$(this).unbind("change");
var val = json[$(this).val()];
var select = $(this);
$(this).empty();
$.each(val, function(i, v) {
select.append("<option>" + v + "</option>");
});
});
});
try this one..
<script type="text/javascript">
$(document).ready(function()
{
$('#acompanante_anterior').on('change', function()
{
my_array = new Array();
<?php foreach($array as $key->val)?>
my_array['<?php echo $key?>'] = '<?php echo $val;?>';
<?php endif; ?>
});
});
</script>

How do I call MVC Controller from with Javascript function

I have a onclick event on a submit button in my CI app. So when user clicks submit, it goes to my js function that disables the button, but it does not continue processing. I used this “document.forms[“mainFrm”].submit();”, but because of the way the code is written I need it to go directly to a controller and finish processing.
So how do I call a CI controller from my js function?
Here is the function that is being called onClick:
function disableWhenSubmit()
{
alert ("You did get here");
var holdBtnElement = document.getElementById('btn_Add');
holdBtnElement.disabled = true;
holdBtnElement.value = "sending ...";
//document.forms["createRequestForm"].submit();
<?= base_url();?>index.php/request"; //this is what I am working on
}
and here is the button:
input type="submit" id="btn_Add" name="btn_Add" value="Submit">
index.php
<script>
// create a global var before calling your external
// javascript file(s).
var BASE_PATH = "<?php echo base_url();?>";
</script>
<script src="link_to_myjavascript.js"></script>
myjavascript.js (jQuery example)
(function($){
$(function(){
var do_ajax = function(some_params){
$.ajax({
url : BASE_PATH + 'controller/method',
});
}
if(conditions)
{
do_ajax(some_params);
}
});
})(jQuery);
Look at ajax call.
Using prototypejs or Jquery
<input type="button" onclick="dosomething()" />
example
<script>
function dosomething() {
var url = "something.php";
new Ajax.Request(url, {
parameters: {//parameters},
onSuccess: function(transport){
// do something when response is good
},
onFailure: function (request) {
// Do something when somehting goes wrong
});
}
</script>

JQuery Updating Status

I am writing some jquery to call an ajax script every 2 seconds to get the result and update the page. I am mostly a backend programmer and could use some help on this.
This is the code I have now:
<script language="javascript">
function downloadProgress(id) {
$("#" + id + "").load("index.php?_controller=download&_action=getDownloadProgressAjax",
{
downloadId: id
}
);
setTimeout(downloadProgress(id), 2000);
}
</script>
<?php
foreach ($downloads as $dl) {
?>
<div id="<?php echo $dl["download_id"]; ?>">
<script language="javascript">
downloadProgress(<?php echo $dl["download_id"]; ?>);
</script>
</div>
<?php
}
?>
This does not work. What am I doing wrong or would you suggest another approach?
Thanks
I think that you are confusing your PHP script by giving it both query string variables (sent as GET) and data (which is probably getting sent as POST). Try this:
$("#" + id).load("index.php?_controller=download&_action=getDownloadProgressAjax&downloadId="+id }
since you are using jquery, you can use the $.ajax function when the page is ready.
$(function () {
function function downloadProgress(id) {
$.ajax({
url: "index.php?_controller=download&_action=getDownloadProgressAjax&downloadId="+id
})
setTimeout(function () {
if (downloadnotcomplete){ // this way your script stops at some pont.
downloadProgress(id);
}
},2000);
}
});
You will attach the downloadProgress(id) function to your download button or anything else, to trigger the function the first time.
The problem you are having is that you have to provide a parameterless function and not a function call to setTimeout. Also, I would do it a little bit different and use setInterval instead of setTimeout as it relays your intention better in the code. Here is how I would do it:
<script language="javascript">
$(function() {
setInterval(downloadHandler, 2000);
});
function downloadHandler() {
// I'm not sure where the id is coming from you will probably need to put a
// class on your div's so that you can select them.
$(".MyDivClass").each(function() {
var id = $(this).attr("id");
downloadProgress(id);
});
}
function downloadProgress(id) {
$("#" + id + "").load(
"index.php?_controller=download&_action=getDownloadProgressAjax",
{ downloadId: id }
);
</script>
and then on your div:
<?php
foreach ($downloads as $dl) {
?>
<div id="<?php echo $dl["download_id"]; ?>" class="MyDivClass"/>
<?php
}
?>
Hope this helps.

Categories