How to echo php array in javascript? - php

I have an php array that is generated by server-side code. I want to show the array value in my input field after user pick an option from my dropdown menu. Please see my code:
$(document).ready(function(){
$('select[name="job_number"]').change (function () {
var selectedVal = $(this).val();
var test="<?php echo $JNarray['selectedVal'];?>"; //where the problem is
$('input[name="project"]').val(test);
//I want show value1 to value 3 in my input field when user picks
//an option from my dropdown menu.
});
<?php
$JNarray['job1']=value1;
$JNarray['job2']=value2;
$JNarray['job3']=value3;
?>
<form action='project_manager' method='post'>
<input type='text' name='project' value='show value1 to value3 when user picks an option' />
<select name='job_number'>
<option value='job1'>job1</option>
<option value='job2'>job2</option>
<option value='job3'>job3</option>
</select>
</form>
Any thoughts? Thanks for the help!

Here's a cleaner way to do it without having to set the array to a variable. Use a data attribute that jQuery reads with $.data()
HTML:
<option value='job1' data-job-val="<? echo $arrayvalue ?>">job1</option>
JS:
$('select[name="job_number"]').change (function () {
var test=$(this).find('option:selected').data('job-val');
$('input[name="project"]').val(test);
});

Though, I don't recommened echoing php in js...
var test=JSON.parse(<?php echo json_encode($JNarray['selectedVal']);?>); //where the problem is

<select name='job_number'>
<option value='<?php echo $JNarray['job1'] ?>'>job1</option>
...
...
</select>
<script>
$(document).ready(function(){
$('select[name="job_number"]').change (function () {
$('input[name="project"]').val($(this).val());
});
</script>
something like that.

You have to declare and populate your array before you use it on the jquery code. Move your <?php ?> code to the top.
Then pass the whole php array to javascript, using JSON as Trevor suggested:
$(document).ready(function(){
var options = JSON.parse(<?php echo json_encode($JNarray);?>);
$('select[name="job_number"]').change (function () {
var selectedVal = $(this).val();
var test=options[selectedVal]; //where the problem was
$('input[name="project"]').val(test);
});
});

I agree with Trevor, however try
"<?php echo $JNarray['"+selectedVal+"'];?>"
Echoing PHP means your calling your JS from a PHP file, not a good approach dude!, The only thing I would pass is maybe a BASE_URL or FILE_UPLOAD_TYPE/SIZE, even those are ewwwwwwwy

Related

How to pass a PHP variable to a .JS file using JQUERY?

I'm a JQUERY begginner. I'm trying to pass a PHP variable to a js file so that i can use it in JQUERY! But found no resource to learn to do so. I'm able to pass a JQUERY variable to a different php file but I couldn't pass PHP variable to a Jquery file. Is really possible to do so?
function.php:
<?php $variable = $fetch['username']; ?>
app.js : How can use this variable in app.js file below?
$(document).ready(function(){
var flwbtn = $(".findrowpplfollowbtn");
flwbtn.click(function(){
var selectflwusername = $(this).parent().prev().last().find(".findpplrowusername").text();
$.post("../php/flw.php",{flwusernameselected:selectflwusername})
});
});
Echo it to HTML temaplate. If it's some structure/array use for example json format.
<script>
<?php $variable = $fetch['username']; ?>
var js_variable = <?php echo json_encode($variable); ?>
</script>
or
echo some hidden element like
<input type="hidden" id="custId" name="custId" value="<?php echo($fetch['username']); ?>">
and grab if with Jquery like
<script>
$( "#custId" ).value();
</script>
with your code
JS:
$(document).ready(function(){ var flwbtn = $(".findrowpplfollowbtn");
flwbtn.click(function(){
var selectflwusername = $(this).parent().prev().last().find(".findpplrowusername").text();
$.post("../php/flw.php",{$( "#custId" ).value()})
});
});

How to pass default value to ajax while retrieving data from mysql in php

I need to get different fields from mysql database table in php using ajax.
I did that using the following code. But I need to get some default value when I load the page without clicking any select button.
My code is
Ajax Code
<script>
function langchange()
{
var langs= $('#langs').val();
$.ajax({
type:"POST",
url:"ajax_lang_change.php",
data:"id="+langs,
success:function(value){
var data=value.split("|_,_|";
for(var i=0;i<data.length;i++){
$("#cat_desc"+i).html(data[i]);
}
}
});
}
</script>
Php/html script
<select name="sources" id="langs" onchange="langchange();" placeholder="English">
<?php
$language=mysqli_query($link,"select * from language_reference";
while($lang=mysqli_fetch_array($language))
{
?>
<option value="<?php echo $lang['lang_id']; ?>" selected="selected"><?php echo $lang['lang_name']; ?>
</option>
<?php } ?>
</select>
Any help?? Thanks in advance..
If i understand you right, then you can call the langchange() on page load and it will take currently selected option from the langs select element
$(window).load(function(){
langchange();
});

Alert id of contents fetched from php while loop using jquery

I am new to jquery and ajax. I have a PHP while loop which display contents from database. What I need is simply alert the "content_id" on click of each contents.
My script
<script type="text/javascript">
$(function() {
$(".show_id").click(function() {
var test = $(".contentid").val();
alert(test);
});
</script>
PHP Code
//code to fetch contents from database
foreach($stmt as $row)
{
echo $row['content'];
?>
<form action="" method="post">
<input type="hidden" class="contentid" value="<?php echo $row['content_id']; ?>">
<div class="show_id" ></div>
</form>
<?php
}
?>
It Alerts the id for each content, But only the first id always .
How to alert id for each contents respectively ?.
Thanks for any help...
This would work:
$(function() {
$(".show_id").click(function() {
var cur = $(".show_id").index($(this)); // get the index of the clicked button within the collection
var test = $(".contentid").eq(cur).val(); // find the input with the contentid class at the same index and get its value
alert(test);
});
});
Note that this assumes that the two classes are always paired together like you show and not used elsewhere in your html, which seems a reasonable assumption here
<script type="text/javascript">
$(function() {
$(".show_id").click(function() {
var test = $(this).prev(".contentid").val();
alert(test);
});
})
</script>

Get value of hidden input to jquery

I am working in wordpress and I have created a custom plugin.In which I have get multiple data from the database and my code is like this.
<?php
foreach($result as $res)
{
?>
<input type="hidden" class="status" value="<?php echo $res->review_status; ?>" />
<button class="aprove" value="<?php echo $res->review_id; ?>">Aprove</button>
<?php
}
?>
Now, I want to get hidden field value in jQuery. My jQuery code is like this:
jQuery(".aprove").click(function(){
var status = jQuery('.status').val();
alert(status);
});
When I click on button then it shows only first value of hidden field. For instance, the fist hidden value is 1 and second value is 0 then it display only fist value 1 for both button. So what shold I have to do to get different hidden value?
Try :
jQuery(".aprove").click(function(){
jQuery('.status').each(function(){
var status = jQuery(this).val();
alert(status);
});
});
.each will loop through all the classes and it will give alert every value of it.
JS Fiddel Demo
Updated
Updated Demo
Here is your answer. for each button the value taken would be from the input element before the button element
jQuery(".aprove").click(function(){
var status = jQuery(this).prev('.status').val();
alert(status);
});
var status = jQuery('.status').val();
alert(status);
this will get the value of element first found on page and will return the result,
if you want all the input values use
jquery each() - https://api.jquery.com/jquery.each/
jQuery('.status').each(function(){
alert($(this).val());
});
// this will give you all the values you want, one by one
you can use .map like this to get what you want:
$(document).ready(function(){
var status=[]
jQuery(".aprove").click(function(){
status = $(".status").map(function() {
return $(this).val();
}).get();
alert(status);//array of values
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" class="status" value="0" />
<input type="hidden" class="status" value="1" />
<button class="aprove" value="">Aprove</button>

jQuery onClick post data to second column

Can't figure it out what is the problem with the $.post here.
Actually i am retrieving data from database in column 1 and column 2. both are getting values perfectly when i am trying the controller function individually. Now, i am trying jquery that when the first column value will be clicked it shows the other column values. but its not passing on $.post
Here is jquery :
<script type='text/javascript'>
$('document').ready(function(){
var link ="<?php echo base_url();?>" ;
$( "#cat_level_1" ).on( "click", function() {
var cat_level_1 = $('#cat_level_1').val();
alert (cat_level_1); //getting elements id like (men alert for 49) alert on click
$.post(link + "admin/admin_cat/cat_level_2", {cat_level_1 : cat_level_1}, function(data) {
alert( "Data Loaded: " + data);
//here it showing me HTML of my controller in alert.
$('#cat_level_3').html('');
$('#cat_level_4').html('');
$('#cat_level_2').html(data);
});
});
});
</script>
For second column :
<script type="text/javascript">
$('document').ready(function(){
var link ="<?php echo base_url();?>" ;
$('#cat_level_2').click(function(){
var cat_level_2 = $(this).val();
alert (cat_level_2); //it shows me alert with its db id.
$.post(link + "admin/admin_cat/cat_level_3", {cat_level_2:cat_level_1}, function(data) {
$('#cat_level_4').html('');
$('#cat_level_3').html(data);
});
});
});
<script>
Here is my php(view) code from which i am getting values :
For column 1 :
<div class="category-col">
<select size="15" name="cat_level_1" id="cat_level_1">
<?php
if (isset($cat_level_1) && $cat_level_1 != ''){
foreach ($cat_level_1 as $cat_1) {?>
<option value="<?php echo $cat_1['cat_id']; ?>">
<?php echo $cat_1['cat_title']; ?>
</option>
<?php }
}
?>
</select>
</div>
For column 2 :
<div class="category-col">
<select size="15" name='cat_level_2' id='cat_level_2'>
<?php
if (isset($cat_level_2) && $cat_level_2 !=''){
foreach ($cat_level_2 as $cat_2) {?>
<option value="<?php echo $cat_2['cat_id']; ?>">
<?php echo $cat_2['cat_title']; ?>
</option>
<?php }
}
?>
</select>
</div>
Some one help me out please!. Where is the problem?
Thank you!
The issues is in this line:
$.post(link + "admin/admin_cat/cat_level_3", {cat_level_1:cat_level_1}, function(data) {
The problem here is you are using var "cat_level_1" value in both the places and when trying to read the para in php you wont get it.
I think you should quote the key cat_level_1. so the code must be:
$.post(link + "admin/admin_cat/cat_level_3", {"cat_level_1":cat_level_1}, function(data) {
try this if it works for you.
The problem is this line
var link ="<?php echo base_url();?>" ; you can not do this from javascript if you have virtual hosts set up you can do this window.location.origin + "/admin/admin_cat/cat_level_2"
Ok here could be the mistake.
cat_level_2:cat_level_1
Make it
cat_level_2:cat_level_2
in the second js.
you cannot write php code inside js file.So this line will not work.
var link ="<?php echo base_url();?>" ;
try to add this line inside your main view file (header) before you including the javascript files
<script type="text/javascript">
var link ="<?php echo base_url();?>" ;
</script>

Categories