Variable Scope Between JS Functions: Variable Not Defined - javascript

I am working on a script that uses jQuery get function to send information to another page and return the data as an alert on current page. I am trying to send the search field value from input form (this works), as well as the collector ID, which is a value generated by an option selected in a drop down menu above the search form.
Unfortunately, I keep getting "collector_id is undefined error" when I run the script. I think I am having an issue with the scope of the variable.. but have tried many options and can't seem to find the solution which keeps the value of collector_id for use in the get function.
$( document ).ready(function() {
$( ".search-field" ).keyup(function() {
//THIS FUNCTION UPDATES THE COLLECTOR ID VARIABLE FROM DROPDOWN MENU VALUE SELECTED BY USER
$( "select" )
.change(function () {
var collector_id = "";
$( "select option:selected" ).each(function() {
collector_id += $( this ).data('value') + " ";
});
})
.change();
//THIS FUNCTION DOES A SEARCH ON ANOTHER PHP SCRIPT PASSING search and collector_id values
if($(".search-field").val().length > 3) {
var search = $(".search-field").val();
$.get("query-include.php" , {search: search, collector_id: collector_id})
.done(function( data ) {
alert( "Data Loaded: " + data );
});
}
});
});

you just need to initialize collector_id outside of the change, so it will be in scope for the $.get
var collector_id = "";
$( "select" )
.change(function () {
$( "select option:selected" ).each(function() {
collector_id += $( this ).data('value') + " ";
});
})
.change();
//THIS FUNCTION DOES A SEARCH ON ANOTHER PHP SCRIPT PASSING search and collector_id values
if($(".search-field").val().length > 3) {
var search = $(".search-field").val();
$.get("query-include.php" , {search: search, collector_id: collector_id})
.done(function( data ) {
alert( "Data Loaded: " + data );
});
}
});

Related

How to combine two similar scripts and run it with slight variations

I have the following two scripts:
The first one, on grabs a keyword from input#search and populates a dropdown#search-results with the results from the ajax call for that keyword.
$(document.body).on( 'keyup', '#search', function ( e ) {
//e.preventDefault();
value = $(this).val(); //grab value of input text
jQuery.ajax({
url : ajaxsearch.ajax_url,
type : 'post',
data : {
action : 'search_client',
key : value,
},
success : function( response ) {
response = jQuery.parseJSON(response);
//console.log(response);
$.each(result, function(k, v) {
$('#search-results').append('<li>' + v['Name'] + '</li>');
});
}
});
});
The second script, grabs the value of the clicked dropdown result, does the same action as the first script only this time the ajax result is used to populate fields located on the page.
$(document.body).on('click','#search-results > li', function ( e ) {
//e.preventDefault();
value = $( this ).text(); //grab text inside element
jQuery.ajax({
url : ajaxsearch.ajax_url,
type : 'post',
data : {
action : 'search_client',
key : value,
},
success : function( response ) {
response = jQuery.parseJSON(response);
//console.log(response);
$.each(response, function(k, v) {
$('#clientID').val( v['ClientId'] );
$('#denumire').val( v['Name'] );
$('#cui').val( v['CUI'] );
$('#regcom').val( v['JRegNo'] );
$('#adresa').val( v['Address'] );
$('#iban').val( v['IBAN'] );
$('#banca').val( v['Bank'] );
$('#telefon').val( v['Phone'] );
$('#pers-contact').val( v['Contact'] );
});
}
});
});
Is there a way to combine the second script into the first one so not to make the second ajax call, but be able to populate the fields on the page with the results from the first ajax call depending on the clicked result in the dropdown list?
If the text you insert from v['Name'] into the list item in the first script is the exact same thing you want to use elsewhere in the page in the second script, you can reduce the code way, way down. After all, if you already have the value you want, there's no need to go search for it again.
//first function, just the relevant bits...
$.each(result, function(k, v) {
var newItem = $('<li>' + v['Name'] + '</li>');
$.data(newItem, "value", v);
$('#search-results').append(newItem);
});
//second function, the whole thing
$(document.body).on('click','#search-results > li', function ( e ) {
e.preventDefault();
var v = $.data($( this ), "value"); //grab object stashed inside element
$('#clientID').val( v['ClientId'] );
$('#denumire').val( v['Name'] );
$('#cui').val( v['CUI'] );
$('#regcom').val( v['JRegNo'] );
$('#adresa').val( v['Address'] );
$('#iban').val( v['IBAN'] );
$('#banca').val( v['Bank'] );
$('#telefon').val( v['Phone'] );
$('#pers-contact').val( v['Contact'] );
});
This should let you store the entire result object into the list item, then retrieve it later. If you have some elements in that list that you're not putting there with searches, you'll have to do some more work to get their relevant data too.

Jquery remote completion, li's are not selectable

I'm trying to create a text input with text completion using a remote host.
I've been trying to use the example in the following URL: http://demos.jquerymobile.com/1.4.0/listview-autocomplete-remote/
this is the javascript code from the example:
$( document ).on( "pageinit", "#myPage", function() {
$( "#autocomplete" ).on( "filterablebeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
if ( value && value.length > 2 ) {
$ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
$ul.listview( "refresh" );
$.ajax({
url: "http://gd.geobytes.com/AutoCompleteCity",
dataType: "jsonp",
crossDomain: true,
data: {
q: $input.val()
}
})
.then( function ( response ) {
$.each( response, function ( i, val ) {
html += "<li>" + val + "</li>";
});
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
});
}
});
});
so first of all I changed dataType from jsonp to json which makes the ajax call
return a proper json object and the unordered list is filled properly.
the problem that I encounter is that once I see the text completion (the li elements), I can't select any of the elements.
I tried browsing this example on my Galaxy Note 2 and I encountered the same problem, the elements are not selectable.
any ideas how to resolve the issue?
thanks
update
as to #Omar comment i changed the following line:
html += "<li>" + val + "</li>";
to
html += "<li><a href='#'>" + val + "</a></li>";
now i can click on an item but it doesn't do anything. it supposed to close the list and add to the text field the selected item.
You need to delegate an event to generated list items and then update input with the value.
$("#autocomplete").on("click", "li", function () {
/* text of clicked element */
var value = $(this).text();
/* update value of input */
$("#autocomplete-input").val(value);
/* optional - remove autocomplete result(s) */
$(this).parent().empty();
});
Demo

I build a select and i need when i refresh the page he shows what i have select before

I tried a lot of things and can't figure out what can I do. I build a select and I need when I refresh the page it shows what I have selected before, because every time it will update the database.
<script type="text/javascript">
$(window).on('load', function () {
$('.lavagem_01').selectpicker('selectAll');
$('.selectpicker').selectpicker({
'selectedText': 'cat',
'showIcon': true
});
$( "select" ).change( displayVals );
function displayVals() {
var etiquetas = $( this ).val() || [];
var product_id = $( this ).attr("id");
$.ajax({
url: 'salvar.php', //This is the current doc
type: "POST",
data: ({product_id: product_id, etiquetas: etiquetas}),
success: function(data){
alert("R: " + data);
}
});
//alert('Produto: ' + product_id + ' - Etiquetas: ' + etiquetas);
}
Sounds like sessionStorage would help.
For more persistent storage, try localStorage, instead.
Here's a jsfiddle example: http://jsfiddle.net/S8Djs/16/
var select = document.querySelector('select');
var lastIndex = sessionStorage.getItem('lastIndex');
// lastIndex, pulled from sessionStorage, is valid, so load into select.
if (typeof lastIndex !== 'undefined')
{
select.selectedIndex = lastIndex;
}
select.addEventListener('change',function(e)
{
// Store the chosen index value, here
sessionStorage.setItem('lastIndex',select.selectedIndex);
});
Notice that, after setting the select field option, you can either click "Run" or refresh the page, and the field will retain its value.
And again, if sessionStorage is not persistent enough for you, simply replace it with localStorage.

Creating error handling in jQuery

I am trying to create an error message from jquery for my document.
I have populated a <select> menu with JSON data, they link to external HTML files to display weather for their Location, what I need is for an error message to appear if there is no HTML file for the option.
For example the locations are London, New York, Paris and Rome, all except Rome have an HTML file that has weather data in it and displays fine but when Rome is selected...Nothing happens! and when Rome is selected after another location has been selected it stays on the current data!
I am using jQuery to pull the data etc. its my gut feeling that it needs an if() statement but I'm not sure of the conditions of the statement!
My jQuery code is here...
$(document).ready(function () {
// The below function pulls in the data from the external JSON file
$.getJSON('json/destinations.json', function (data) {
// attaches it to a variable
var destinations = data.Destinations;
$(destinations).each(function (id, destination) {
$('#destinations').append('<option value="' + destination.destinationID + '">' + destination.destinationName + '</option>');
});
$("#destinations").change(function () {
$('#weatherForecasts').load('raw_html/' + $(this).val() + '_weather.html .ngtable', function () {
$('#weatherForecasts').show("slow");
});
});
});
// Hide statements for our extra fields and also the weather forecast DIV
$('#weatherForecasts').hide();
$('#extraFields').hide();
$('.errorMessage').hide();
// Function that allows us to see the extraFields when a radio button is checked!
$("input[name='survey1']").change(function () {
$("#extraFields").show("slow");
});
$("input[name='survey1']:checked").change(); //trigger correct state onload
});
http://api.jquery.com/load/
at the bottom of the page there is an example for handling errors:
$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
So in your case
$("#destinations").change(function () {
$('#weatherForecasts').load('raw_html/' + $(this).val() + '_weather.html .ngtable', function (response, status, xhr) {
if (status == 'error'){
// do error things
}else{
$('#weatherForecasts').show("slow");
}
});
});

Retrieving AJAX value from a different Javascript function

In this simplified example of a larger web app, consider a simplistic registration form with fields: username, firstname, lastname and a Register button type="button".
<form action="" method="post" id="cns_form">
<table id="companyTable"><tr>
<td width="200">
First name*:<br />
<input type="text" id="first_name" name="first_name">
</td>
<td width="200">
Last name*:<br />
<input type="text" id="last_name" name="last_name">
</td>
</tr></table>
<input type="button" value="Register" id="register" >
</form>
<div id="alert" title="Alert"></div>
When the username field is completed, jQuery fires an ajax search of a database to see if that username already exists. This same search is also triggered when one clicks Register (for reasons removed from this simplified example).
PROBLEM: Everything works great when leaving the username field. However, after clicking Register, I don't know how to retrieve the result of the AJAX search and stop the form from submitting if the username already exists. I've tried all kinds of different things, but have returned the code to this state so it is easiest for the reader to assist.
For example, I tried integrating the suggested solution from this question, but I was unsuccessful applying it to my situation... I tried setting async:false inside the ajax function... I also tried calling the checkUsername(uname) from inside the checkForm function, but that didn't work either. A little help?
jQuery document.ready:
$(function(){
$('#username').blur(function() {
var uname = $.trim($(this).val());
checkUsername(uname);
}); //END BLUR username
$('#register').click(function() {
var uname = $.trim($( '#username').val());
checkUsername(uname);
checkForm();
});
}); //END document.ready
AJAX Call:
function checkUsername(uname) {
if (uname != '') {
$.ajax({
type: "POST",
url: 'ajax/ax_all_ajax_fns.php',
data: 'request=does_this_username_already_exist&username=' + uname,
async: false,
success:function(data){
//alert('Returned AJAX data: '+data);
if (data != 0) {
var existing_user = data.split('|');
var fn = existing_user[0];
var ln = existing_user[1];
focus_control = 'username';
$( '#alert' ).html( 'That username is already in use by ' + fn +' '+ ln +'. Please choose another.' );
$( '#alert' ).dialog( 'open' );
} //EndIf data<>0
} //End success
}); //End $.ajax
} //End If this.val <> ""
}
checkForm Function:
function checkForm() {
var un = $.trim($( '#username').val());
var fn = $( '#first_name').val();
var ln = $( '#last_name').val()
if (un=='' || fn=='' || ln=='') {
$( '#alert' ).dialog({
height: 200,
width: 300,
});
$( '#alert' ).html( 'Fields marked with an asterisk are required.' );
$( '#alert' ).dialog( 'open' );
} else {
$("#cns_form").submit();
}
}
One both rejoices and weeps when answering his own question, but here goes. The solution was to send the checkUsername() function as an input param to the checkForm() function, and to make the checkUserName() function return a value that we could check inside checkForm().
Therefore, we must modify the $('#register').click function thusly:
$('#register').click(function() {
var uname = $.trim($( '#username').val());
checkForm(checkUsername(uname)); //<===========================
});
THEN the checkUsername() function, thus:
function checkUsername(uname) {
var returnVal = 0; //<=================================
if (uname != '') {
$.ajax({
type: "POST",
url: 'ajax/ax_all_ajax_fns.php',
data: 'request=does_this_username_already_exist&username=' + uname,
async: false,
success:function(data){
//alert('Returned AJAX data: '+data);
if (data != 0) {
var existing_user = data.split('|');
var fn = existing_user[0];
var ln = existing_user[1];
focus_control = 'username';
$( '#alert' ).html( 'That username is already in use by ' + fn +' '+ ln +'. Please choose another.' );
$( '#alert' ).dialog( 'open' );
returnVal = 0; //<============================
} //EndIf data<>0
} //End success
}); //End $.ajax
} //End If this.val <> ""
return returnVal; //<==============================
}
AND the checkform() function thus:
function checkForm(exists) { //<============================
alert('sub checkForm(). value of exists: ' + exists);
if (exists==9) { //<================================
$( '#alert' ).html( 'That username is already in use' + existing +'. Please choose another.' );
$( '#alert' ).dialog( 'open' );
}else{ //<==========================================
var un = $.trim($( '#username').val());
var fn = $( '#first_name').val();
var ln = $( '#last_name').val()
if (un=='' || fn=='' || ln=='') {
$( '#alert' ).dialog({
height: 200,
width: 300,
});
$( '#alert' ).html( 'Fields marked with an asterisk are required.' );
$( '#alert' ).dialog( 'open' );
} else {
$("#cns_form").submit();
}
} //<===================================================
}
Thanks and kudos to Felix Kling for this helpful post.
Might put return false in the function call in the HTML form markup.
<form>
<bunchOfElements />
<button onclick="checkUserName(); return false">Check Name </button>
</form>
Also, you might bind the function to the button's click event using
$(document).ready(function(){
$("#buttonID").bind('click', function(){
//do your thing
checkForm();
});
});
Put a return false at the end of your #register button click function, right below checkForm(). The button is continuing to fire the form submit. when you have that handled by your javascript function.

Categories

Resources