Limiting search results Javascript - javascript

I was wondering how to limit the search result in the Javascript file, my JS file details as following:
/* JS File */
<script>
// Start Ready
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
</script
I just need to add similar to following code to be able to load a loading images before the result and limit the results into five or whatever, and if possible add load more later.
<script>
function loadSearch(query) {
document.body.style.overflow='hidden';
if (typeof xhr != "undefined") {
xhr.abort();
clearTimeout(timeout);
}
if (query.length >= 3) {
timeout = setTimeout(function () {
$('#moreResults').slideDown(300);
$('#search_results').slideDown(500).html('<br /><p align="center"><img src="http://www.tektontools.com/images/loading.gif"></p>');
xhr = $.ajax({
url: 'http://www.tektontools.com/search_results.inc.php?query='+encodeURIComponent(query),
success: function(data) {
$("#search_results").html(data);
}
});
}, 500);
} else {
unloadSearch();
}
}
function unloadSearch() {
document.body.style.overflow='';
$('#search_results').delay(100).slideUp(300);
$('#moreResults').delay(100).slideUp(300);
}
</script>
I have got the 2nd code from another template page, and I am just failing to adjust it to fit my search template (1st code), I'd appreciate it if someone could help me to adjust it, thanks a lot.

If you want to do this on the javascript side, you can use slice.
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html.slice(0, 5);
}
});
I would personally suggest that you do the limiting of rows on the server side to minimize the amount of data you transfer between the client and the server.

Related

How to use two forms in the Ajax request?

var getLoginpasssystem = function(getPassForgotSystem,getLoginCheckSystem){
$(document).ready(function() {
$('#login' || '#lostpasswordform').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'http://www.virtuelles-museum.com.udev/spielelogin/logsystem.php',
data: $(this).serialize(),
success: function(response) {
var data = JSON.parse(response);
if (data.success == "accepted") {
document.getElementById('inner').innerHTML = 'Herzlich Willkommen';
// location.href = 'index.php';
} else {
alert('Ungültige Email oder Password!');
}
}
});
});
})
}
The question is how to use two forms in one request with ajax. In this code I used ||, but it doesn't work. I mean the #login form works well but the #lostpasswordform doesn't work. When I click on the button it reloads the page instead of giving an alert.
The reason for this is the way you do your jQuery selection. Selecting multiple elements is done like this: $( "div, span, p.myClass" )
In other words it should work if you replace $('#login' || '#lostpasswordform') with $('#login, #lostpasswordform')
You can read more in detail about this in the jQuery docs
elector be used to select multiple elements. $("#login,#lostpasswordform").submit()
Use below code :
var getLoginpasssystem = function(getPassForgotSystem,getLoginCheckSystem){
$(document).ready(function() {
$("#login,#lostpasswordform").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'http://www.virtuelles-museum.com.udev/spielelogin/logsystem.php',
data: $(this).serialize(),
success: function(response) {
var data = JSON.parse(response);
if (data.success == "accepted") {
document.getElementById('inner').innerHTML = 'Herzlich Willkommen';
// location.href = 'index.php';
} else {
alert('Ungültige Email oder Password!');
}
}
});
});
})
}

Ajax not working properly

Bear with me I'm my javascript is a little rusty. So I'm trying to use a call by ajax to a PHP file and give it a plan type then make sense of it check to see if it then return a true or false if some allowed slots are less than some slots used up for the plan. Here is the Form in XHTML.
<form method="post" action="/membership-change-success" id="PaymentForm">
<input type="hidden" name="planChosen" id="planChosen" value="" />
</form>
On the same file. The ( < PLAN CHOICE > ) gets parsed out to the current plan.
<script>
var hash = window.location.hash;
var currentPlan = "( < PLAN CHOICE > )";
$(".planChoice").click(function(event){
var isGood=confirm('Are you sure you want to change your plan?');
var success;
$("#planChosen").val($(this).data("plan"));
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: ({plan: $(this).data("plan")}),
success: function (data) { //This is what is not working I can't get it to return true
success = data;
}
});
if(success) {
if (isGood) {
$("#PaymentForm").submit();
}
window.location = '/membership-change-success';
} else {
alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
}
});
My PHP for the ajax response looks like this.
<?php
require ('../includes/common.php');
include_once ('../includes/db-common.php');
require ('../includes/config.php');
$membership = new membership($dbobject);
$listing = new listing($dbobject);
$totalAvailableListings = ($membership->get_listingsAmount($_POST['plan']));
if($totalAvailableListings>=$listing->get_active_listings($user->id)){
echo json_encode(true); // I've tried with out jason_encode too
} else {
echo json_encode(false);
}
And that's pretty much it if you have any suggestions please let me know.
So I've tried to do it another way.
$(".planChoice").click(function (event) {
var isGood = confirm('Are you sure you want to change your plan?');
var success;
$("#planChosen").val($(this).data("plan"));
if (false) {
if (isGood) {
$("#PaymentForm").submit();
alert('you did it');
}
} else {
alert(isSuccessful($(this).data("plan")));
//alert('Please make sure you deactivate your listings to the appropriate amount before you downgrade.');
}
});
and I have an ajax function
function isSuccessful(plan) {
return $.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: {plan: plan}
});
}
The alert tells me this [object XMLHttpRequest]
any suggestions?
$.ajax() returns results asynchronously. Use .then() chained to $.ajax() call to perform task based on response
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: {plan: $(this).data("plan")}
})
.then(function(success) {
if (success) {
$("#PaymentForm").submit();
}
// if `form` is submitted why do we need to set `.location`?
// window.location = '/membership-change-success';
} else {
alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
}
}, function err(jqxhr, textStatus, errorThrown) {
console.log(errorThrow)
})
You should use the following form for your ajax call
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: ({plan: $(this).data("plan")}),
success: success = data
})
.done(function(response) {
if(success) {
if (isGood) {
$("#PaymentForm").submit();
}
window.location = '/membership-change-success';
}
else {
alert('Please make sure you deactivate your listings to the
appropriate amount before you Downgrade.')
}
});
the .done() clause ensures that you perform that code after the ajax call is finished and the response is obtained.

Cannot write in text box while it's autosaving using tinymce-4 plugin

I am using a plugin to autosave a textbox. However, when the autosave function is called, the text box cannot be typed into. I want users to be able to continue typing while the auto save is posted via AJAX.
tinymce.PluginManager.add('jsave', function(editor) {
// Get the form element into a jQuery object.
var $form = $(editor.formElement);
// Settings for initialization.
var settings = {
// Interval to execute the function. Default is 15000 (ms 1000 = 1 second).
//seconds: editor.getParam('jsave_seconds') || 2000,
seconds: 2000,
// This is our url that we will send data. If you want to have two different links,
// one for ajax and one for manual post this setting is pretty useful!
url: editor.getParam('jsave_url') || $form.attr('action'),
// This is the callback that will be executed after the form is submitted
callback: editor.getParam('jsave_callback')
};
$('.form_header,#attachbox').change(function (){
tinymce.get('mail_body').isNotDirty=0;
$("#save_status").html("Not saved");
});
var interval = setInterval(function() {
// Quit the function if the editor is not dirty.
if (!editor.isDirty()){
return;
}
// Update the original textarea
editor.save();
// Create a data string from form elements.
ds =$form.serialize();
// $form.find(':input').each(function (i, el) {
// $el = $(el);
// if($el.attr('name')!=null)
// ds[$el.attr('name')] = $el.val(); }
// );
$("#save_status").html("Saving");
$.ajax({
url: settings.url,
type: $form.attr('method'),
data: ds,
dataType:"json",
async:false,
success: function(msg) {
if (settings.callback){
//editor.setContent(msg.draft_body);
$("#save_status").html("Saved");
settings.callback(msg);
}
else{
$("#save_status").html("Saving error");
console.log(msg);
}
}
});
}, settings.seconds);
}); //vsk.me/en/28/adding-an-autosave-plugin-to-tinymce-2#sthash.jsOruJSd.dpuf
I have solved this problem:
just change form async:false, to async:true, in ajax calling part.
$.ajax({
url: settings.url,
type: $form.attr('method'),
data: ds,
dataType:"json",
async:true,
success: function(msg) {
if (settings.callback){
//editor.setContent(msg.draft_body);
$("#save_status").html("Saved");
settings.callback(msg);
}
else{
$("#save_status").html("Saving error");
console.log(msg);
}
}
});
Why don't you just disable it while doing the ajax call and enable again on ajax call ends?
You have a reference to enable/disable the field via JavaScript here:
make readonly/disable tinymce textarea
That way you could use the complete attribute on your Ajax call to enable the field again after either succes or error response like this:
var interval = setInterval(function() {
// Quit the function if the editor is not dirty.
if (!editor.isDirty()){
return;
}
// Update the original textarea
editor.save();
// Create a data string from form elements.
ds =$form.serialize();
$("#save_status").html("Saving");
tinyMCE.get('textarea_id').getBody().setAttribute('contenteditable', false);
$ajax({
url: settings.url,
type: $form.attr('method'),
data: ds,
dataType:"json",
async:false,
success: function(msg) {
if (settings.callback){
//editor.setContent(msg.draft_body);
$("#save_status").html("Saved");
settings.callback(msg);
}
else{
$("#save_status").html("Saving error");
console.log(msg);
}
},
error:function(){
//DO ERROR STUFF
},
complete:function(){
tinyMCE.get('textarea_id').getBody().setAttribute('contenteditable', true);
}
});

Running AJAX to retrieve logged in users is returning undefined

Hi so I am in the process of learning AJAX and have decided for a better UX on my admin system to have users online, messages, tasks updated and so on updated every 30 seconds or so depending on the load (in the code i have it set to 5 seconds for testing purposes).
The PHP file works fine and outputs the following JSON:
[{"username":"columkelly","time":"2013-12-18 14:13:55"}]
PHP
header('Content-Type: application/json');
if($_GET['function'] === "users_online"){ users_online(); }
function users_online(){
$result=mysql_query("SELECT * FROM sessions");
while($array = mysql_fetch_assoc($result)){
$dataArray[] = $array;
}
echo json_encode($dataArray);
}
The problem comes when I try to output the users that are online... The console log shows that it has picked it up but I am unable to get it to work with the users_online function with the callback. Here is the AJAX:
AJAX
var timer, delay = 5000;
timer = setInterval(function(){
val = $(this).serialize();
$(document).ready(function () {
$.when(
$.ajax({
url: "ajax.php?function=users_online",
dataType: "json",
type: "GET",
data: val,
success: function(data)
{
console.log(data);
}
}),
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "bird",
tagmode: "any",
format: "json"
})
).then(function (users_online, images) {
$("#users_online").html('');
$.each(users_online, function(data){
$('#users_online').html(data.username +':' + data.time);
}
),
$("#dvImages").html('');
random = Math.floor((Math.random()*3)+1);
$.each(images[0].items, function (i, item) {
var img = $("<img/>");
img.attr('width', '200px');
img.attr('height', '150px');
img.attr("src", item.media.m).appendTo("#dvImages");
if (i == random) return false;
})
});
});
}, delay);
What i end up getting is 1-4 images appearing from the flicker api (used this as a test base) and undefined:undefined. I know it has to have something to do with the success (i tried putting them into a javascript array but that did not work) and the function to grab the data:
function (users_online, images) {
$("#users_online").html('');
$.each(users_online, function(data){
$('#users_online').html(data.username +':' + data.time);
}
)
Thanks for all the help so far guys. I have searched far and wide but am unable to get anything to work with this.
Colum
EDIT:
This is the finished code that worked:
var timer, delay = 5000;
var users_online = [];
timer = setInterval(function(){
val = $(this).serialize();
$(document).ready(function () {
$.when(
$.ajax({
url: "ajax.php?function=users_online",
dataType: "json",
type: "GET",
data: val,
success: function(data)
{
console.log(data);
users_online = data; // Now call and loop through users_online wherever you need
}
}),
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "bird",
tagmode: "any",
format: "json"
})
).then(function (users_online, images) {
$("#users_online").html('');
$.each(users_online[0], function (i, item) {
$('#users_online').html(item.username +':' + item.time);
}
),
$("#dvImages").html('');
random = Math.floor((Math.random()*3)+1);
$.each(images[0].items, function (i, item) {
var img = $("<img/>");
img.attr('width', '200px');
img.attr('height', '150px');
img.attr("src", item.media.m).appendTo("#dvImages");
if (i == random) return false;
})
});
});
}, delay);
Although people would argue how optimal this solution is, it will fix the issue granted you don't overwrite it:
var timer, delay = 5000;
var global_users_online = []; // create a global array
timer = setInterval(function(){
val = $(this).serialize();
$(document).ready(function () {
$.when(
$.ajax({
url: "ajax.php?function=users_online",
dataType: "json",
type: "GET",
data: val,
success: function(data)
{
console.log(data);
global_users_online = data; // Now call and loop through global_users_online wherever you need
}
}),
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "bird",
tagmode: "any",
format: "json"
})
)

updating to separate DIVs via ajax

I have 2 elements on my page that I am trying to reload via ajax - however I can only ever seem to update one. Below is my code,
$('#messages_send').live('click', function() {
$.ajax({
url: base_url + 'ajax/send_message',
data: {
username: $('#messages_username').val(),
message: $('#messages_message').val(),
saveid: $('#messages_savedid').val(),
},
success: function(data) {
sending_message();
var x = jQuery.parseJSON(data);
if(x) {
if(x.gp_id==80)
{
$('#spn_ucredit').load(base_url + 'ajax/userdata/credits');
$('#overlay_credits').load(base_url + 'ajax/userdata/credits');
}
}
//$('#spn_ucredit').html($('#ncd_id').val());
//tmp_cost = $('#spn_ucredit').html()-$('#ncd_id').val();
//$('#ncd_id').val($('#ncd_id').val()-tmp_cost);
//alert(data);
setTimeout(message_sent, 2000);
setTimeout(remove_modal_box, 3000);
setTimeout(message_revert, 3500);
$("#saved_messages").load(base_url + 'messages #saved_messages > form');
$("#messages_content").load(base_url + 'messages #messages_content > form');
}
});
return false;
});
Am I doing something wrong?
sico,
There's a number of things you can do to debug/improve the code, chief amongst which is to reduce the number of HTTP requests. With $.get() instead of .load(), it should be possible to use the HTTP responses twice each.
Something like this :
$(document).on('click', '#messages_send', function() {
sending_message();
$.ajax({
url: base_url + 'ajax/send_message',
data: {
username: $('#messages_username').val(),
message: $('#messages_message').val(),
saveid: $('#messages_savedid').val(),
},
dataType: 'json',
success: function(data) {
var creditsPromise, messagesPromise;//vars that allow .when() later.
if(data.gp_id == 80) {
creditsPromise = $.get(base_url + 'ajax/userdata/credits', function(data) {
$('spn_ucredit').html(data);
$('#overlay_credits').html(data);
});
}
else {
creditsPromise = (new $.Deferred()).resolve().promise();
}
messagesPromise = $.get(base_url + 'messages', function(data) {
var $data = $(data);
$("#saved_messages").empty().append($data.find('#saved_messages > form'));
$("#messages_content").empty().append($data.find('#messages_content > form'));
});
$.when(creditsPromise, messagesPromise).done(function() {//fires when both $.get()s have successfully responded
message_sent();
setTimeout(remove_modal_box, 1000);
setTimeout(message_revert, 1500);
});
}
});
return false;
});
This reduces the number of HTTP requests from five to three.
You could further reduce the number of HTTP requests to one, though you would need to write a server-side script to perform everything currently performed by ...ajax/send_message, ...ajax/userdata/credits and ...messages, and json-encode a composite response.
The client-side code could then simplify to something like this:
$(document).on('click', '#messages_send', function() {
sending_message();
$.ajax({
url: base_url + 'ajax/send_message',
data: $("#messages form").serialize(),//assumed
dataType: 'json',
success: function(data) {
if(data.gp_id == 80) {
$('#spn_ucredit').html(data.credits);
$('#overlay_credits').html(data.credits);
}
$("#saved_messages").html(data.saved_messages);
$("#messages_content").html(data.messages_content);
message_sent();
setTimeout(remove_modal_box, 1000);
setTimeout(message_revert, 1500);
}
});
return false;
});

Categories