Suggenstion on focusout function - ajax

What I'm trying to accomplish? :
I have provided a search bar, if you type something it will autosuggest you the results. By clicking on the results user will be taken to the reference page. I wanna provide a functionality that if a user clicks outside the result or input box, the result will get disappeared.
What did it take? :
Html, css, js, php and ajax
Problem? :
I am able to see the results but I have problem with focusout function in jquery. ( I don't know much about jquery ) If I click on the body of my webpage, the result element doesn't get disappeared.
Half success! :
Well I tried focusout and focusin function on input box, the result element was able to get disappeared but then if I click on any list-item (results) it stopped taking me to the reference page since I used focusout with input box
jquery:
$(document).ready(function(){
$('#search_bar_input').focusin(function(){
$('#results').css('display','block') ;
});
} );
$(document).ready(function(){
$('#search_bar_input').focusout(function() {
$(this).val('') ;
$('#results').css('display','none') ;
} );
} );
Html :
<form id="search_bar" name="search">
<input type="text" placeholder="Search a Song or Artist..." name="search_text" onkeyup="findMatch()" id="search_bar_input"/>
</form>
<div id="results">
</div>
Ajax or something I don't know to be honest. :
function findMatch() {
var xmlhttp ;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest() ;
} else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP") ;
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("results").innerHTML = xmlhttp.responseText ;
}
}
xmlhttp.open('GET', 'include/search.php?search_text='+document.search.search_text.value, true) ;
xmlhttp.send() ;
}
I have a file search.php here is the code
<?php
if(isset($_GET['search_text']) ) {
$search_text = $_GET['search_text'] ;
}
if(!empty($search_text)) {
if(mysql_connect('localhost', 'root', '' ) ) {
if(mysql_select_db('getthetrack.com')) {
$query = "SELECT `Artists` FROM `artist's name` WHERE `Artists` LIKE '".mysql_real_escape_string($search_text)."%' ";
$query_run = mysql_query($query) ;
if(mysql_num_rows($query_run)){
while($query_row = mysql_fetch_assoc($query_run)) {
echo '<ul class="search_results">';
$Artists = '<li class="search_results_items">'.$query_row['Artists'].'</li>' ;
echo ''.$Artists.'' ;
echo '</ul>';
}
} else {echo "No results found!";}
}
}
}
Any suggestions on the functionality I wanna deliver?

You can try this:
$( "#search_bar_input" ).blur(function() {
});

Try this so:
$(document).click(function (e)
{
var container = $("#results");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.hide();
}
});

Related

How to stop infinite scroll when data is no longer codeigniter

hi am having a problem with infinite scroll functionality, when all the contents have been displayed it still continues to scroll (strange behavior). i am looking for a way to stop the infinite scroll when all contents are displayed
here is my code
$(document).ready(function() {
var total_record = 0;
var total_groups = <?php echo $total_data; ?>;
$('#results').load("<?php echo base_url() ?>admin/csr_transactions/get_products",
{'group_no':total_record}, function() {total_record++;});
$(window).scroll(function() {
});
$('#load_more').click(function(){
load_more(total_record, total_groups);
});
function load_more(total_record, total_groups) {
if(total_record <= total_groups)
{
$('.loader_image').show();
$.post('<?php echo site_url() ?>admin/csr_transactions/get_products',{'group_no': total_record},
function(data)
{
if (data != "") {
$("#results").append(data);
$('.loader_image').hide();
total_record++;
}
});
}
}
});
</script>`

Live Search Filter with Checkbox PHP

I have issue about the live search with check box. My problem is when i search one the name list the check box is automatically check. only the showed data check.
example i search world "vin"
all have word vin must be checked.
this is my [sample][1]
[1]: http://jsfiddle.net/v921/TxYqv/3/
UPDATED answer:
Here is how your js should look like:
function filter(element) {
var $trs = $('.AvailableGroupLab tr').hide();
var regexp = new RegExp($(element).val(), 'i');
var $numberOfShownRows = 0;
var $rows = $trs.filter(function () {
if($(element).val() != "")
{
$(this).children(':nth-child(1)').html("<input type='checkbox' checked />");
}
else
{
$(this).children(':nth-child(1)').html("<input type='checkbox' />");
}
return regexp.test($(this).children(':nth-child(2)').text());
});
$rows.show();
if($rows.length == 0)
{
$('#message').show();
}
else
{
$('#message').hide();
}
}
$('input:text').on('keyup change', function () {
filter(this);
})
And put this div whereever you want to put your text:
<div id="message" style="display:none"> No record! </div>

getProductListJSON need more data

There is a part of the code that calls the getProductListJSON javascript function that looks like this
$.getJSON(storeRootUrl + "jsoncatalog/product/list/id/"+id, function(jsonObj) {
renderProductList(jsonObj,sid);
});
It returns the image, product name, description and id.
I would like it to return a bit more, like the type of product, as in "simple, configurable, etc"
Based on the layout:
<jsoncatalog_product_list>
<reference name="content">
<block type="paypal_catalog/json_product_list" output="toHtml" name="product_list"/>
</reference>
</jsoncatalog_product_list>
Looking at app\code\community\Paypal\Catalog\Block\Json\Product\List.php (hopefully I am looking in the right place), I can see the following code, wich I assume returns the data.
public function _toHtml()
{
try {
$array = array();
$category = Mage::registry('pp_current_category');
if (!is_null($category)) {
$array = Mage::helper('paypal_catalog')->getProducts($category->getId());
$this->setCurrenCategoryKey($category->getId());
} else {
$array = array('category' => '', 'items' => array());
}
return Mage::helper('core')->jsonEncode($array);
} catch (Exception $e) {
Mage::logException($e);
return false;
}
}
Where can I add the extra fields in that I need?
Am I on the right track, or even looking at the right template / php code that returns the data?
Please help me out here, I have not done Magento development for 2 years, so I have to re-learn allot of this stuff again....
Thanks in advance.
This is indeed he place where output is made. However you need to dig deeper. Look at this line:
$array = Mage::helper('paypal_catalog')->getProducts($category->getId());
This fills the array where jsonEncode uses in the output routine. This is probably located somewhere in app/code/community/Paypal/Catalog/Helper/.
Alternatively, you can post-process that $array and add in your fields. However I strongly discourage that as you may have better luck (and performance) inside the helper method getProducts instead.
Good luck.
I ended up with the following code, which is not the most efficient, but there are never more than 5 products in the list of this mobile app solution...
Added code to:
$array = Mage::helper('paypal_catalog')->getProducts($category->getId());
$this->setCurrenCategoryKey($category->getId());
And made it:
$array = Mage::helper('paypal_catalog')->getProducts($category->getId());
foreach ($array['items'] as &$productitem) {
$productId = $productitem['id'];
$product = Mage::getModel('catalog/product')->load($productId);
if(!is_null($product)){
$productitem['type'] = $product->getTypeId();
//Get all options for product
$options = array();
$options = $product->getOptions();
if (count($options) > 0){
$productitem['hasoptions'] = '1';
}
else
{
$productitem['hasoptions'] = '0';
}
$addTocartUrl = $this->helper('checkout/cart')->getAddUrl($product);
$productitem['addTocartUrl'] = $addTocartUrl;
}
else{
$productitem['type'] = 'simple';
$productitem['hasoptions'] = '0';
}
}
$this->setCurrenCategoryKey($category->getId());
I was then able to change my footer.phtml with the following:
<!-- Product List Template -->
<div id="productListTemplate">
<li onclick="checkQuickAdd(jQuery(this),'%url%');">
<div class="product-image">%image%</div>
<div class="product-content">
<div class="product-title">%title%</div>
<div class="product-description"><span class="counter" style="font-weight:bold;font-size:large;"></span> %description%</div>
<div class="product-price">$%price%</div>
<div class="quickadd">+</div>
</div>
<div class="product-id" style="display:none;">%id%</div>
<div class="product-hasoptions" style="display:none">%hasoptions%</div>
</li>
</div>
Which allowed to query the values later on in a js function:
function checkQuickAdd(listitem,url)
{
var hasOptions = jQuery(listitem).find(".product-hasoptions").text();
var productId = jQuery(listitem).find(".product-id").text();
var productTitle = jQuery(listitem).find(".product-title").text();
if (hasOptions == '0'){
try {
jQuery(".ui-loader").css("display","block");
var cartUrl = "/index.php/test/jsoncheckout/cart/add/product/" + productId;
var cartno = jQuery(jQuery('.ui-page-active .menu-bar-item.itemright>div')[0]).attr('id').replace("cartCount","");
var cartCount = jQuery(jQuery('.ui-page-active .menu-bar-item.itemright>div')[0]).text();
jQuery.ajax( {
url : cartUrl,
type: "POST",
dataType : 'json',
contentType: "application/json; charset=utf-8",
async: true,
cache: false,
success : function(data) {
//alert("added");
var counter = 1;
var strCounter = jQuery(listitem).find(".counter").text();
if (strCounter != "") { counter = parseInt(strCounter) + 1; }
if (cartCount != "") {
cartCount = parseInt(cartCount) + 1;
}
else {
cartCount = 1;
}
jQuery(listitem).find(".counter").text(counter);
// update cart number
updateCartCount(cartCount, cartno);
jQuery(".ui-loader").css("display","none");
alert("Added " + productTitle);
},
fail: function (msg) {
jQuery(listitem).find(".product-description").text(msg.d);
jQuery(".ui-loader").css("display","none");
}
});
jQuery(".ui-loader").css("display","none");
}
catch (e) {
alert(e);
jQuery(".ui-loader").css("display","none");
}
}
else{
forwardURL(url);
}
}
This must be the most inefficient code that I have written in a long time, but the time frame was very small to complete this.
I would love to do this in a more efficient way.
Any suggestions would be appreciated!

PhantomJS: event handler that executes AJAX call

This is a simple test case for PhantomJS to demonstrate that an event handler that, when invoked, executes an AJAX call, does not work.
I've created a simple test here to try and access some content loaded via AJAX. It's very possible I've done something wrong, in which case I'd appreciate someone pointing out what that is. However, if not, I think there is a problem with PhantomJS.
Here's a simple page with a single that has a change event bound to it. When the value of the changes, it loads some content from the server and replaces the content of a specific <p>
The text of the <p id="bar">foo</p> should change to 'bar' after the ajax call is completed and processed.
Can anyone help me out?
<html>
<head>
<title>AJAX test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(function(){
$('#getBar').change(function() {
$('#bar').load("/test/bar");
});
});
</script>
</head>
<body>
<h1>Foo</h1>
<div>
<select id="getBar">
<option value=""></option>
<option value="go" id="go">Get Bar Text</option>
</select>
</div>
<p id="bar">foo</p>
</body>
</html>
Here's the script I use to navigate to this simple page and ATTEMPT to use jQuery to change the value of the and trigger the change event.
The steps of the script are broken out into an array of 'step' functions:
var wp = require("webpage");
var system = require('system');
var util = require('./util-module.js'); // my logging API
var baseUrl = 'http://127.0.0.1:8080';
/* Global error handler for phantom */
phantom.onError = function(msg, trace) {
var msgStack = ['PHANTOM ERROR: ' + msg];
if (trace) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line);
});
}
util.log.error(msgStack.join('\n'));
// exit phantom on error
phantom.exit();
};
/* Inject jQuery into the phantom context */
var injected = phantom.injectJs('./jquery.min.js');
util.log.debug('phantom injected jQuery: ' + injected);
/* Create and initialize the page */
var page = wp.create();
var loadInProgress = false;
page.onLoadStarted = function() {
loadInProgress = true;
util.log.debug("page load started: " + page.url);
};
page.onLoadFinished = function() {
loadInProgress = false;
util.log.debug("page load finished: " + page.url);
// inject jquery onto the page
var injected = page.injectJs('./jquery.min.js');
util.log.debug('page injected jQuery: ' + injected);
page.evaluate(function() {
jQuery.noConflict();
});
};
page.onResourceRequested = function(request) {
console.log('Request (#' + request.id + '): ' + JSON.stringify(request));
};
page.onResourceReceived = function(response) {
console.log('Response (#' + response.id + ', stage "' + response.stage + '"): ' + JSON.stringify(response));
};
/* Redirect all console messages logged on page to debug */
page.onConsoleMessage = function(msg) {
util.log.debug(msg);
};
var steps = [
function() {
util.log.debug('LOAD THE TEST PAGE');
page.open(baseUrl + "/test/foo");
},
function() {
util.log.debug('CHANGE THE SELECT');
// see what the first result is. change the sort. Wait for the ajax update to complete
// start iterating over results.
var oldTitle = page.evaluate(function() {
return jQuery('#bar').text();
});
util.log.debug('OLD TEXT: ' + oldTitle);
page.evaluate(function(){
jQuery('select').val('go');
jQuery('select').trigger('change');
jQuery('select').change();
console.log('SELECT VALUE AFTER UDPATE: ' + jQuery('select').val());
});
loadInProgress = true;
count = 0;
var fint = setInterval(function() {
var newTitle = page.evaluate(function() {
return jQuery('#bar').text();
});
util.log.debug('NEW TEXT: ' + newTitle);
count++;
if (oldTitle != newTitle) {
clearInterval(fint);
loadInProgress = false;
}
if (count > 5) {
clearInterval(fint);
loadInProgress = false;
}
}, 500);
},
function() {
util.log.debug('PRINT PAGE TITLE');
page.evaluate(function(){
console.log(document.title);
});
},
];
// harness that executes each step of the scraper
var testIndex = 0;
interval = setInterval(function() {
if (!loadInProgress && typeof steps[testIndex] == "function") {
util.log.debug("step " + (testIndex + 1));
steps[testIndex]();
testIndex++;
}
if (typeof steps[testIndex] != "function") {
util.log.debug("test complete!");
clearInterval(interval);
phantom.exit();
}
}, 500);
And here is the output. I'm expecting the text to change from 'foo' to 'bar' but it never happens
DEBUG: CHANGE THE SELECT
DEBUG: OLD TEXT: foo
DEBUG: SELECT VALUE AFTER UDPATE: go
DEBUG: NEW TEXT: foo
DEBUG: NEW TEXT: foo
DEBUG: NEW TEXT: foo
DEBUG: NEW TEXT: foo
DEBUG: NEW TEXT: foo
DEBUG: NEW TEXT: foo
DEBUG: step 5
DEBUG: PRINT PAGE TITLE
DEBUG: AJAX test
DEBUG: test complete!
BTW, PhantomJS 1.7. This is a great project.
The problem with the example listed above is that I simply injected jQuery into a page that already had jQuery. When I stopped doing that, it worked.

Load part of a webpage with AJAX - no JQuery

I know that there is a JQuery way of doing this but that's not what I need right now.
I have the following javascript that pulls a page content into a div, however I don't want the whole page, just the content of a DIV from that page:
function ahah(url, target) {
document.getElementById(target).innerHTML ='<img src="ajax-loader.gif"/>';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
req.onreadystatechange = function() {ahahDone(url, target);};
req.open("GET", url, true);
req.send("");
}
}
function ahahDone(url, target) {
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) { // only if "OK"
document.getElementById(target).innerHTML = req.responseText;
} else {
document.getElementById(target).innerHTML=" Error:\n"+ req.status + "\n" +req.statusText;
}
}
}
function load(name, div) {
ahah(name,div);
return false;
}
And then I call it like this:
LOAD
Where should specify the selector I want to load from page.php?
Normally in AJAX application, in order to get the HTML Fragment the server is the one who is returning the fragment instead of having it selected on the client's side. For example, see this Simple Example on Section 4. Cool AJAX example. Code from the website is provided below for your reference:
<?php
function validate($name) {
if($name == '') {
return '';
}
if(strlen($name) < 3) {
return "<span id=\"warn\">Username too short</span>\n";
}
switch($name) {
case 'bob':
case 'jim':
case 'joe':
case 'carol':
return "<span id=\"warn\">Username already taken</span>\n";
}
return "<span id=\"notice\">Username ok!</span>\n";
}
echo validate(trim($_REQUEST['name']));
?>
Notice that the PHP page is just returning an HTML Fragment containing the <span> only instead of the full html. This is one of the benefits of AJAX call that you don't need to return the full page thereby saving the bandwidth cost since the payload is smaller

Resources