I am using AJAX to read a large JSON file (about 15 MB minified), in order to display autocomplete suggestions on a text field.
The problem is that after user types 4 characters in order the suggestions to begin, i have to wait around 20 to 60 seconds which makes actually impossible to use it.
I don't know any techniques how i could make it read the JSON file faster.
I would like to read your suggestions...
My AJAX request is :
$(document).ready(function () {
$("#card").autocomplete({
source: function (request, response) {
$.ajax({
dataType: "json",
data: {
term: request.term,
},
type: 'GET',
contentType: 'application/json; charset=utf-8',
xhrFields: {
withCredentials: true
},
cache: true,
url: base_url+'/test123/wp-content/plugins/trading-collectible-cards/public/js/AllSets.json',
success: function (data) {
var keys = Object.getOwnPropertyNames (data)
var outputArray;
$.each(keys,function(ele, val){
var array = $.map(data[val].cards, function (set) {
return {
label: set.name + " (" +data[val].name + ")",
value: set.name,
text: set.text,
multi: set.multiverseid,
rarity: set.rarity,
setname:keys[ele],
setfull:data[val].name
}
});
if (ele == 0)
outputArray = $.merge([], array);
else {
outputArray = $.merge(outputArray, array);
}
});
response($.ui.autocomplete.filter(outputArray, request.term));
},
error: function (data) {
}
});
},
minLength: 3,
open: function () {
},
close: function () {
},
focus: function (event, ui) {
},
select: function (event, ui) {
$( "#card" ).val( ui.item.label );
$( "#description" ).html( ui.item.text );
}
});
Related
I face the problem to pass primary key value to the dynamic url using Ajax in Django. Thanks for any helps...
below is the JS code for click button's function:
$(function () {
$(".js-create-book").click(function () {
$.ajax({
url: '/supplier/**<int:pk>**/new/',
type: 'get',
dataType: 'json',
beforeSend: function () {
$("#modal-book").modal("show");
},
success: function (data) {
$("#modal-book .modal-content").html(data.html_form);
}
});
});
});
the views.py got the function new_stok() as follows:
def new_stok(request, pk):
supplier = get_object_or_404(Supplier, pk=pk)
form = NewStokForm()
context = {'pk': supplier.pk, 'form': form}
html_form = render_to_string('includes/partial_stok_create.html',
context,
request=request,
)
return JsonResponse({'html_form': html_form})
You can use HTML5 data attributes:
<button class="js-create-book" data-id="{{ supplier.pk }}">Add new</button>
Then in javascript retrieve the attribute:
$(function () {
$(".js-create-book").click(function () {
var data_id = $(this).attr("data-id");
$.ajax({
url: '/supplier/' + data_id + '/new/',
type: 'get',
dataType: 'json',
beforeSend: function () {
$("#modal-book").modal("show");
},
success: function (data) {
$("#modal-book .modal-content").html(data.html_form);
}
});
});
});
It won't go to a new browser tab, is my code wrong?
function getWaterMeterList() {
// alert("ON");
var BillingPeriod = $('#BillingPeriod').val();
$.ajax({
url: '/DataEntryWater/WaterMeterAlphaListReport',
type: 'POST',
data: { 'BillingPeriod': BillingPeriod },
dataType: 'json',
success: function (a) {
$(location).attr('href', a)
a.preventDefault();
},
error: function (err) {
}
});
}
What you're looking for might be:
window.open('http://stackoverflow.com/', '_blank');
And in your code:
function getWaterMeterList() {
// alert("ON");
var BillingPeriod = $('#BillingPeriod').val();
$.ajax({
url: '/DataEntryWater/WaterMeterAlphaListReport',
type: 'POST',
data: { 'BillingPeriod': BillingPeriod },
dataType: 'json',
success: function (a) {
var win = window.open('http://stackoverflow.com/', '_blank')
if(win) {
win.focus(); /if tab is open, change focus there.
}
},
error: function (err) {
// do stuff here
}
});
}
I need validate user's nickname when the gonna registre in my proyect:
My Controller
$inputData = Input::get('nickname');
parse_str($inputData);
$informacion = array('nickname' => $inputData);
$regla = array('nickname'=>'required|unique:usuarios|alpha_num|min:6|max:15');
if($request->ajax()){
$usuarios = Usuarios::Usuarios();
$validar = Validator::make($informacion,$regla);
if($validar->fails()){
return Response()->json(array(
'fail' => true,
'errors' => $validar->getMessageBag()->toArray()));
}
else{
return Response()->json(array('success' => true, "message" => "Nombre de Usuario Disponible"));
}
}
My Script
$( "#validar" ).click(function( event ) {
var dato = $('#nickname').val();
var route = $('#form-sign-up').attr('action');
var tipo = $('#form-sign-up').attr('method');
var token = $('#form-sign-up #token').val();
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: tipo,
dataType: 'json',
data:{nickname: dato},})
.fail(function(data){
$('#nickname-msj').html(data.errors);
$('#nickname-msj').fadeIn();
})
.done(function(data) {
$('#nickname-msj').html(data.message);
$('#nickname-msj').fadeIn();
});
});
.done works, but .fails not, and i need display that information to my user, because so they can know what is the problem, if someone can help me will be great.
I am using Laravel 5.2
Thank you.
The fails function of Ajax is triggered with a code different from 200. So you can return
if($validar->fails()) {
return response()->json($arrayHere, 400); //HTTP 400 error for bad request
}
So, just basically add 400 after your array, inside of json() function. When you don't specify the code, it defaults to 200.
Maybe also change your ajax request ? Or not
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: tipo,
dataType: 'json',
data:{
nickname: dato
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});
OK new at this / long time away from it...
I have a json list created thus:
$.ajax({
url: 'http://www.somewebsite.com/land.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status) {
$.each(data, function(i, item) {
var balance = '<p>' + item.itemm + ' ' + item.amount + ' ' + item.status +
' ' + 'edit' + ' ' +
' delete' +
'</p><hr>';
total2 = total2 + parseInt(item.amount);
$("#mylbl").append(balance);
$("#mylbl5").html(total2);
});
},
error: function() {
output.text('There was an error loading the data.');
}
I'm using this method as I'm using phonegap...I have display items and add items working but want to add in edit and delete functionality...
I'm trying to add edit and delete links on each row (as above) but just cant get it sorted....
Only at delete stage .. and have tried this delete function..
function deleteRecord(id) // Get id of record . Function Call when Delete Button Click..
{
mysql_connect("localhost","454547_yeah","password");
mysql_select_db("454487_mydbdb");
var deleteStatement = mysql_query("DELETE FROM balance WHERE id=?");
db.transaction(function (tx) { tx.executeSql(deleteStatement, id, onError); alert("Delete Sucessfully"); });
}
Any help or pointers greatly appreciated ....I've trawlled the web and found nought that might help...
you can try this one
formDataEdit = {
itemm: $("#itemm"),
amount: $("#amount"),
status: $("#status")
};
$.ajax({
url: 'http://www.somewebsite.com/delete.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
data: formDataEdit,
success: function(data, status) {
alert("Edit successful");
},
error: function() {
output.text('There was an error loading the data.');
}
});
formDataDelete = {
id: $("#id")
};
$.ajax({
url: 'http://www.somewebsite.com/delete.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
data: formDataDelete,
success: function(data, status) {
alert("Delete successful");
},
error: function() {
output.text('There was an error loading the data.');
}
});
html
<b><a onclick="edit(1);">Edit</a> | <a onclick="delete(1);">Delete</a></b>
js
currentPage = {};
currentPage.edit = function(id){ //also can use for delete
alert(id);
};
My code is as follows
jQuery('#calendar').fullCalendar({
weekMode: 'liquid',
events: themeforce.events,
eventRender: function (event, element) {
element.find('span.fc-event-title').html(element.find('span.fc-event-title').text());
}
});
where themeforce.events is a variable containing an encoded url of the json feed a php file - all works well.
I tried replacing events: themeforce.events, with
events: {
url: themeforce.events,
type: 'POST',
data: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
However now the calendar fails to load.
What can I do?
I wanted the start and end times for a post ajax request and it took me a bit of time to work it out.
This might help you:
events: function(start, end, timezone, callback) {
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: {
start: start.format(),
end: end.format(),
custom_param1: 'value 1',
custom_param2: 'value 2',
},
error: function () {
alert('there was an error while fetching events!');
},
success: function(doc) {
var events = [];
$.each(doc,function (index, e) {
events.push(e);
});
callback(events);
}
});
}
You should use extraParams as explained in doc : https://fullcalendar.io/docs/events-json-feed
var calendar = new Calendar(calendarEl, {
eventSources: [
// your event source
{
url: '/myfeed.php',
method: 'POST',
extraParams: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
failure: function() {
alert('there was an error while fetching events!');
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
}
// any other sources...
]
});
Also be sure your feed's url return raw json data array !
Just put "data" instead of "extraParams" in "events"
events: {
url: 'service.php',
method: 'POST',
data: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
failure: function() {
alert('there was an error while fetching events!');
},
}