Uncaught ReferenceError: $ is not defined - Laravel 5.5 + Laravel Mix - php

I recently check out my project from SVN. I ran into "Uncaught ReferenceError: $ is not defined" where ever I have used "$" ie; Jquery. I am using laravel mixer to combine the JS and CSS Files.
This is my bootstrap.js
window._ = require('lodash');
window.Popper = require('popper.js').default;
window.tooltip = require('tooltip.js');
try {
window.$ = window.jQuery = require('jquery');
require('jquery-ui-dist/jquery-ui.min.js');
require('bootstrap');
} catch (e) {}
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
//Moment JS
window.moment = require('moment');
//Collect JS
window.collect = require('collect.js');
//Clipboard JS
window.ClipboardJS = require('clipboard');
//Import Toster
window.toastr = require('toastr');
//Swaet Alert
import Swal from 'sweetalert2';
window.swal = Swal;
//Owl Carousel
window.owlCarousel = require('owl.carousel');
//JS Cookie
window.Cookies = require('js-cookie');
//Image Zoom
require('ez-plus');
This is my webpack.mix.js
let mix = require('laravel-mix');
mix.js('resources/assets/js/app.js', 'public/js').sourceMaps()
.sass('resources/assets/sass/app.scss', 'public/css');
My Laravel Version: 5.5.40
laravel-mix Version: 1.7.2

This worked for me:
Remove the defer from the app.js script tag and change window.$ = window.jquery = to global.$ = global.jquery =
Weather or not this is the correct way to do it, this has worked for me.
laravel 5.7

Related

Angular 6 CSV download

I'm new to angular, currently i'm working in a project which needs an csv export. Here i'm using Angular 6 as frontend and laravel as backend
This is how i wrote laravel function using mattwebsite/excel
// Lead export to csv
public function downloadExcel(Request $request)
{
$credentials = $request->only('token');
$token = $credentials['token'];
$userid = $this->getUseridFromToken($token);
$type = "xls";
$data = DB::table('user_mailbox AS A')
->select('A.id', 'A.name', 'A.email', 'A.phone', DB::raw('DATE_FORMAT(A.send_on, "%d / %b / %Y") as send_on'), 'B.listing_heading','B.listing_id','B.listing_heading', 'C.name')
->leftjoin('broker_listing AS B', 'B.listing_id', '=', 'A.listing_id')
->leftjoin('users AS C', 'C.id', '=', 'A.sent_by')
->where('A.sent_to', $userid)
->where('A.user_type', '1')
->orderBy('A.id', 'desc')->get()->toArray();
Excel::create('Lead_Export', function($excel) use ($data) {
$excel->sheet('Lead_Export', function($sheet) use ($data)
{
$sheet->fromArray($data);
});
})->download($type);
}
This is how i wrote function in angular component
// Download leads as excel
download_excel(){
const fd = new FormData();
fd.append('token',this.token);
this.brokerleads.downloadLeads(fd).subscribe(
data => this.handleResponsedwnload(data),
error => this.handleErrordwnload(error)
);
}
handleResponsedwnload(data){ console.log('test');
const blob = new Blob([data], { type: 'text/xls' });
const url= window.URL.createObjectURL(blob);
window.open(url);
}
handleErrordwnload(data){
}
service is like this
// Download as excel
downloadLeads(data):Observable<any>{
return this.http.post(`${this.baseUrl}downloadExcel`, data);
}
view
<a class="export-leads" href="javascript:void(0);" (click)="download_excel()" >EXPORT LEADS</a>
while doing this i'm getting response like this but file is not downloading
You need to navigate the browser to the route where the Excel file is made on the backend (in a new tab) either with a link <a href="path" target="_blank"> or with window.open
The ->download() function sets headers so that the file will be automatically downloaded.
When you fetch this data with an AJAX call (which is what HttpClient does) you simply get the binary data returned (which is what you see in your Response tab in Chrome developer tools).
(There are front-end hacks to download a file retrieved by ajax such as creating a link element and clicking it with JavaScript (see below), but they can not be recommended):
let fileName = 'filename.xlsx';
let a = document.createElement('a');
a.href = window.URL.createObjectUrl(responseData);
a.download = fileName;
a.click();
This can also be done using file-saver:
import * as FileSaver from 'file-saver';
this.http.post(`${this.baseUrl}downloadExcel`, data, { responseType: 'blob' })
.subscribe((resp: any) => {
saveAs(resp, `filename.csv`)
});
This function working for me to export csv,
downloadFile(data: any) {
const replacer = (key, value) => value === null ? '' : value; // specify how you want to handle null values here
const header = Object.keys(data[0]);
let csv = data.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));
csv.unshift(header.join(','));
let csvArray = csv.join('\r\n');
var a = document.createElement('a');
var blob = new Blob([csvArray], {type: 'text/csv' }),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = "myFile.csv";
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}

I'm getting a 406 response error when I try to make a https request (Note: no error when i use just http)

I'm using the cordova file-transfer plugin in order for users to upload pictures within my app.
My code works perfectly when making a normal http request to the php page on my server.
I would like to make a secure request so am trying to use https however I am getting a 406 error (see screenshot for error details)
All other ajax requests I am making within the app are working successfully using https.
I am currently not sending any headers when making the request however there is an option to do this using the file-transfer plugin.
I have looked into how I can solve this error (for example this question here) however am still uncertain as to what I need to do in my case.
I was wondering can you help determine what headers I need?
Here is my code:
Javascript
function uploadProfilePic(){
var token = localStorage.getItem("usertoken");
var defs = [];
var def = $.Deferred();
function win(r) {
if($.trim(r.response) === "0") {
alert("Sorry! We have encountered an error");
def.resolve(0);
}else{
def.resolve(1);
}
}
function fail(error) {
//upload of pic failed.
alert("Sorry! We have encountered an error: " + JSON.stringify(error));
def.resolve(0);
}
var uri = encodeURI("https://www.example.com/update_profile_pic.php");
var options = new FileUploadOptions();
options.fileKey="profile_pic_image_file";
options.mimeType="image/jpeg";
var params = new Object();
params.usertoken = token;
params.app_root_url = app_root_url;
//not sure what headers to add here.
//var headers={'headerParam':'headerValue'};
//options.headers = headers;
options.params = params;
var ft = new FileTransfer();
ft.onprogress = function(progressEvent){
if(progressEvent.lengthComputable){
loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total);
}else{
loadingStatus.increment();
}
};
ft.upload($ESAPI.encoder().encodeForURL(profileImage), uri, win, fail, options);
defs.push(def.promise());
$.when.apply($, defs).then(function() {
//pic uploaded fine
});
}
PHP (upload_profile_pic.php)
header("Access-Control-Allow-Origin: *");
if(isset($_FILES['profile_pic_image_file'])){
$data['profile_image_is_set'] = true;
//do stuff with profile image here
echo json_encode($data);
}else{
$data['profile_image_is_set'] = false;
//image not set
echo json_encode($data);
}

Laravel Echo Cannot set property 'X-Socket-ID' of undefined

I recently upgraded to 5.3 from 5.2.
Last week I installed Laravel Echo, and am using it with Pusher, Vue and Vue-resource.
Everytime I post to my database I get this error
Cannot set property 'X-Socket-ID' of undefined
The doc says if you use Vue and Vue-resource X-Socket-ID is attached to the header automatically, but obviously no in this case
Does anyone got any ideas how to solve this?
Error comes from this code
Vue.http.interceptors.push(function (request, next) {
if (_this.socketId()) {
request.headers['X-Socket-ID'] = _this.socketId();
}
next();
});
main.js
var Vue = require('vue');
window.moment = require('moment');
require("moment/locale/ja.js");
window.Vue = Vue;
Vue.use(require('vue-resource'));
window.Pusher = require('pusher-js');
import Echo from "laravel-echo"
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'my key'
});
Thanks for you help
solved after installing Vue-resource#^0.9.3

Laravel Elixir - run version task from extension

I'd like to make an extension for Laravel Elixir.
In my own extension I need to run an existent Elixir version() task.
How can I do this?
A bit of my code:
// File: elixir-extensions.js
var gulp = require('gulp');
var Elixir = require('laravel-elixir');
var Task = Elixir.Task;
Elixir.extend('recursive', function(dir) {
new Task('recursive', function(dir) {
// Generate files list for versioning...
var files = [];
// ...
// Here I need to run Laravel Elixir version(files) with my files list
});
});

PUT request from Backbone to Slim REST service causes 404 Not Found

I have a backbone script that calls a Slim REST service. GET requests are working fine, PUT requests are returning 404 Not Found. Note: this was working until my code was recently moved to a different server (and it works locally), so I'm guessing it has something to do with an Apache config setting. Here's a snippet of the backbone script:
jQuery(document).ready(function ($) {
//define box model
var Box = Backbone.Model.extend({
url: function () {
var urlId = (this.id) ? this.id : "";
var myUrl = "/wp-includes/api/service.php/box/" + urlId;
return myUrl;
}
});
var BoxView = Backbone.View.extend({
tagName: "div",
template: $("#boxTemplate").html(),
initialize: function () {
this.model = new Box(box);
this.render();
},
saveBox: function(e){
e.preventDefault();
$("#boxMessage").empty();
var formData = {},
prev = this.model.previousAttributes();
$(e.target).closest("form").find(":input").not("button").each(function (){
var el = $(this);
formData[el.attr("id")] = el.val();
});
this.model.set(formData);
this.model.save(
{ },
{
success: function() {
$("#boxMessage").html("Box information saved.");
},
error: function() {
}
}
);
}
Here's a snippet of the Slim REST service:
<?php
require 'Slim/Slim.php';
$app = new Slim();
$app->get('/workouts/:id', 'getWorkout');
$app->put('/box/:id', 'updateEventBox');
$app->run();
function getWorkout($id) {
echo json_encode(GetEventCompetitorWorkout($id));
}
function updateEventBox($id) {
$request = Slim::getInstance()->request();
$body = $request->getBody();
$eventBox = new EventBox(null);
$eventBox->TakeJson($body);
$eventBox->Save();
}
And here's the header info for the request:
Request URL:http://www.mydomain.com/wp-includes/api/service.php/box/1
Request Method:PUT
Status Code:404 Not Found
UPDATE: just tested a POST to the same service and it worked fine. PUT still fails.
I've found it not too uncommon that some servers only have GET,POST,HEAD enabled and that PUT,DELETE which are needed for REST are not enabled. That could be the case.
To test for this you can tell Backbone to use "emulatated HTTP" by calling this before your code:
Backbone.emulateHTTP = true;
This will make backbone use only GET/POST requests however it will append to the querystring "_method=PUT" or "_method=DELETE" which you can use on the serverside to detect the intended HTTP verb.
So on the server side you need to do something like this like as the first line of your index.php file (before any of the framework loads):
if (isset($_REQUEST['_method'])) $_SERVER['REQUEST_METHOD'] = $_REQUEST['_method'];

Categories