Auto Complete is Very slow my page is hanging at search time? - javascript

In Below you can see my code . #proname is my text box . Page loading time i will call api and fill data into auto complete source property.
At text entering time it is very slow. beacuse in my table i have 20000 records.
So please give me an alternative solution for this problem.
$.ajax({
type: "GET",
url: serverbase+"Site/GetModels",
contentType: "application/json"
}).done(function (data) {
var src = data.map(function (element) {
return element.name;
});
$("#proname").autocomplete({
source: src
});
});

Further to #Boy With Silver Wings comment, you should probably paginate the response that way you only get back so many records rather than ALL records. This also heaps reduce server load, as well load time for the front end.
To answer your question, autocomplete is requiring for your ajax call to complete before it finishes the request. If you MUST get all results, store the results locally rather than doing an AJAX request everything.
Without knowing what your back-end runs on, I can't really provide you with an example of paginating your data :-)

You should avoid pulling the data in a single request and instead query the data based on the autocomplete request. For instance, take a look at this example:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Remote datasource</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
.ui-autocomplete-loading {
background: white url("images/ui-anim_basic_16x16.gif") right center no-repeat;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#birds" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
log( "Selected: " + ui.item.value + " aka " + ui.item.id );
}
});
} );
</script>
</head>
<body>
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds">
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
</body>
</html>
Described here:
https://jqueryui.com/autocomplete/#remote

Related

How to dispay a page in another domain into my page?

In angular 7 i have created a dummy page , http://localhost:4200/auth/register.
Here i need to display that page http://localhost:4200/auth/register in different domain using jquery,either using load() or other possible methods.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery load() Demo</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$( "#box" ).load( "http://localhost:4200/auth/register", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
});
});
</script>
</head>
<body>
<div id="box">
<h2>Click button to load new content inside DIV box</h2>
</div>
<button type="button">Load Content</button>
</body>
</html>
you can use HTML Tag with
DomSanitizer

Use JQuery to get data from JSON file

Overflow!
I'm currently working on a little application I have to finish for school monday. I didn't have a lot of time to make something big. So I decided, why not retrieve information of Steam's Web Api and get the stats of players.
The url to the steam api:
http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=76561198263871727
The last parameter &steamid= represents the id of the player. Now I have found out how to get the steamid into a variable, but when trying to add the id to the rest of the url (http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=id should be here and fetching the data with the Ajax.getJson method.. It just doesn't work.. I'm for very experienced with JSON btw.. Can someone help me out with this?
My Web Page:
<!DOCTYPE html>
<html lang="en">
<head>
<!--Meta Information-->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--JQuery Mobile-->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<!--FontAwesome-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<!--Custom Styles-->
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div data-role="page" id="index">
<div data-role="header">
<h1>CS:GO Stats</h1>
</div>
<div data-role="main" class="ui-content">
<div class="search">
<label for="search">Enter SteamID:</label>
<input type="search" name="search" id="inputSearch" />
<input type="submit" id="butSearch" data-inline="true" value="Search SteamID">
</div>
<div id="result">
</div>
</div>
</div>
<!--getSteamUserId function-->
<script src="js/getSteamUserId.js"></script>
</body>
</html>
My Javascript Code:
$(document).ready(function() {
$('#butSearch').click(function(event) {
var input = $('#inputSearch').val();
$.getJSON( "http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=" + input, function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "#result" );
});
})
})
Now what I want is to get the stats data from the JSON file into my web page. Would anyone know how to do this? I can also see the JSON is not only a flat JSON file.. Like it has different layers (if that's a good explenation)..
Thanks in advance!
Work with jsonP like here:
$.ajax({
url: url,
dataType: 'JSONP',
type: 'GET',
jsonp: 'jsonp',
success: handler
});
Working example here
I'm not entirely sure about the first part. It gives me an error which after googling led me to "No 'Access-Control-Allow-Origin' header is present on the requested resource" which advises using CORS. Error:
XMLHttpRequest cannot load http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=&76561198263871727. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 400.
Once you have the JSON it's easier. If it's stringified you can turn it into a javascript object with
steamObject = JSON.parse(steamJsonData);
and then navigate through it like a normal javascript object. Cycle through playerstats.stats[i] with a for loop and you can add the data to your page using normal DOM manipulation.

how to pass php array to jquery using ajax [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
help me to retrive the php array using ajax from one page to another
when ever user start input in that text field,at that time only it has to retrive the data from page2 using ajax
<!doctype html> //page1
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
var movies = <?php echo json_encode($varma); ?>; // here i want to pass that php array using ajax
alert(JSON.stringify(movies));
$( "#tags" ).autocomplete({
source: movies
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags"> // input field
</div>
</body>
</html>
<?php //page 2
$varma=array("ActionScript","AppleScript","Java","JavaScript","Lisp","Perl","PHP","Python","Ruby","Scala","Scheme"); //php array
?>
The source attribute can have an URL as value. The URL must render json formated for the plugin.
See http://api.jqueryui.com/autocomplete/#option-source
$( "#tags" ).autocomplete({
source: '/myMovies.php'
});
/myMovies.php
<?php echo json_encode($varma); ?>;
Here is a more generic method to ajax in php.
Construct the php array
$arReturn = array( 'name' => 'AliasM2K' );
header( 'Content-Type: application/json' );
print json_encode( $arReturn );
Perform ajax
$.ajax({
url: 'ajaxPhp.php',
dataType: 'json',
success: function( oData ) {
alert( oData.name );
}
});
<?php
/*
I read your problem and your code also and the suggestion from my side is :
Some how you don't required any second page and doesn't required ajax for all this.
You can autocomplete your textbox with PHP array's values using below successive code..
Do yourself and enjoy.
*/
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<?php
$title_name = array();
$fetch=array("ActionScript","AppleScript","Java","JavaScript","Lisp","Perl","PHP","Python","Ruby","Scala","Scheme"); //php array
foreach ($fetch as $data)
{
array_push($title_name,$data); } ?>
<script>
$(function(){
var availableTags =<?php echo json_encode($title_name)?>;
//PUT TEXTBOX ID here
$( "#tags" ).autocomplete({ source: availableTags });
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags"> // input field
</div>
</body>
</html>

My Javascript Ajax request works in Phonegap index.html but not in any other pages, how can I fix this?

The request I have made works in the index.html file but not in any others which is greatly frustrating. I think it is to do with the onDeviceReady function but I am not sure how to change or fix this?
Here is the separate page (not index.html) code:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0;" />
<script src="cordova-1.8.1.js"></script>
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/load-whites.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>
</head>
<body>
<div data-role="page" id="whites">
<div data-role="header" data-position="fixed">
<h1>White Wines</h1>
</div>
<div data-role="content">
<div data-role="collapsible-set" data-theme="c" data-content-theme="d">
<div id="whites"></div>
</div>
</div>
</div>
</body>
Here is the request that works for the index.html file but not for any other .html files in my phonegap project (Cordova 1.8.1). How could I change it so that it does work? the file below is load-whites.js:
$(document).ready(function(){
$(document).bind('deviceready', function(){
onDeviceReady();
});
function yourCallback(button) {
if (button == 2) {
dataRequest();
}
}
function dataRequest() {
var output = $('#whites').text('Loading white wines and their deta1ils, please wait...');
$.ajax({
url: 'http://localhost/whites.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
output.empty();
$.each(data, function(i,item){
var whites = '<div data-role="collapsible"><h3>'+item.Name+'</h3>'
+'<b>Price:</b> £'+item.Price+'<br />'
+'<b>Vintage:</b> '+item.Vintage+'<br />'
+'<b>Country:</b> '+item.Country+'<br />'
+'<b>Grape:</b> '+item.Grape+'<br />'
+'<b>Alcohol:</b> '+item.Alcohol+'%<br /><br />'
+item.Description+'</p></div>';
output.append(whites);
$('#whites').trigger('create');
});
},
error: function(){
output.text('The Wines could not be loaded at this time.');
navigator.notification.confirm(
'Please check your internet connection. Would you like to retry?',
yourCallback,
'Something went wrong',
'No,Yes'
);
}
});
}
dataRequest();
});
Any help would be greatly appreciated. Thanks again.
I see you are using JQuery mobile. Its possible it could be similar to a problem I had today and JQuery mobile was the culprit. http://jquerymobile.com/demos/1.1.1/docs/pages/page-scripting.html
If you are declaring the Javascript file in the header another page other than the index, it will ignore it. If this is your problem, declare the JS file load-whites.js in the index then..
$( document ).delegate("#PAGENAME", "pageinit", function() {
//do work here
});
Not sure if this is your problem, but could be!

Not printing results from AJAX

I am working on a script to send data to a mysql table and I have it all working properly but the success part of the call, it is not loading my results in to my results column on my page. My code is below.
Any suggestions on what I can do to fix that? I am guessing the problem is within my "success:" option in my AJAX call.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Facebook like ajax post - jQuery - ryancoughlin.com</title>
<link rel="stylesheet" href="css/screen.css" type="text/css" media="screen, projection" />
<link rel="stylesheet" href="css/print.css" type="text/css" media="print" />
<!--[if IE]><link rel="stylesheet" href="css/ie.css" type="text/css" media="screen, projection"><![endif]-->
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
/* <![CDATA[ */
$(document).ready(function(){
$('p.validate').hide();
$.getJSON("readJSON.php",function(data){
$.each(data.posts, function(i,post){
content = '<div id="post-'+ post.id +'">\n';
content += '<h3>' + post.author + '</h3>\n';
content += '<p class="small quiet">' + post.date_added + '</p>\n';
content += '<p>' + post.post_content + '</p>';
content += '<hr/>';
$("#contents").append(content).fadeIn("slow");
});
});
$(".reload").click(function() {
$("#posts").empty();
});
$("#add_post").submit(function() {
$('p.validate').empty();
// we want to store the values from the form input box, then send via ajax below
var author = $('#author').attr('value');
var post = $('#post').attr('value');
if(($('#author').val() == "") && ($('#post').val() == "")){
$("p.validate").fadeIn().append("Both fields are required.");
$('#author,#post').fadeIn().addClass("error");
}else{
$.ajax({
type: "POST",
url: "ajax.php",
data: "author="+ author + "&post=" + post,
success: function(result){
$('#contents').after( "<div>" +result +"</div>" );
}
});
}
return false;
});
});
/* ]]> */
</script>
<style type="text/css">
h3{margin:10px 0;}
p{margin:5px 0;}
#posts{display:none;}
</style>
</head>
<body>
<div class="container">
<div class="span-24">
<div id="post-container" class="span-9 colborder">
<h2>Posts loaded via Ajax:</h2>
<div id="contents"></div>
</div>
<div id="form" class="span-11">
<h2>New Post:</h2>
<form name="add_post" id="add_post" action="">
<label>Author:</label><br />
<input type="text" name="author" id="author" size="15" class="text" /><br />
<label>Post:</label><br />
<textarea name="post" id="post" rows="5" cols="5" class="text"></textarea><br />
<input type="submit" value="Post" id="submit" /><br />
</form><br />
<p class="validate error"></p>
</div>
</div>
<div class="span-24">
Reload
</div>
</div>
</body>
</html>
Questions to ask yourself...
Does jQuery even run your success callback?
If so is the response data well formed markup?
To begin I would add a "debugger;" statement to your success function (assuming you have firefox and firebug). This will enable you to break into the script console and get a better understanding of what is happening.
The debugger statement will cause the script execution to pause and break into the firebug console. Try the following
success: function(result){
debugger;
$('#contents').after( "<div>" +result +"</div>" );
}
If your script hits this I suspect your response markup is not well formed and jQuery is having issues parsing into the div but you can check all this when your at that breakpoint in firebug.
Another easy thing to check and dismiss in your debugging is
does your web server serve a valid (status 200) response (check the console or net tab in firebug to see this, or use the likes of fiddler if running in ie)
Let me know how you get on.
You might be getting an error try adding a debug statement to your ajax call using the error setting
$.ajax({
type: "POST",
url: "ajax.php",
data: "author="+ author + "&post=" + post,
error: function(XMLHttpRequest, textStatus, errorThrown)
{ alert(errorThrown); },
success: function(result){
$('#contents').after( "<div>" +result +"</div>" );
}
});

Categories

Resources