Passing variables with jQuery - javascript

i'm relatively new to jquery and javascript and am trying to pass
a unique id (number) into a flickr search function (jquery.flickr-1.0-js) like so, (number is the variable where i'm storing the unique id)
<script type="text/javascript" src="javascripts/jquery.flickr-1.0.js"></script>
<script type="text/javascript">
jQuery(function(){
jQuery(".btnRefresh").click(function(){
var number = $(this).attr("id");
$('#gallery_flickr_'+number+'').show();
jQuery('#gallery_flickr_'+number+'').html("").flickr({
api_key: "XXXXXXXXXXXXXXXXXXXXXXX",
per_page: 15
});
});
});
</script>
When i try to pass it in to the flickr-1.0.js function like so (abbreviated)
(function($) {
$.fn.flickr = function(o){
var s = {
text: $('input#flickr_search_'+number+'').val(),
};
};
})(jQuery);
i get a error
number is not defined
[Break on this error] text: $('input#flickr_search_'+numbe...] for type=='search' free text search
please help, what do i need to do to pass the variable between the two scripts?
Thanks,

Try adjusting your scripts as below:
...
jQuery('#gallery_flickr_'+number+'').html("").flickr({
api_key: "XXXXXXXXXXXXXXXXXXXXXXX",
per_page: 15,
search_text: $('input#flickr_search_'+number+'').val()
});
...
(function($) {
$.fn.flickr = function(o){
var s = {
text: o.search_text
};
};
})(jQuery);
The idea is that you need to find the search text based on the id of the clicked item. You do that in the function where the id is available, then pass the value of the input to the flickr function with the other values in the hash argument. In the flickr function you extract the named item from the hash and use the value.

You can pass parameters in JQuery very easily; for example:
$.ajax({
type: "POST",
url: "/<%=domainMap%>/registration/recieptList.jsp",
data: "patientId=" + patientId+"golbalSearch="+golbalSearch,
success: function(response){
// we have the response
$('#loadPatientReciept').html(response);
},
error: function(e){
alert('Error: ' + e);
}
});
}

I just realized 'flicker' != 'flickr'
darn you cutesy web 2.0 names!!!
Thanks!

Related

Displaying only javascript values in select tag

I am having one select tag
<select id="pname">
<option>saome data</option>
</select>
After javascript function run i want to display only javascript values in select tag, i tried this as below
<script>
function xyz() {
$.ajax({
url: 'abc.php',
type: "get",
cache: false,
data: {
cat: $('#xyzn').val()
},
success: function(response) {
var myObject = JSON.parse(response);
$('#pname').val(myObject.details[3]);
}
})
}
</script>
like this i am using javascript for display only javascript value but its not working.
please help in this.
If myObject.details[3] is an array you can loop over it and append your values there.
var myObject = JSON.parse(response);
myObject.details[3].forEach(function (val) {
$('#pname').append($('<option>',
{
value: val,
text: val
}));
});
Else just append like the following.
$('#pname').append($('<option>', {
value: myObject.details[3],
text: myObject.details[3]
}));
you can append the option tags using jQuery.
try this
$('#pname').append("<option>"+myObject.details[3]+"</option>")
hope it works
I don't understand your questions completely but I think you want to make a option for data obtained from that file. And you want to remove other options. This can done by:
$('#pname').html("<option>" + myObject.details[3] + "</option>");
if you want to keep the existing data, use this:
$('#pname').append("<option>" + myObject.details[3] + "</option>");

Function Statements no name error

I have the following code:
<script type="text/javascript">
$(document).on("click", "#leftconversation", function(){
var self = this;
var cid = $(this).attr('class'); // getting the user id here
var request = $.ajax({
url: "conversation.php",
type: "POST",
data: { cid: cid },
beforeSend: function(){
self.html("Loading please wait...");
}
});
//WHEN SUCCESS
request.success(function( data ) {
$("#right").html(data); // replace the right div with echoed content from php file
});
});
</script>
However, my console keeps giving me the error: “SyntaxError: Function statements must have a name.”
I can't seem to fix the issue and that’s why the AJAX code isn’t running. Where’s this error coming from?
As per what Todd said, i changed the code to following:
<script type="text/javascript">
$(document).on("click", "#leftconversation", function(){
var self = this;
var cid = $(this).attr('class'); //you are getting the user id here
var request = $.ajax({
url: "conversation.php",
type: "POST",
data: { cid: cid },
beforeSend: function(){
self.html("Loading please wait...");
},
success: function(data) {
$("#right").html(data);
},
error: function(request, err){ console.log('An Error Occured' + err); }
});
});
</script>
It fixed the first error, but now its telling me TypeError: undefined is not a function (evaluating 'self.html("Loading please wait...")')
This is fixed, should have used var self = $(this); instead
as per my comment
$(document).on("click", "#leftconversation", function(){
var $self = $(this);
var cid = $(this).attr('class'); // getting the user id here
var request = $.ajax({
url: "conversation.php",
type: "POST",
data: { cid: cid },
beforeSend: function(){
$self.html("Loading please wait...");
}
});
//WHEN SUCCESS
request.success(function( data ) {
$("#right").html(data); // replace the right div with echoed content from php file
});
});
You can fix your issue without having to use a variable. Just set the context: property of the $.ajax call.
var request = $.ajax({
url: "conversation.php",
type: "POST",
data: { cid: this.className }, // Quicker way to get the class.
context: $(this), // The context in the callback will be the jQuery object.
beforeSend: function() {
// v-- This is now a jQuery object.
this.html("Loading please wait...");
}
});
Your code, as you have posted it, is correct. The error must be coming from elsewhere. That said, wherever the error is, here’s what to look for:
As you likely know, functions can be defined like this:
function greet(name) { /* ... */ }
This works in a statement context. Functions can also be used in an expression context:
[1, 2, 3].forEach(function(item) { alert(item); });
In an expression context, we can omit the name, as we did above, or we can include a name:
[1, 2, 3].forEach(function foo(item) { alert(item); });
However, what we cannot do is have a standalone function declaration without a name. This is an error:
function(name) { /* ... */ }
That is what your (now first) problem was.
“undefined is not a function”
Your updated code has a different problem. When you set self = this, this is a DOM element, not a jQuery object. You later try to use self.html, but DOM elements do not have a html property. If you wish to use jQuery methods, you must convert the element into a jQuery object, either at the point of assignment (self = $(this)) or at the point of use $(self).html.

parse name from user input when using jquery serialize

I am trying to grab user input from a dynamic form using jquery serialize. My form looks like this
<form id="lookUpForm">
<input name="q" id="websterInput" />
<button onclick="webster(); return false;">Search</button>
</form>
I want to take the input, and attach it to the end of websters dictionary URL to search for a word.
http://www.merriam-webster.com/dictionary/ + (user input)
When you run an alert to see what the value of 'q' is, you get
q=input
so for example if I put 'cats'
the alert would say q=cats.
I want the the string to just be what the user entered. However, you need to give the input a name to use seralize. So how can I take the user input, and strip out the 'q=' part.
EDIT
as requested here is the function I'm calling. Note. I HAVE to use serialize(); This isnt an option.
function webster() {
var stringHolder = $("#lookUpForm").serialize();
alert(stringHolder);
$.ajax({
type: 'GET',
crossDomain: 'true',
url: "http://www.merriam-webster.com/" + stringHolder,
success: function (data) {
console.log(data);
console.log("http://www.merriam-webster.com/" + stringHolder);
},
error: function () {
alert("Failed to get dictionary data");
console.log("http://www.merriam-webster.com/dictionary/" + stringHolder);
}
});
};
You can just access it using val method of jQuery
function webster() {
var stringHolder = $("#lookUpForm").serialize();
alert(stringHolder);
$.ajax({
// (...) removed some code for brevity
error: function () {
alert("Failed to get dictionary data");
console.log("http://www.merriam-webster.com/dictionary/" +
$('#websterInput').val()); // I suppose you want the user-input here
}
});
};
You could use serializeArray().
And then do something like this and put your string together like you want to
var array = $("#lookUpForm").serializeArray();
$(array ).each(function(){
alert(this.value);
});

JSON VALUE AS QUERY STRING

I'm using Maxmind.Com's GeoIP2 (Omni) Webservice on my Drupal 7 website to pull geographic data based on my visitor's IP.
I am able to get a JSON document by using this code:
<script type="text/javascript" src="//js.maxmind.com/js/apis/geoip2/v2.0/geoip2.js">
</script>
<script type="text/javascript">
var onSuccess = function(location){
console.log(
"Lookup successful:\n\n"
+ JSON.stringify(location.city.names.en, undefined, 4)
);
};
var onError = function(error){
alert(
"Error:\n\n"
+ JSON.stringify(error, undefined, 4)
);
};
geoip2.omni(onSuccess, onError);
</script>
One of the returned values is the visitor's city name. How can I use the returned value as part of a query string?
For example, if 'city.names.en' = 'Detroit', how could I use "Detroit" as a key to retrieve data (e.g. Local phone number) from another document, table, etc?
The end goal is to dynamically insert a "local" phone number into the "contact us" section based on the visitor's location.
Typically you'll format a query string like this:
http://mydomain.com/route?parameterName=value
For your example it may look like this:
http://mydomain.com/phoneNumbers/phoneNumber?city=Detroit
There can be two approach to achieve what you want to do.
Load the contact information after getting the city name using ajax. Here's an example:
<span id="contact"></span>
<script type="text/javascript">
$(document).ready(function() {
geoip2.omni(function(data) {
$.ajax({
type: "GET",
url: "your/url/to/contact/getter/service",
data: {
city : data.city.names.en
},
success: function(contact) {
// update your contact information
$("#contact").text(contact);
}
}
}, function(data) {
debugger;
});
});
</script>
Obviously, you need a resource that you can request to provide the contact information given the city name.
Create a contact information map and use it to get the contact information for a City without having to send a request again.
<span id="contact"></span>
<script type="text/javascript">
var contactMap = {
NewYork : "123123",
London : "9797987"
}
$(document).ready(function() {
geoip2.omni(function(data) {
// update your contact information
$("#contact").text(contactMap[data.city.names.en]);
}, function(data) {
debugger;
});
});
</script>

CKEDITOR ajax posts

I am trying to make an admin page using AJAX so when the client updates information in the CKEDITOR it doesn't have to take him to a new page. Getting data from input fields are easy enough using the .val() function, but because textareas are not updated on the fly, I can't use that same function. Heres as far as I got:
// this replaces all textarea tags into CKEDITORS
<script type="text/javascript">
CKEDITOR.replaceAll();
</script>
//this attempts to grab all data from inputs and textareas
$(function() {
$("#submit").click(function() {
var newsTitle = $("#newsTitle").val();
var editNews = CKEDITOR.instances.editNews.getData();
var contactTitle = $("#contactTitle").val();
var editContact = CKEDITOR.instances.editContact.getData();
var linksTitle = $("#linksTitle").val();
var editLinks = CKEDITOR.instances.editLinks.getData();
$.ajax({
type: "POST",
url: "update.php",
data: 'newsTitle='+newsTitle+'&editNews='+editNews+'&contactTitle='+contactTitle+'&editContact='+editContact+'&linksTitle='+linksTitle+'&editLinks='+editLinks,
cache: false,
success: function(){
updated();
}
});
return false;
});
});
the getData() function seemed like it would work because I tested it with alerts and it was grabbing the data from the editors, but once I would try and update, it wouldn't work...
any ideas?
This code replaces the textarea:
<script type="text/javascript">
CKEDITOR.replace( 'TEXTAREA_ID', {
extraPlugins : 'autogrow',
removePlugins : 'resize',
entities : false
});
</script>
In the JS file this is the code and I am using Jquery Validator Plugin:
$(document).ready(function(){
jQuery.validator.messages.required = "";
$("#FormID").validate({
submitHandler: function(){
var ContentFromEditor = CKEDITOR.instances.TEXTAREA_ID.getData();
var dataString = $("#FormID").serialize();
dataString += '&ContentFromEditor='+ContentFromEditor;
$.ajax({
type: "POST",
url: "Yourfile.php",
data: dataString,
cache: false,
success: function(html){
YOU WORK WITH THE RETURN HERE
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.responseText);
}
});
return false;
}
});
});
This is the line that most of the time creates the error:
CKEDITOR.instances.TEXTAREA_ID.getData();
After the instances always comes the ID of the textarea.
I have my own config.js that you can get from the ckeditor website or from the examples.
Tage a look at the CKEditor function/adaptor for jQuery
http://docs.cksource.com/CKEditor_3.x/Developers_Guide/jQuery_Adapter
Because setting and retrieving the editor data is a common operation, the jQuery Adapter also provides the dedicated val() method:
// Get the editor data.
var data = $( 'textarea.editor' ).val();
// Set the editor data.
$( 'textarea.editor' ).val( 'my new content' );
With this code, my problems were solved.
I updated the field running ckeditor to be seen in serialize.
$('#form').find('.class').each(function(index) {
$(this).val(CKEDITOR.instances[$(this).attr('id')].getData());
});

Categories