How to use a PHP variable in Javascript using Laravel? - javascript

I use this error code when this information is not found while I echo the JS variable, but it doesn't work in PHP function
$(document).click(function() {
$('#more').empty();
$('#detail-more').empty();
$.get('/inbox', function(date) {
$.each(date, function(app, subcatObj) {
var time = timeAgo(subcatObj.created_at);
if (subcatObj.id == id) {
var id =subcatObj.id;
$('#detail-more').html(`<div class="peers peer-greed">` +
`<div class="peer mR-20"><img class="bdrs-50p w-3r h-3r" alt="" src="https://randomuser.me/api/portraits/men/11.jpg"></div>` +
`<div class="peer"><small>${time}</small>` +
`<h5 class="c-grey-900 mB-5"></h5><span>Then:<?php app\User::find(${id})->name; ?> </span></div>` +
`</div>` +
`<div class="peer"><i class="fa fa-reply"></i></div>`);
$('#more').html(`<h4> ${subcatObj.title} </h4><p> ${subcatObj.text}</p>`);
}
});
});
});
error:"Use of undefined constant id - assumed 'id' (this will throw an
Error in a future version of PHP) (View:
C:\xampp\htdocs\tasvirevarzesh\resources\views\dashboard\email\index.blade.php)"

if you write in others js files you should use input type="hidden"
in blade to get value and then handle it.
You can use
in blade and use {{ }} to coding something here

Related

Django: Writing JavaScript inside template vs loading it

I am using JavaScript to add comment without refreshing the page. When I am using JavaScript inside the template it is working perfectly fine but if I am writing the JavaScript to a file and loading the file inside the template then it is not displaying the name of the person who wrote the comment (It is displaying the comment fine). Below is the JavaScript I used inside the template:
function create_comment(event,div_id,form_id,commentinsert_id) {
event.preventDefault();
var text_id = '#'.concat(div_id,' ','#comment-text')
var slug_id = '#'.concat(div_id,' ','#post_slug')
var appenddiv_id = '#'.concat(div_id)
comment_count ++;
var divcommentinsert_id = 'inserted_comment-'.concat(comment_count.toString())
$.ajax({
url : "create_comment/", // the endpoint
type : "POST", // http method
data : { text : $(text_id).val(), post_slug: $(slug_id).val(),},
// handle a successful response
success : function(json) {
div.innerHTML = `
<div id = `+divcommentinsert_id+` class="card-footer">
<div class="row">
<div>
<img src="{{user.profile.profile_picture.url}}" alt="" width="40" height="40">
</div>
<div class="col-md-8">
<b style="color:rgb(240, 0, 0);"> {{user.first_name}} {{user.last_name}}</b>
<br>
`+json.text+`
<a onClick="edit_comment('`+json.slug+`','`+divcommentinsert_id+`','`+json.text+`')"><i class="fa fa-edit"></i></a>
<a onClick="delete_comment('`+json.slug+`','`+divcommentinsert_id+`')"><i class="fa fa-trash-o"></i></a>
</div>
</div>
</div>`;
document.getElementById(commentinsert_id).appendChild(div);
document.getElementById(form_id).reset();
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
};
In the above code <b style="color:rgb(240, 0, 0);"> {{user.first_name}} {{user.last_name}}</b> is used to display the name. It is displaying name of the person who added the comment but when I copy the same function to comments.js file and load the file like <script src="{% static 'scripts/comments.js' %}"></script> then its not displaying the name instead it is displaying {{user.first_name}} {{user.last_name}}. I am using this javascript in several pages, I thought it is best to write to file and load the file instead of writing the same script in every page. Can someone help me with this?
{{ dictionary.key }}, etc in a template is how you use variables with the django template engine.
A static javascript file is not a template. It isn't processed by the django template engine.
Put the values you need in your html (through the template engine), access them from JS.
Basic ideas:
Create a JS variable (eg: <script>var user_full_name = "{{ user.user_name }} {{ user.last_name }}"</script>), use user_full_name inside the ajax sucess callback.
Put the values inside some html element (eg: <input type="hidden" id="user_name" value="{{ user.user_name }}">) and get it with JS/jQuery $("#user_name").val().
edit: added missing closing double quote to the user_full_name declaration.

how to generate different html if the given object has no results

I am talking to WP REST API and if I do have results in data object I generate HTML code to frontend, and that is working fine, but what to do, and how to generate different HTML output (for example "There is no search result") if there is not data in data object.
I try with if statement but no luck with that. I am new to coding so forgive me if this is trivial problem...
var searchVal = this.inputField.val();
$.getJSON('http://localhost:8888/wptest/wp-json/wp/v2/posts?search=' + searchVal,
data => {
this.createHtml.html(`
<h2 class="search-overlay__section-title">Posts Info</h2>
<ul class="link-list min-list">
<li>${data[0].title.rendered}</li>
</ul>
`);
});
Your code should work if its as below:
var searchVal = this.inputField.val();
$.getJSON('http://localhost:8888/wptest/wp-json/wp/v2/posts?search=' + searchVal,
data => {
if (data.length == 0) {
// no results html
} else {
this.createHtml.html(`
<h2 class="search-overlay__section-title">Posts Info</h2>
<ul class="link-list min-list">
<li>${data[0].title.rendered}</li>
</ul>
`);
}
});
Hope this helps !!
Hello guys I did a little research and found a more concise solution, Ternary Operator... sorry if I didn't say it was ES6 syntax and I used a compiler to run regular javascript in the browser
var searchVal = this.inputField.val();
$.getJSON('http://localhost:8888/wptest/wp-json/wp/v2/posts?search=' + searchVal,
data => {
this.createHtml.html(`
<h2 class="search-overlay__section-title">Posts Info</h2>
${data.length == 0 ? '<p>No Results</p>' : '<ul class="link-list min-list">'}
${data.map(item => `<li>${item.title.rendered}</li>`).join('')}
${data.length == 0 ? '</ul>' : ''}
`);
});

How to dynamic dropdown list in laravel 5.3?

My html is like this :
<div class="form-group has-feedback{{ $errors->has('kdkotama') ? ' has-error' : '' }}">
<select class="form-control" name="kdkotama" id="kdkotama">
<option value="">---- Pilih Kotama----</option>
#foreach($tkotam as $tkotam)
<option value="{{$tkotam->kdkotama}}">{{$tkotam->nmkotama}}</option>
#endforeach
</select>
#if ($errors->has('kdkotama'))
<span class="help-block">
<strong>{{ $errors->first('kdkotama') }}</strong>
</span>
#endif
</div>
<div class="form-group has-feedback{{ $errors->has('kdsatker') ? ' has-error' : '' }}">
<select class="form-control" name="kdsatker">
<option value="">---- Pilih Satker ----</option>
</select>
#if ($errors->has('kdsatker'))
<span class="help-block">
<strong>{{ $errors->first('kdsatker') }}</strong>
</span>
#endif
</div>
My javascript is like this :
<script>
$(document).ready(function() {
$("#kdkotama").change(function() {
console.log($("#kdkotama").val());
$.getJSON("../dropdowns/satkers/" + $("#kdkotama").val(), function(data) {
var $satkers = $("#kdkotama");
$satkers.empty();
$.each(data, function(index, value) {
$satkers.append('<option value="' + index +'">' + value + '</option>');
});
$("#kdkotama").trigger("change"); /* trigger next drop down list not in the example */
});
});
});
</script>
My routes/web is like this :
Route::get('dropdowns/satkers/{id}', 'DropDownController#getSatkers');
My controller is like this :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\TSatkr
class DropDownController extends Controller
{
public function getSatker($id)
{
$satkers = TSatkr::where('kdkotama', '=', $id)->get();
$options = array();
foreach ($satkers as $satker) {
$options += array($satker->kdsatkr => $satker->nmsatkr);
}
return Response::json($options);
}
}
I added this: console.log ($ ("# kdkotama"). val ()); in javascript. when I select kotama, the results of console.log that appear. but in the console, it did not succeed in calling controller. whereas the code, it looks like it is correct
is there anyone who can help me?
I faced so many problem to generate dynamic drop-down but now I do like this which is more powerful and useful to set dynamic drop-down value.
Lets generate DOM using method which can help us to generate dynamic DOM with one truth or source..
//Controller/HelperController.php
class HelperController
{
public static function ajaxDynamicDropDown($changeDropdown, $replaceDropdown, $url, $empty = []) {
$html = '<script type="text/javascript">';
$html.='jQuery(document).ready(function($) {';
$html.='jQuery("select[name=\'' . $change_dropdown . '\']").change(function(e){';
$html.='jQuery.ajax({';
$html.='type: "'.$action_type.'",';
$html.='url: "' . $url . '",';
$html.='dataType:"json",';
$html.='data: jQuery(this).parents("form").find("input,select").not("[type=hidden][name^=_]").serialize(),';
$html.='success:function(data){';
$html.=' jQuery("select[name=\'' . $replace_dropdown . '\']").find("option:not(:first)").remove();';
if (!empty($empty)) {
foreach ($empty as $key => $emt) {
$html.=' jQuery("select[name=\'' . $emt . '\']").find("option:not(:first)").remove();';
}
}
$html.=' jQuery.each(data, function(key,value){';
$html.=' jQuery("select[name=\'' . $replace_dropdown . '\']").append(\'<option value="\'+key+\'">\'+value+\'</option>\');';
$html.='});';
$html.='}';
$html.='});';
$html.='});';
$html.='});';
$html.='</script>';
return $html;
}
}
Benefit of it is I don't have to write change event for each dropdown. Also no need trigger.
// Blade File:
{!! Form::select('country_id',['1'=>'Test 1','2'=>'Test 2'],null,[]) !!} // First Dropdown with value
{!! Form::select('state_id',[],null,[]) !!} // Second Dropdown will set based on first one.
<script type="text/javascript">
{!! HelperController::ajaxDynamicDropDown('country_id','state_id',URL::to('ajax/states'),['state_id','city_id']) !!}
</script>
Now I am going to use implicit route controller. Using that I get controller methods based on the HTTP request type and name.
Mean in ajax if I used POST method request then in my controller my method name will be like postState() or if GET request then same getState(). For more please click here
//routes.php
Route::controller('ajax', 'AjaxController');
Here is code sample of AjaxController
// AjaxController.php
class AjaxController
{
public function postState()
{
// of course here I get Input by using request()->get('input_name')
return ['1'=>'test'];
}
}
Also you can set old value when validation going false with old() in AjaxController.
You can also use it for multiple dependencies like state if came from country now it can be possible you need to get city from state same method you can use for it..

Stop a For Loop From Repeating in AngularJS

I'm trying to replace some html code with Javascript when a user searches for an email. I have it working correctly, but for some reason the error displays around 20+ times, so it will replace the div and say
"user does existuser does existuser does existuser does existuser does existuser does exist"
instead of just putting the error message once. Any idea how I can fix it?
$scope.checkEmail = function
findUsersMatchingEmail(emailAddress) {
ref.child('users').orderByChild('email').
equalTo($scope.emailAddress).once('value', function (snap) {
var output = '<div>',
myError = document.querySelectorAll('#d');
for (var key in arguments[0]) {
output += (snap.name() +
(snap.val() === null ? ' Does Not' : ' does') + ' exist');
}
output += '</div>';
for (var i = myError.length - 1; i >= 0; i--) {
myError[i].innerHTML = output;
}
});
};
As I wrote in the comments, never manipulate the DOM from anywhere but the link function of a directive. Explaining why is probably out of scope for this answer, and has been answered multiple times here on SO. A very good read is:
“Thinking in AngularJS” if I have a jQuery background?
and A Conceptual Introduction to AngularJS
So to make it short, here's a very simple demo of how you could handle your error messages.
Note that this is by no means the only nor the best way to do it. There's ngMessages or form validation in general which could be used as well.
(function (app) {
'use strict';
app.controller('EmailCtrl', ['$scope', function ($scope) {
$scope.errors = [];
$scope.checkEmail = function findUsersMatchingEmail(emailAddress) {
// clear previous errors
$scope.errors.length = 0;
// check email and add errors if needed
// using your service (ref)
$scope.errors.push({
message: 'email not unique ' + (Math.random()) // random is only used to show that the errors actually change
});
};
}]);
})(angular.module('app', []));
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<div data-ng-app="app" data-ng-controller="EmailCtrl">
<ul>
<li data-ng-repeat="error in errors">{{ error.message }}</li>
</ul>
<form data-ng-submit="checkEmail(email)">
<input data-ng-model="email" placeholder="email">
</form>
</div>
Side note: I would normally use the controller as syntax, though I did not want to introduce any more new topics.

How do i get a value from Kendo UI template

I have this template:
var template = kendo.template("<div class='relatedItemRow'>"
+ "<span id='relatedItemName'>Related Item #: Number #</span>"
+ "<div class='relatedItemRowInfo'><span >#: Name #</span>"
+ "<a data-relatedItemID='#: Value #' class='removeRelatedItem'>"
+ "<img src= '#: Img #'/</a></div><br class='clear'/></div>");
var data = {
Name: "" + checkbox.getAttribute('flatName'),
Number: $('#relatedItemsList').children().length + 1,
Img: '/Content/images/x_remove.png',
Value: checkbox.value
};
var result = template(data);
$("#relatedItemsList").append(result);
I am able to access the data-relatedItemID by using:
$('#relatedItemsList').children().eq(i).children().last().attr('data-relatedItemID')
But how do I get to the Number field in data? I want to change that one dynamically.
I have tried:
$('#relatedItemsList').children().eq(i).children().attr('Number') == 5
but it does not work. Any idea how to do that?
I know that there is an answer for this question even accepted but I'd like to suggest a different approach that I think it is much simpler and more Kendo UI oriented and is using Kendo UI ObservableObject. This allows you to update an HTML that is bound to the ObservableObject without having to crawl the HTML.
This approach is as follow:
Wrap your data definition with a Kendo Observable Array initialization.
Redefine your template and start using using data-binding.
Append this new template to your HTML.
Bind data to the HTML.
Now you can get current value using data.get("Number") or set a new value using data.set("Number", 5) and the HTML get magically updated.
The code is:
Template definition
<script type="text/kendo-template" id="template">
<div class='relatedItemRow'>
<span id='relatedItemName'>Related Item <span data-bind="text : Number"></span></span>
<div class='relatedItemRowInfo'>
<span data-bind="html : Name"></span>
<a class='removeRelatedItem' data-bind="attr: { data-relatedItemID : Value }">
<img data-bind="attr : { src : Img }"/>
</a>
</div>
<br class='clear'/>
</div>
</script>
data definition as:
var data = new kendo.data.ObservableObject({
Name: "" + checkbox.getAttribute('flatName'),
Number: $('#relatedItemsList').children().length + 1,
Img: '/Content/images/x_remove.png',
Value: checkbox.value
});
and the initialization of the HTML is:
$("#relatedItemsList").append($("#template").html());
Getting current value of Number is:
var old = data.get("Number");
Setting is:
data.set("Number", 5);
Running example in JSFiddle here : http://jsfiddle.net/OnaBai/76GWW/
The variable "result" and thus the data you're trying to change aren't a Kendo templates, they're just html created by the template, and the number is just text in the html. To modify the number without rebuilding the whole string, you need to change the template so you can select the number by itself with jQuery by putting it in it's own element, and adding something to identify it.
var template = kendo.template("<div class='relatedItemRow'><span id='relatedItemName'>Related Item <span class='relatedNumberValue'>#: Number #</span></span><div class='relatedItemRowInfo'><span >#: Name #</span><a data-relatedItemID='#: Value #' class='removeRelatedItem'><img src= '#: Img #'/</a></div><br class='clear'/></div>");
//other code the same
And once you can select it, then you can change it like this.
$('#relatedItemsList').children().eq(i).find('.relatedNumberValue').text(5);
And retrieve it like this.
var foo = $('#relatedItemsList').children().eq(i).find('.relatedNumberValue').text();

Categories

Resources