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>
Related
How do I make jQuery get value from while loop and display it in another div?
I know I should do it with PHP, But I want to display it with only jQuery.
<? while($commentresult = $commentdata->fetch_array(MYSQLI_ASSOC)) { ?>
<div class="show_url"></div>
<? } ?>
$(document).ready(function() {
var getUrl = $('.get_url_comments').attr('href');
$(".show_url").text("Click This" + getUrl);
});
To do this you can set the text() of the .show_url element based on the following .get_url_comments. Try this:
$(document).ready(function() {
$(".show_url").text(function() {
return $(this).next('.get_url_comments').attr('href');
});
});
You should note though that it would be a much better idea to do this directly in PHP:
<? while($commentresult = $commentdata->fetch_array(MYSQLI_ASSOC)) { ?>
<div class="show_url"><? echo $commentresult['comment']; ?></div>
<? } ?>
Try with this..
$(document).ready(function() {
$('.get_url_comments').map(function(guc){
var el = $(guc);
var url = el.attr('href');
el.prev().text("Click This" + url);
// or
el.prev().html("Click This" + url);
});
});
I try to put data into js file, through "jquery $.post" and "fwrite php", and get back that data into array. How to do that?
here's the html:
<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function() {
if ($("#nameput").val() != "") {
$.post("processing.php", {
putname: $("#nameput").val()
});
var arr = [$.getScript("talk.js")];
alert(arr[0]);
}
})
})
</script>
</head>
<body>
<input type="text" id="nameput" />
<button id="button">send AJAX req</button>
</body>
</html>
Here's the php, I name it "processing.php" :
<?php
$file = fopen("talk.js","a");
$text = $_POST["putname"];
fwrite($file,'"'.$text.'",');
fclose($file);
?>
And "talk.js" will look like this :
"a","b","c",
Why I can't put that data from "talk.js" into array at " var arr = [$.getScript("talk.js")]; " as in html file above?
Here's what I try after I read comments. I change the scirpt into this:
<script>
$(document).ready(function() {
$("#button").click(function() {
if ($("#nameput").val() != "") {
$.post("processing.php", {
putname: $("#nameput").val()
}, function() {
$.getScript("talk.js", function(data) {
var arr = data.split(",");
alert(arr[0]);
})
})
}
})
})
</script>
And php into this:
<?php
$file = fopen("talk.js","a");
$text = $_POST["putname"];
fwrite($file,$text);
fclose($file);
?>
But it still not work?
here's a simplified version of your button click to help you out:
$("#button").click(function() {
$.getScript("talk.js", function(data){
var arr = data.split(',');
alert(arr[0]);
});
});
If you log the output of $.getScript you will easily see why what you're trying doesn't work.
Using this method you will get the data returned from the script ("a","b","c"), but you'll need to split it on a comma into an array. Then you can reference whichever part of the array you want.
Note that the each element of the array will have quotations around them.
I have a html search bar like so:
<form id="testblah" action="search_results.php" method="GET">
<input type="text" name="search" class="Search_bar_box" id="search">
</form>
I am then using Jquery to auto complete the input of a search criteria using pre-defined tags like so:
<script>
$(function() {
$('form').each(function() {
$(this).find('input').keypress(function(e) {
// Enter pressed?
if(e.which == 10 || e.which == 13) {
this.form.submit();
}
});
});
});
$(function () {
var availableTags = [
"Telehandlers",
"Cranes",
"Fork Attachments",
"Aggreko",
"12 Tonne Telhandlers",
"Marwood",
"Crane Suppliers in Manchester",
"Total",
"Oil, Gas & Lubricants",
"Tomato Plant"
];
$("#search").autocomplete({
source: availableTags,
select: function (event, ui) {
window.location = 'search_results.php?search=' + ui.item.value;
}
});
$('#searchForm').on("submit", function (event) {
event.preventDefault();
alert($('#search').val());
});
});
</script>
This all works fine, however, what I want to do now is change my tags from pre-defined text so that my tags are instead pulled from my MySQL data. so I am trying to run a MySQL query to get all data from my table like so:
<?php $query12 = "SELECT * FROM supplier_users, supplier_stats GROUP BY supplier_users.user_id";
$result12 = mysql_query($query12);
while($row1 = mysql_fetch_assoc($result12)) {
$tags = $row1; } ?>
and then trying to place my string inside the jquery tags section like so:
$(function () {
var data = "<?= $tags ?>";
var availableTags = [
data ];
however this stops my jquery from working. Can someone please show me where I am going wrong and how I would need to do this. thanks in advance
You can edit your php code like the following,
<?php
$query12 = "SELECT * FROM supplier_users, supplier_stats GROUP BY supplier_users.user_id";
$result12 = mysql_query($query12);
$tags = array();
while($row1 = mysql_fetch_assoc($result12)) {
array_push($tags, $row1);
}
?>
and in java script as Naruto told replace the
var data = "<?= $tags ?>";
with the following
var data = "<?php echo json_encode($tags); ?>";
// array
var availableTags = JSON.parse(data);
Try to use this kind of solution.
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'.
I have a requirement to get a variable from PHP to Javascript when clicked by the user. I have an array of data returned by a query and I need to pass an ID value for the element clicked so that I can populate an additional data set via the .load using another PHP page. I am unsure how todo this?
Javascript Code in Page:
<script type="text/javascript">
$(function () {
$("#pass_userid_div").click(function () {
$("#another_div").load('remote_pages/get_info.php?userid=' + $GET_THE_USERID_AND_PASS_HERE);
});
});
</script>
PHP Code in Page:
$query_str = "SELECT id, username, dateregistered FROM users";
$query = mysql_query($query_string) or die(mysql_error());
while ($results = mysql_fetch_array($query)) {
print "<div id='pass_userid_div'>{$results['username']}</div>";
print "<div>{$results['dateregistered']}</div>";
}
Why must it be a div? Use an interactive element:
PHP:
while ($results = mysql_fetch_array($query)) {
print "<button type='button' name='pass_userid_div' value='{$results['id']}'>{$results['username']}</button>";
print "<div>{$results['dateregistered']}</div>";
}
JavaScript:
<script type="text/javascript">
$(function () {
$("button[name='pass_userid_div']").click(function () {
$("#another_div").load('remote_pages/get_info.php?userid=' + $(this).val());
});
});
</script>
Update: If it really must be a div, use a data- attribute:
<div class="pass_userid_div" data-userid='{$results['id']}'…
…$(this).data("userid")
$("#another_div").load('remote_pages/get_info.php?userid=' + $GET_THE_USERID_AND_PASS_HERE, function(){
$("#another_div #pass_userid_div").each(function(){
var yourvar =$(this).text();
// use your var
})
});
Please not you should not use more then one div whith the same id. Use class instread