How to share a variable with js files laravel? - javascript

I have a Laravel 5.5 project
In the app service providers I have shared some variables like this:
public function boot()
{
View::share('path', 'laravel/public');
}
I can access it in every view blade very easily.
But I have ajax search and it comes from a separated JS file included in the master layout.
<script src="{{ asset('style//js/searchajax.js')}}"></script>
This is the searchajax.js code
var path = '/laravel/public/';
$("#userSearchAjax").bind('change keyup',function(){
var userSearchAjax = $(this).val().trim();
if(userSearchAjax != '')
{
$.ajax({
type:'GET',
url: '/laravel/public/userssearchajax',
data: {userSearchAjax:userSearchAjax},
success:function(data){
var result = "<tr class='info'><td>اسم المستخدم</td><td>الصورة</td></td><td>البريد الالكتروني</td></td><td>رقم الهاتف</td></td><td>الفرع</td></td><td>اعدادات</td></tr>";
for(i = 0;i<data.length;i++)
{
result+= "<tr class='warning'><td>"+data[i]['user_name']+"</td>";
result+= "<td>";
result += "<a data-title='"+data[i]['user_name']+"' data-lightbox='image-1' target='_blank' href='"+path+"uploads/users/"+data[i]['id']+"/"+data[i]['id']+".jpg'><img alt='"+data[i]['user_name']+"' title='"+data[i]['user_name']+"' src='"+path+"/uploads/users/"+data[i]['id']+"/"+data[i]['id']+".jpg' class='thumb' /><br /></a>";
result+= "</td>";
result+= "<td>"+data[i]['user_email']+"</td>";
result+= "<td>"+data[i]['user_phone']+"</td>";
result+= "<td>"+data[i]['user_department']+"</td>";
result+= "<td><a class='btn btn-success'>عرض</a>";
result+= "<a class='btn btn-info'>تعديل</a></td></tr>";
}
result += "";
$("#search-result").html(result);
}
});
}
else
{
$("#search-result").html("");
}
})
My problem is that I can't access the shared variable $path inside js file
even shared model like Auth and other default models in Laravel I cant access them inside the js file.
Thanks

<script>
var path= {!! $path !!};
</script>
I would also recommend changing the variable name to "public_path". There are other paths you could need.
This question was also similar to:
laravel-5 passing variable to JavaScript

You can set the path in your JS code by injecting the code using Blade like this {{$path}} or {{session('path')}} ... provided you have set the session('path') somewhere at right time and right place.

Related

How to parse a PHP variable using a dynamic JS variable?

I have 5 PHP variables, $menu1 to $menu5, that each evaluate to a keyword. I'm trying to populate these 5 PHP variables in JavaScript, and display them. The below code doesn't work. What is wrong with my processing of the PHP variables?
var menu_populator = "";
for (var x = 1; x <= count; x++) {
menu_populator += '<li><a class="myclass" href="#link">' + '<?php echo $menu' + x + '?>' + '</a></li>';
}
$('#nav_menu').html(menu_populator);
Depending on how you are getting the menu data server-side you can try both methods below. One is for set $menu variables but if you are getting data from a database or the $menu variable are created within a loop you might find the second method better.
Method one- PasteBin
Echo your php variables into a javascript array.
var myarray=["<?php echo $menu1;?>","<?php echo $menu2;?>","<?php echo $menu3;?>","<?php echo $menu4;?>","<?php echo $menu5;?>"];
Method Two- PasteBin
Create this array server-side, this will be better if you are creating the current $menu variable in a loop, with this you can just use array_push() to push the values into the array.
<?php
// PHP Array
$menu = array('Home', 'Gallery', 'About');
// How to push new item into array
array_push($menu, 'Contact');
?>
Then just simply echo this array into your javascript myarray variable.
var myarray=<?php echo json_encode($menu);?>;
I have used the following javascript to test both methods and both seem to function just fine. I prefer the second method but I have decided to offer both as I don't know what your PHP looks like or how your $menu variables are being defined so this should cover both.
window.onload=function(){
for(var i=0; i<myarray.length; i++){
var link= document.createElement('a');
link.href="#";
link.innerHTML=myarray[i];
document.body.appendChild(link);
document.body.appendChild(document.createElement('br'));
}
}
If you have any questions about the source code above please leave a comment below and I will get back to you as soon as possible.
I hope this help. Happy coding!
Something like this would do the trick
<?php
$menu = "menu";
echo '
<script>
var count = 10;
var menu_populator="";
for(var x=1;x<=count;x++)
{
menu_populator += \'<li><a class="myclass" href="#link">'.$menu.' \'+x+\'</a></li>\';
}
$(\'#nav_menu\').html(menu_populator);
</script>
';
?>

Javascript variable works only the first time

I have function that works with JSON.
function makeItem(data){
var tbl_body = "";
$.each(data, function() {
var id = parseInt(this.ProductId);
var tbl_row = "";
tbl_row += "<a href='article.php?cat=<?=$cat?>&subcat=<?=$subcat?>&id="+id+"'>";
tbl_row += "<div class='subCatImg'><img src='imagesDB/articles/<?=$main["+id+"]['dir']?>/<?=$main["+id+"]['image']?>'></div>";
tbl_row += "<div class='subCatName'>"+this.ProductNameBG+"</div>";
tbl_row += "<div class='subCatText'>"+this.ProductNameBG+"</div>";
tbl_row += "</a>";
tbl_body += "<div class='categoryWrap'>"+tbl_row+"</div>";
})
return tbl_body;
}
The problem is that the variable id works only the first time - in the a tag but not in the second nor the third time.
Is it because the a tag is not immediately closed or because the second and the third time I'm trying to use it in php array. I'm sure that the array works because if I hardcore it(<?=$main[1]['dir]?>) the image is displayed(no need for quotation marks, I need integer).
The thing is that I have to make it dynamic so I can't just type some number.
Why does it work the first time but not the others?
You can convert your PHP array into a json object like this :
var main = <?php echo json_encode($main) ?>;
then iterate through it.
#epascarello is correct. PHP is server side, were JS is client side. Instead, try to do something like
UPDATED:
tbl_row += <?php print("\"<a href='article.php?cat=$cat&subcat=$subcat&id=\" + id + \"'>\""); ?>
tbl_row += <?php print("\"<div class='subCatImg'><img src='imagesDB/articles/$phpVal1/$phpVal2'></div>\""); ?>
tbl_row += <?php print("\"<div class='subCatName'>\" + this.ProductNameBG + \"</div>\"");?>
tbl_row += <?php print("\"<div class='subCatText'>\" + this.ProductNameBG + \"</div>\"");?>
tbl_row += <?php print("\"</a>\"");?>
In this, you will have to pass the value of the id and the dir from JS to php so php can parse it's multidimensional array. You'll notice that <?=$main["+id+"]['dir']?>/<?=$main["+id+"]['image']?> has changed to $phpVal1/$phpVal2.
You can do this a number of ways - perhaps through a click of a button. But php will be done first, and then the JS.
In essence, you are getting all the values from the server (php) and forcing it to write the client side (JS) for you.

Wordpress Multisite, Injecting Dynamic Content into New Site Registration Form in 'site-new.php'

I have found a solution here by dennisg and edited by Hans Helge. The part I am working with is the injection of extra form fields using an IIFE and jQuery in an external file.
(function($) {
$(document).ready(function() {
$('<tr class="form-field form-required"></tr>').append(
$('<th scope="row">New field</th>')
).append(
$('<td></td>').append(
$('<input class="regular-text" type="text" title="New Field" name="blog[new_field]">')
).append(
$('<p>Explanation about your new field</p>')
)
).insertAfter('#wpbody-content table tr:eq(2)');
});
})(jQuery);
Thus far, I have successfully squeezed PHP into the above js. The following seems to work ok, when I suffix the file name with .php instead of .js
<?php
$user_def_cats = array('Subject', 'Person', 'Client');
?>
(function($) {
$(document).ready(function() {
$('<tr class="form-field form-required"></tr>').append(
$('<th scope="row">Site Category</th>')
).append(
$('<td></td>').append(
$('<select name="blog[blog_cats]" ><?php
foreach ($user_def_cats as $key => $val) {
echo "<option value=\"" . ($key + 1) . "\" >" . $val . "</option>";
}
?></select>')
).append(
$('<p>Blog Category (Allows creation of different blog listings.)</p>')
)
).insertAfter('#wpbody-content table tr:eq(2)');
});
})(jQuery);
So, this works with sample data:
$user_def_cats = array('Subject', 'Person', 'Client');
Next, I try to access the dynamic content ('Subject','Person' ... etc ) using PHP by requiring once the main plugin file, so I can call a method to retrieve the dynamic form data using get_site_option().
require_once WP_PLUGIN_DIR . '/' . plugin_basename(__FILE__);
With the inclusion of this one line above, I get an error:
Uncaught SyntaxError: Unexpected token <
http://wpmu.net/wp-content/plugins/list-all-blogs-i3/js/add_site_cat_frm_elem.php?ver=4.4.3
line 1
This might be because the plugin file I am calling is echoing out stuff, which is outside of any legitimate js code. E.g. echo "Hi"; causes same error.
Reading around the web I see that perhaps, a better solution would be to save all my dynamic content into a data.json file (as opposed to wp_sitemeta using update_site_option() ), and then AJAX/ get_json to access the data. This would avoid the somewhat awkward cross over of PHP and JS.
Maybe there is a better way to add form fields with dyn content into admin site-new.php page?
Any light on this matter would be gratefully appreciated.
OK. In my plugin file, I now have this script, which uses wp_localize_script(), to pull in the IIFE with server side data injected into it:
wp_register_script('add_site_cat_frm_elem',
plugins_url('js/add_site_cat_frm_elem.js', __FILE__));
// Only way I can see to easily inject dynamic data into js file.
wp_localize_script('add_site_cat_frm_elem', 'user_def_cats', $this->user_def_cats);
wp_enqueue_script('add_site_cat_frm_elem');
In this instance $this->user_def_cats holds data extracted from wp_sitemeta using get_site_option().
And then finally, my js file looks like this, where the said data is used to build options for a select form element:
(function($) {
$(document).ready(function() {
var myOptions = '';
user_def_cats.forEach(function(val,i,user_def_cats){
myOptions += '<option value="'+ i +'">' + val + '</option>';
});
$('<tr class="form-field form-required"></tr>').append(
$('<th scope="row">Site Category</th>')
).append(
$('<td></td>').append(
$('<select name="blog[blog_cats]" >' + myOptions + '</select>')
).append(
$('<p>Blog Category (Allows creation of different blog listings.)</p>')
)
).insertAfter('#wpbody-content table tr:eq(2)');
});
})(jQuery);

How to change conditional PHP if-phrase to JS?

I had a product grid that originally was written in PHP. But I've changed it to AJAX and get the results in JSON and have turned that to JS variables.
Now I need to write the whole HTML structure as a JS string to attach it with jQuery. But I'm having difficulties with this one:
<? if(isset($mv['jan_code']) AND $mv['jan_code']!=''){ ?>
<td>JAN Code</td><td>"+post_meta['jan_code']+"</td>
<? }?>
$mv['jan_code'] is the following JS string: post_meta['jan_code'].
How can I rewrite this PHP if-phrase in JS?
I'm not sure if this is the best way, but this is how I'm thinking of outputting my JSON results:
var fill_grid_json = function(data){
var jsonData=$.parseJSON(data); //change here
$.each(jsonData, function(i) {
// get JS variables
var id = jsonData[i].ID;
var post_title = jsonData[i].post_title;
var post_meta = jsonData[i].post_meta;
var grid_item = "<tr>"+
"<td>" + id + "</td>"+
"<td>" + post_title + "</td>"+
"</tr>";
$(grid_item).appendTo("#testajax tbody");
});
};
I found one of the ways is just creating a JS string like this:
if(post_meta['jan_code'] != ''){
var spectr_jan = "<tr><td>JAN Code</td><td>"+post_meta['jan_code']+"</td></tr>";
} else { var spectr_jan=''; }
and then showing it somewhere using jQuery.

Ajax function triggered from another ajax function not working

I am working on a script that copies a row ID from one table and creates a new table on the page with all rows that have been selected via checkbox in order to create a comparison table of selected results and I've run into an issue with the synergy between two of my ajax calls.
When the following row is created in the original table, the class that is assigned to the <a> element of that row triggers an ajax call which then populates a modal that shows up on the page with additional information.
This is the line
echo "<td><a id='$id' data-toggle='modal' href='#provmodal' class='push'>".$results['provider_name']."</a>";
When the modal is triggered this way, the information populates just fine.
Now, within the script that populates the new table, I make a call to another separate script which re queries the selected row ids and sets the html.
Here is that portion of the script :
$('.compareCheck:checked').each(function(){
var ele_id = $(this).attr('id');
$.ajax({
type : 'post',
url : 'compare.php', //query
data : 'post_id='+ ele_id, // passing id via ajax
dataType: "json",
success : function(data){
var row = "<tr class='removeRow'>";
row += "<td>" + data.provider_num + "</td>";
//HERE IS WHERE THE RE-CREATION OF THE MODAL CALL GOES \/
row += "<td><a id='" + ele_id + "' data-toggle='modal' href='#provmodal' class='push'>" + data.provider_name + "</a></td>";
row += "<td style='text-align:right;'>$" + formatNumber(data['233_net_charity_care']) + "</td>";
row += "<td style='text-align:right;'>$" + formatNumber(data['291_cost_of_non_mcr_bad_debts']) + "</td>";
row += "<td style='text-align:right;'>$" + formatNumber(data['301_cost_of_uncomp_care']) + "</td>";
row += "<td style='text-align:right;'>" + ((data['233_net_charity_care']/data['301_cost_of_uncomp_care'])*100).toFixed(1) + "%</td>";
row += "<td style='text-align:right;'>" + ((data['291_cost_of_non_mcr_bad_debts']/data['301_cost_of_uncomp_care'])*100).toFixed(1) + "%</td>";
row += "</tr>";
$("#compareTable > tbody").append(row);
}
});
});
As you can see in my current implementation I am using the ele_id var, but I have also tried things like data.id and data['id']. All of which trigger the modal but produce no results from the php script.
Here are my two php scripts:
Script A: Populating the modal - (modalquery.php)
<?php
require_once("link_costreport_2013.php");
$id = $_POST['post_id'];
$modalquery = $link->prepare("SELECT * FROM s10 WHERE id = :id");
$modalquery->bindParam(':id', $id, PDO::PARAM_INT);
$modalquery->execute();
$modalresults = $modalquery->fetch();
print_r("<h4>State: ".$modalresults['state']."</h4>");
print_r("<h4>City: ".$modalresults['city']."</h4>");
print_r("<h4>Street: ".$modalresults['street']."</h4>");
print_r("<h4>Zip: ".$modalresults['zip']."</h4>");
print_r("<h4>County: ".$modalresults['county']."</h4>");
?>
and script B - The script that turns the re-query into values for the new comparison table (compare.php)
<?php
include_once('functions.php');
include_once('link_costreport_2013.php');
if(isset($_POST['post_id'])){
$id = $_POST['post_id'];
}
$query = $link->prepare("SELECT *
FROM `s10`
WHERE `id` = :id");
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->execute();
$results = $query->fetch(PDO::FETCH_ASSOC);
echo json_encode($results);
?>
also in case it helps, here is my script for turning the .push class into a trigger for the ajax call which returns the modal content.
$(function(){
$('.push').click(function(){
var ele_id = $(this).attr('id');
$.ajax({
type : 'post',
url : 'modalquery.php', // in here you should put your query
data : 'post_id='+ ele_id, // here you pass your id via ajax .
// in php you should use $_POST['post_id'] to get this value
success : function(r)
{
// now you can show output in your modal
$("#provmodal .modal-body").html(r).promise().done(function(){
$("#provmodal").modal('show');
});
}
});
});
});
I'm new to using ajax and jquery in this fashion so any insight at all would be excellent.
thanks in advance
:EDIT: Here is the output from json_encode($results) when ID = 1
{"id":"1","report_record_num":"548598","provider_num":"381301","provider_name":"COTTAGE GROVE COMMUNITY HOSPITAL","street":"1515 VILLAGE DRIVE","city":"COTTAGE GROVE","county":"LANE","state":"OR","zip":"97424-9700","cbsa":"21660","urban_or_rural":"Rural","ownership_type":"Voluntary, Nonprofit, Church","divider":"","divider2":"","1_cost_to_charge_ratio":"0.703459","2_net_rev_from_mcd":"3920096","3_recieve_sup_mcd_payments":"Y","4_include_if_yes":"N","5_dsh_or_sup_payments":"84890","6_medicaid_charges":"6192717","7_medicaid_cost":"4356323","8_dif_net_rev_and_cost":"351337","9_schip_net_rev":"0","10_stnd_alone_schip_charges":"0","11_stnd_alone_schip_cost":"0","12_diff_schip_rev_and_cost":"0","13_net_rev_from_state_local":"0","14_charge_under_state_law":"0","15_state_local_program_cost":"0","16_dif_between_net_rev_and_cost":"0","17_private_grants_and_donations":"6886","18_gov_grants":"0","19_tot_unreim_cost_mcd_schip_gov":"351337","201_tot_init_charity_for_uninsured":"593922","202_tot_init_charity_for_insured":"1072203","203_tot_init_charity_all":"1666125","211_cost_of_init_charity":"417800","212_cost_of_init_charity":"754251","213_cost_of_init_charity":"1172051","221_partial_pmt_charity_pat":"4385","222_partial_pmt_charity_pat":"8868","223_partial_pmt_charity_pat":"13253","231_net_charity_care":"413415","232_net_charity_care":"745383","233_net_charity_care":"1158798","241_charges_beyond_los_inc":"N","251_charges_beyond_los_lim":"0","261_total_bed_debts":"0","271_medicare_bad_debts":"79275","281_non_medicare_bad_debts":"-79275","291_cost_of_non_mcr_bad_debts":"-55767","301_cost_of_uncomp_care":"1103031","311_cost_of_unreim_and_uncomp":"1454368"}
:EDIT2: Ok, so I went back and took some pics of what is happening. Somehow my modal text is not appearing in the second table <a class="push"> element. Here are the pics:
!(http://imgur.com/xgsOzSy) - This is in the first table
!(http://imgur.com/uSsI3DM) - This is what happens in the second when the same link is pressed. I believe it's not triggering the ajax .push call.
Try changing:
$(document).on('click','.push',function(){
For:
$('.push').on('click', function(){
In the first case the event handler is added to every element with the "push" class that is present in the DOM at the moment of the execution of the "click" function. The second case, the one wich uses the "on" function, it adds the event handler to the elements already present and those which are not yet in the DOM, those which you create after the execution of the adition like the ones you add to the table.
Wish i make my self clear, i am trying to improve my english.

Categories

Resources