how to put laravel echo function in javascript - javascript

How to use echo in strings in javascript datatable
className:'text-center',
data:'stage',
name:'stage',
render: function(data)
{
return '<td class="text-center">{{trans('stage.'' + data.stage + ')}}</td>';
}
error: syntax error, unexpected ''+ data.stage +'' (T_CONSTANT_ENCAPSED_STRING), expecting ',' or ')'
I have tried escaping using backlash it still doesnt look right.
<td class="text-center">{{trans('stage.'.$sub->stage)}}</td>
//this is what i want to display if i were to use laravel blade

Blade is rendered before you hit the page. So you cannot do what you're trying to, like this. I would recommend using xDebug to see how this works more consistently
If you want to include a translated variant of text in the variable stage, you either need to fetch some HTML and pass it back rendered, via an ajax request for example
OR
You can write/use a javaScript helper which will translate text for you.
OR (best)
You can write an accessor/getter on stage which will translate it before it's received by your DataTable
This would mean writing the following on the Model where the attribute stage comes from. Please note, prefixed Method name with 'get' and 'Attribute' as the suffix.
public function getStageAttribute()
{
return trans($this->stage);
}
For more information please see https://laravel.com/docs/8.x/eloquent-mutators#defining-an-accessor

Related

How to change : Fullcalendar generates GET request

I am implementing fullcalendar on my website.
I have created a div with calendar as id.
I have put data from a SQL query in a php variable and used json encode to get the right format.
This is how I create the calendar :
$html .= "<script src='/wp-content/plugins/biobelt/moment.min.js'></script>
<script src='/wp-content/plugins/biobelt/fullcalendar.min.js'></script>
<link rel= 'stylesheet' href='/wp-content/plugins/biobelt/fullcalendar.css' type='text/css'>
<script>
jQuery(document).ready(function() {
var bevents = '".$buildingevents."'
console.log(bevents)
jQuery('#calendar').fullCalendar({
defaultDate: '" . $_SESSION['statDateFrom'] ."',
editable: true,
events: bevents,
});
});
</script>";
The console log gives me an output of the array that I am passing to events, and it is the correct format :
[{"id":"1","titre":"1","start":"2018-04-09 07:00:01","stop":"2018-04-09 11:00:00"},{"id":"2","titre":"1","start":"2018-04-09 07:00:01","stop":"2018-04-09 11:00:00"},{"id":"3","titre":"2","start":"2018-04-09 16:00:01","stop":"2018-04-09 21:00:00"},{"id":"4","titre":"2","start":"2018-04-09 16:00:01","stop":"2018-04-09 21:00:00"}, etc...
What I get from this is :
GET 403 Forbidden Error
I checked in apache logs, this is because the URL is too long since every field of the array is put into the url.
For some reason I don't want to change the limit request line in apache conf file.
I want to generate a POST instead of GET request.
And I would like to know how it generates a GET request since I didn't put GET anywhere in my files.
EDIT :
according to : https://fullcalendar.io/docs/events-json-feed
Fullcalendar create the get request and the URL. The problem persists since the URL is too long and I want to create a POST request instead. How to do that?
You seem to have misunderstood the documentation somewhat.
You said
The console log gives me an output of the array that I am passing to events, and it is the correct format
And indeed what you've showed does look like a Javascript array. So...it's a static array and not a URL. You do not have any kind of server endpoint to which you can make a separate ajax call to get your events. Therefore the article you linked to (https://fullcalendar.io/docs/events-json-feed) is not relevant. Instead you are providing a static list of events as per the method described at https://fullcalendar.io/docs/events-array).
Except that...you're not. Due to the way you've written your code, you're providing a string instead of an array. That is causing fullCalendar to assume you're providing a URL, and then trying to call that URL, and it's no surprise that it errors.
If you simply remove the single quotes from
var bevents = '".$buildingevents."'
so that it becomes
var bevents = ".$buildingevents.";
then your code should work ok, because this will inject a hard-coded array into the JavaScript instead of a string.

Html Encode Ionic 2 + API PHP quotes errors

My api returns a string of html in which I convert to html with php with the function:
[API ENCODE HTML, IF NOT IS RENDERIZE AS STRING ]
$description = html_entity_decode($description)
After this Json_encode
And return this value to the Ionic 2 app.
In which I take this item and show with:
[APP HTML RECEIVE WITH NO TRAITAMENT IN INNERHTML TO SHOW DESCRIPTION]
<div class="item item-text-wrap" [innerHTML]="item.description"></div>
But some items use as a tooltip in the tag:
<span title="Auxiliary content open per click">click</span>
However, some content breaks due to double quotation marks.
title=" table rowspan="2"></table "
How could I add slashs or a rendition of that html inside the title without breaking it by the quotation marks.
I've already tried modifying your content in the API, but I have not yet been able to render this html.
Is there a way to do this by ionic 2? as ?
Is there a way to do it with regex in php to modify the title only?
Thanks for the help, and sorry for my bad english.
Not result any erros;
Test for the response 1:
let description = this.item.descricao;
this.descricao = description.replace(/'/g, '"');
You can replace your "" with ' as shown below using Javascript/TS.
var result = yourString.replace(/'/g, '"');
I changed my API PHP to create a json file, every time updated content with CKeditor, I override file make.json.
When app request my API, he read this file like this:
public function make(){
if(file_exists("web/uploads/make/make.json")){
$make = file_get_contents('web/uploads/make/make.json');
echo ($make);
}else{
return false;
}
die;
}
So, Thank for help me.

PHP $_GET and underlines

I have a very short piece of PHP that I use to make HTTP requests from JavaScript.
<?php echo file_get_contents($_GET['url']); ?>
I have used it successfully in a few projects, but am running into a problem with making requests in my current project. Based on my searching, I believe it may be caused by the underscore in the request, though through my searching and not knowing PHP, I have not been able to confirm that.
Below is an example of what I am doing from JavaScript:
$.get("grabber.php?url=" + "http://tidesandcurrents.noaa.gov/api/datagetter?station=8573364&begin_date=20160202&end_date=20160203&product=predictions&units=english&time_zone=gmt&format=json&application=poseidonweathercom+&datum=MLLW", function(forecast) {
console.log(forecast);
});
If I copy the url and put in it in a browser, I get back the JSON that I requested. When I use the code above, I end up getting an error message from NOAA:
Wrong Product : Product cannot be null or empty Wrong Time zone: Time zone cannot be null or empty Wrong Unit:Unit cannot be null or empty Wrong Format: Format cannot be null or empty Wrong Date: The beginDate cannot be null or empty
Do I need to use a regex for the underscore in PHP? Is there some other issue that I do not understand?
Thanks.
You need to send it encoded, which will convert all the underscores/spaces/ampersands etc. with their encoded equivalents:
var url = "http://tidesandcurrents.noaa.gov/api/datagetter?station=8573364&begin_date=20160202&end_date=20160203&product=predictions&units=english&time_zone=gmt&format=json&application=poseidonweathercom+&datum=MLLW";
$.get("grabber.php?url=" + encodeURIComponent(url), function(forecast){
console.log(forecast);
}
Using encodeURIComponent() on that URL shows:
http%3A%2F%2Ftidesandcurrents.noaa.gov%2Fapi%2Fdatagetter%3Fstation%3D8573364%26begin_date%3D20160202%26end_date%3D20160203%26product%3Dpredictions%26units%3Denglish%26time_zone%3Dgmt%26format%3Djson%26application%3Dposeidonweathercom%2B%26datum%3DMLLW
Alternatively, if you just want to access the JSON data and handle it within the JavaScript function, you can retrieve the data via the URL directly, without having to encode the URL:
$.get("http://tidesandcurrents.noaa.gov/api/datagetter?station=8573364&begin_date=20160202&end_date=20160203&product=predictions&units=english&time_zone=gmt&format=json&application=poseidonweathercom+&datum=MLLW", function(forecast) {
console.log(forecast);
});
Um why do you even need your php code ... the code below will work just fine and eliminate your server overhead.
$.get("http://tidesandcurrents.noaa.gov/api/datagetter?station=8573364&begin_date=20160202&end_date=20160203&product=predictions&units=english&time_zone=gmt&format=json&application=poseidonweathercom+&datum=MLLW", function(forecast) {
console.log(forecast);
});

Double Quotes Break HTML Attributes and JS

So I have some ajax requests that pull data from our product pages. These product pages can have a " (double quote) in their URL somewhere. This is a necessary evil, I'd explain why, but please just accept that I have to keep the double quotes in these URLs.
In a nutshell, I am pulling stuff from an Excel XML file, then conducting ajax requests with Javascript/jQuery that pull text and data from "Product Pages" and then displaying that stuff on a "Product Listings" page. Again, the URLs of these "Product Pages" sometimes have double quotes in them.
Moving on, these ajax requests are called via a function and the data obtained is returned and utilized by a callback. These functions have worked great until recently when we discovered that " (double quotes) are breaking the functions. These double quotes are being passed in the url variable to these AJAX requests. I have read a bunch of other posts mentioning quotes breaking their scripts, but many have found solutions, and I have not been able to.
I even tried var href = encodeURI( $(this).text() ); and var href = encodeURIComponent( $(this).text() );. These don't seem to fix the issue. Before I go on, let me show you my script.
XML
<Worksheet ss:Name="Recommended">
<Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="5" x:FullColumns="1"
x:FullRows="1" ss:DefaultRowHeight="15">
<Column ss:AutoFitWidth="0" ss:Width="96.75"/>
<Row ss:AutoFitHeight="0">
<Cell><Data ss:Type="String">/2U-12"-Economy-Rack-Shelf-KH-3000100202/</Data></Cell>
</Row>
</Table>
</Worksheet>
JS
$(this).find('Data').each(function(){
var href = $(this).text();
// This is where the 'url' is getting it's value from the 'href' variable
// that is being pulled from the XML file 'Data'
getProductData('name', href, function(val) {
console.log(val);
});
});
// Get data from the product page anywhere (Global)
function getProductData(type, url, callBack) {
$.ajax({
url: url,
method: 'GET',
dataType: 'html',
success: function(data){
var $data = $(data).find('#product-data');
var val = $data.data(type);
return callBack( val );
},
error: function(data) {
console.error( 'getProductData: ' + type + ' = FAIL / URL: ' + url );
}
});
}
HTML
<input type="hidden" id="product-data" data-name="{product['product_name']}">
Any ideas on how I can get these double quotes to work with my script? It seems there is very little on the subject available... I haven't had this issue in all my years in development :(
I just cannot get the quotes (that are actually coded as " in the XML file) to encode properly when the AJAX request uses this string as the url parameter...
The outcome of the above is my getProductData() simply does not return anything. This same function returns data just fine when the url variable does not contain double quotes in the string...
EDIT
I have also tried var href = $(this).text().replace('"', '\"'); btw.
EDIT So I mis-diagnosed my issue. The AJAX requests were working, the values being returned were just corrupted by the quotes. So, the issue was that the quotes made attributes break apart in my HTML, the AJAX requests were doing okay.
I am renaming the post to better label the issue I was having. Sometimes, it's the most basic things that break our stuff right?
You can't put strings with double quotes inside an attribute that is itself enclosed by double quotes. While I do not know what technology you're using to set the value of the data-name attribute, whatever you're using must convert the double quote to ". In PHP you would use the htmlspecialchars function. With JavaScript you could use .replace(/"/g,"&quot");
The end result should look like this
<input type="hidden" id="product-data" data-name="2U-12"-Economy-Rack-Shelf-KH-3000100202"
So ultimately what I had to do was:
Change the the double quotes in my HTML to single quotes
Use var href = encodeURI( $(this).text() ); when passing the href variable to getProductData()
I could have also used .replace('"', '&quote') on the data-name value to resolve the issue as well, but I don't like using javascript unless absolutely necessary... It would be cleaner IMo, but yeah...

Angular $http.get query returning html data doesn't display as normal html.. Instead it display as text in website ..

Basically my problem is that when i fetch data using $http.get method of the AngularJS , the Json encoded data which is printed by the PHP doesnt render in the website instead it shows as plain text.. for ex when PHP prints <h3 class=\"someclass\">Hello World<\/div>" and also simultaneously i try to parse the JSON using JSON.parse but it gives me Syntax Error: Unexpected token o . Basically the received HTML markup is not rendered.. Its just as plain text..
See below:
The h3 tag that i rectangled in black doesn't render in the page. Even in the source you can see its not as a markup but as a plain text.
There is a pretty good answer on escaping/not escaping HTML in angular here: https://stackoverflow.com/a/19417443/402551
It is a security feature that text injected into the DOM is not parsed as HTML, which saves you against some XSS attacks and the like. You have to manually ensure that it is rendered, so you need to think about the security implications yourself. Please familiarize yourself with XSS mechanisms and sanitize your input, before you bypass the escaping.
In general, Angular is designed in a way that you do not render any HTML server-side, just supply your frontend with the data and render there. This way, you won't have most of these problems. Please review, whether you can change that in your project.
Use ng-bing-html to escape HTML content from the response,
While getting the response do as below,
$scope.temp_variable=$sce.trustAsHtml(response);
In your HTML display the value like this,
<div>
<span ng-bind-html="temp_variable"></span>
</div>
To print an html data, Ned to include sanitize Module first
http://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-sanitize.js
Then create a filter
Rapp.filter('unsafe', function($sce) {
return function(val) {
return $sce.trustAsHtml(val);
};
});
Then write the html as shown below
<span ng-bind-html="myWelcome | unsafe"></span>

Categories

Resources