How to add live search function into Laravel - laravel

I have Japan postal zip code live search function. It works at my xampp. I tried to add this into Laravel app but the search doesn't work.
Here is my whole code which works at XAMPP.
https://jsfiddle.net/blueink/rnsftzg8/
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="//jpostal-1006.appspot.com/jquery.jpostal.js"></script>
<script type="text/javascript">
$(window).ready( function() {
$('#postcode').jpostal({
postcode : [
'#postcode1'
],
address : {
'#address1' : '%3',
'#address2' : '%4',
'#address3' : '%5',
'#address1_kana' : '%8',
'#address2_kana' : '%9',
'#address3_kana' : '%10'
},
trigger : {
'#address1_kana' : true,
'#address2_kana' : true,
'#address3_kana' : false
}
});
$("#address1_kana").on("change", function() {
var val = $("#address1_kana").val();
val = "onchange_" + val;
$("#address1_kana_onchange").val(val);
});
$("#address2_kana").on("change", function() {
var val = $("#address2_kana").val();
val = "onchange_" + val;
$("#address2_kana_onchange").val(val);
});
$("#address3_kana").on("change", function() {
var val = $("#address3_kana").val();
val = "onchange_" + val;
$("#address3_kana_onchange").val(val);
});
});
</script>
What I tried is ...
First I save all js into public/js folder but it didn't work. So
I simple save js file app.blade.php which is header.
Then I save html code into index.blade.php.
I'm wondering why it works at xampp only?
Could you teach me what I missing please?

You can do it like so (depending on your Laravel version, mine is 5.7) :
First, create a route in the "routes" folder like this :
Route::get('test', 'TestController#test')->name('test');
You will be able to access to this road in the /test URL.
In your TestController.php file (usually in app/Http/Controllers), create a method :
public function test(){
return view('test');
}
Then, in resources/views, create a file named test.blade.php
In this file, put the HTML part of this fiddle:
https://jsfiddle.net/dayLkp4s/
After that, you can split header, footer, scripts parts in other files to use them elsewhere.
Useful resources
https://laravel.com/docs/5.7/blade

Related

How to connect to existing sqlite database in phonegap

I use phonegap for create an android application.
I did these steps :
1. Wrote html, css and jquery mobile codes.
2. Include phonegap.js into .
3. Create the database via sqlite manager firefox extension and copy to root the project directory (beside index.html).
4. use this code:
<script>
$(function() {
onDeviceReady();
queryDB();
$("#links").niceScroll();
});
</script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady()
{
var db = window.openDatabase("shia.sqlite", "1.0", "shia", 100000);
}
function queryDB(tx) {
tx.executeSql('SELECT * FROM posts', [], querySuccess, errorCB);
}
function querySuccess(tx, results) {
console.log("Returned rows = " + results.rows.length);
// this will be true since it was a select statement and so rowsAffected was 0
if (!results.rowsAffected) {
console.log('No rows affected!');
return false;
}
// for an insert statement, this property will return the ID of the last inserted row
console.log("Last inserted row ID = " + results.insertId);
}
function errorCB(err) {
alert("Error processing SQL: "+err.code);
}
</script>
This error displayed into console :
Uncaught TypeError: Cannot read property 'executeSql' of undefined
Please help me .
#Behzad,
your code has the function
function queryDB(tx) {
tx.executeSql('SELECT * FROM posts', [], querySuccess, errorCB);
}
However, when you call queryDB, you did not pass the handle. So in this function the parameter tx is null because you did not pass the handle.

How can I clean this code up better?

I have a script inserted into Magento and it does not seem to be behaving properly. Whenever it runs it actually feeds the contents of the html document back into the text box rather than the autosuggestion. Can anyone tell me what the issue seems to be? I think it might be the two functions conflicting, is there a good way to clean this up?
<script type="text/javascript" src="jquery-2.1.1.js"></script>
<script type="text/javascript" src="jquery.autocomplete.js"></script>
<script type="text/javascript" >
//<![CDATA[
$j = jQuery.noConflict();
$j(document).ready(function(){
$j("#antique_toys_materials").keyup
(function()
{
var tag= $j(this).val();
if(tag!='')
{
$j.ajax(
{
type: "GET",
url: "autocomplete.php",
data: "q=" + tag,
cache: true,
success: function(result)
{
$j("#antique_toys_materials").val(result);
}
}
);
}
return false;
}
);
}
);
//]]>
</script>
<script type="text/javascript" >
//<![CDATA[
$j = jQuery.noConflict();
$j(window).load(function(){
function calculate()
{
var values = [
$j("#cost").val(),
$j("#shipping_paid").val(),
$j("#tax_paid").val()
];
var percent_value = $j("#our_markup").val();
//---------------------------//
if (percent_value == 285)
{
var percent_value = 0;
}
var sub_total = eval( values.join('+') );
var total = eval("sub_total+(sub_total * percent_value)");
var shortened_total = total.toFixed(2);
$j("#price").val(shortened_total);
}
$j( document ).ready(function() {
$j(document).on('input', 'input', calculate);
$j(document).on('change', 'select,input', calculate);
});
});
//]]>
</script>
and it hooks up with this
<?php
$q=$_GET['q'];
$my_data=mysql_real_escape_string($q);
$mysqli=mysqli_connect('localhost','XXXXXXX','XXXXXXX','XXXXXXX') or die("Database Error");
$sql = "SELECT DISTINCT auto_complete_suggestions FROM auto_complete WHERE auto_complete_suggestions LIKE '%$my_data%'
ORDER BY CASE WHEN auto_complete_suggestions = '$mydata' THEN 0
WHEN auto_complete_suggestions LIKE '$mydata%' THEN 1
WHEN auto_complete_suggestions LIKE '%$mydata%' THEN 2
WHEN auto_complete_suggestions LIKE '%$mydata' THEN 3
ELSE 4
END, auto_complete_suggestions LIMIT 0,1";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error());
if($result)
{
while($row=mysqli_fetch_array($result))
{
echo $row['auto_complete_suggestions']."\n";
}
}
?>
It works fine in isolation without the noConflict but then when I put it in Magento it seems to need some help and I'm sure that since it's feeding the html file back into it that something's wrong.
Thoughts? Thanks!
This is just a quick guess, but try using the word "jQuery" instead of "$". I had to change a few plugin scripts that interfered with prototype since it too uses the "$". Once I replaced all instanced of $ with the word jQuery, things started working as I expected.

Displaying uploaded files from server in dropzone js

I am using the dropzone js plugin to upload files to a php server. It is working great. I am facilitating the user to update the uploaded files. So once the user clicks on update button, the dropzone appears, and I am able to display the uploaded files in it through a JQuery-AJAX call. But my problem is that though the files are displayed in the thumbnail format, the number of files in the dropzone counts to zero. I feel that the accept function is not being triggered.But if a new file is added to the displaying list the file count is 1 though there are files already existing in it.
I am using the following code to display the files in dropzone:
var mockFile = { name: "Filename", size: 12345 };
myDropzone.options.addedfile.call(myDropzone, mockFile);
myDropzone.options.thumbnail.call(myDropzone, mockFile, "/image/url");
Can anyone help me solve this?
I think you need to push the mockFile in the dropZone manually like this
myDropzone.emit("addedfile", mockFile);
myDropzone.emit("complete", mockFile);
myDropzone.files.push(mockFile);
It's work for me... if you need more code just ask!
Mock file is not uploaded as explained here https://github.com/enyo/dropzone/issues/418
If you want to submit the form use myDropzone.uploadFiles([]); in init()
$('input[type="submit"]').on("click", function (e) {
e.preventDefault();
e.stopPropagation();
var form = $(this).closest('#dropzone-form');
if (form.valid() == true) { //trigger ASP.NET MVC validation
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
} else {
myDropzone.uploadFiles([]);
}
}
});
example for U!
jQuery(function($) {
//文件上传
$(".dropzone").dropzone({
url : "pic_upload.jsp?id=<%=request.getParameter("id")%>",
addRemoveLinks : true,
dictRemoveLinks : "x",
dictCancelUpload : "x",
maxFiles : 5,
maxFilesize : 5,
acceptedFiles: "image/*",
init : function() {
//上传成功处理函数
this.on("success", function(file) {
alert("修改前:"+file.name);
});
this.on("removedfile", function(file) {
alert("File " + file.name + "removed");
//ajax删除数据库的文件信息
$.ajax({
type:'post',
url:'pic_delete.jsp?id='+file.name ,
cache:false,
success:function(data){
}
});
});
<%
if(null!=list){
for(PlaceImg img:list){%>
//add already store files on server
var mockFile = { name: "<%=img.getId()%>", size: <%=img.getFilesize()%> };
// Call the default addedfile event handler
this.emit("addedfile", mockFile);
// And optionally show the thumbnail of the file:
this.emit("thumbnail", mockFile, "<%=img.getImgUrl()%>");
<%}
}%>
}
});

Loading "knockout.mapping" plugin using require.js

I am creating an MVC3 application, with requireJS. In my views I need to convert the Model object into a knockout viewmodel object. So I need to use knockout and knockout.mapping libraries.
My application is designed in the following way,
1). All the script files are categorized into folders
Scripts/app/home/ - contains the scripts for the views in Home controller.
Scripts/lib/ - contains the scripts like jQuery, knockout,knockout.mapping, requirejs etc
2). In the "_Layout.cshtml" I am referencing "require.js" like this.
<script src="#Url.Content("~/Scripts/lib/require.js")" type="text/javascript"></script>
3). To configure the require.js settings I am using a different script file called "common.js" (Scripts/lib/common.js)
require.config(
{
baseUrl: "/Scripts/",
paths:{
jquery: "lib/jquery-2.0.3",
ko: "lib/knockout-2.3.0",
komapping: "lib/knockout.mapping"
}
});
4). This is my index.js file which is in 'Scripts/app/home/"
define(['ko', 'komapping'], function (ko, komapping) {
var person = function () {
var self = this;
self.getPersonViewModel = function (data) {
return ko.mapping.fromJS(data); ;
};
};
return { Person: person };
});
5). This is my "Index" action method in the "Home" controller
public ActionResult Index()
{
var person = new Person
{
Id = 1,
Name = "John",
Addresses = new List<Address>(new[]{new Address{Country = "Country 1", City = "City 1"}})
};
return View(person);
}
6). Finally this is my "Index" view
#model MMS.Web.Models.Person
<script type="text/javascript">
require(["/Scripts/common/common.js"], function () {
require(["app/home/index"], function (indexJS) {
var person = new indexJS.Person();
var vm = person.getPersonViewModel(#Html.Raw(Json.Encode(Model)));
});
});
</script>
The problem which I am facing is when loading the index.js file, I get a script error that the knockout.js cannot be loaded.
Failed to load resource: the server responded with a status of 404 (Not Found) - http:///Scripts/knockout.js
But if I remove the dependency of "komapping" inside the "index.js" file it loads correctly, but then I cannot use the mapping functionality.
I had a look inside these links, but couldn't find a solution,
Knockout.js mapping plugin with require.js and
https://github.com/SteveSanderson/knockout.mapping/issues/57
Your help, suggestions are much appreciated. Thanks!
I had the same issue. The problem is that the knockout.mapping defines a knockout dependency, so you need to satisfy this one when you load the script.
Here is how you should load your mapping stuff
require.config(
{
baseUrl: "/Scripts/",
paths:{
jquery: "lib/jquery-2.0.3",
knockout: "lib/knockout-2.3.0",
komapping: "lib/knockout.mapping"
},
shim: {
komapping: {
deps: ['knockout'],
exports: 'komapping'
}
}
});
Then in my case, I use an index.js file with a requirejs call like the following
requirejs(['jquery', 'knockout', 'komapping'], function($, ko, komapping){
ko.mapping = komapping;
//Do other stuff here
});

Load JavaScript when partial is called via ColorBox?

It seems when loading a Razor partial view via ColorBox (not using an iframe), the JavaScript libraries do not initialize properly or it is an artifacte of the partial. If I include the libraries in the parent page, the JavaScript function runs inside the partial jsut fine. I don't see any errors coming from the browser when the library is in the partial, but it is not working. If I move the library (in this case fileuploader.js) outside of the partial and keep the function in the partial it works fine.
Example:
<script src="#Url.ContentArea("~/Scripts/plugins/ajaxUpload/fileuploader.js")" type="text/javascript"></script>
<div id="file-uploader">
<noscript>
<p>
Please enable JavaScript to use file uploader.</p>
</noscript>
</div>
<script>
$(function () {
var fileCount = 0;
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '/Admin/Avatar/AvatarUpload',
debug: true,
params: {
'userId': '#ViewBag.UserId'
},
onSubmit: function (id, fileName) {
fileCount++;
},
onComplete: function (id, fileName, responseJson) {
if (responseJson.success) {
if (createAvatar(responseJson.file, responseJson.imageId)) {
fileCount--;
} else {
fileCount--;
}
} else {
$("span.qq-upload-file:contains(" + fileName + ")").text(responseJson.errorMessage);
fileCount--;
}
if (fileCount == 0) {
.....
}
},
onCancel: function (id, fileName) {
fileCount--;
if (fileCount == 0) {
....
}
}
});
});
<script>
You may want to check whether there are duplicate references to the JavaScript libraries you are using (one in the parent and one in the partial).
This is a common issue and it will not raise any errors whatsoever, but will stop your JavaScript code from executing.
I think this is a time line problem.Before the "Partial View" load(or appending the div) JavaScript try to bind it and fail.So it cannot find a element which is in your Partial View document.I had a problem with like this with "ColorBox".I have found a solution for this problem.For example : When you call GET or POST method ,after the query put a control point like this .For example for binding "colorbox" :
function getMyPartial(partialname) {
var resultDiv = document.getElementById("content");
$.ajax({
type: "GET",
url: partialname,
async: false,
success: function (data) {
resultDiv.innerHTML = "";
resultDiv.innerHTML = data.toString();
}
});
var indd = 0; //This is Control Point
if (partialname == "YourPartialName") {
var yourelementinpartial= document.getElementById("example");
while (!yourelementinpartial) {
indd++;
}
$(".group4").colorbox({ rel: 'group4' }); //binding point
}
}
At the control point, if any of the element in your PartialView document has found it will bind.

Resources