i want define a variable in Json callback.
Code;
$("select").change(function () {
var $variable = "";
$("select option:selected").each(function () {
$variable += $(this).text() + " ";
});
$("div.yaz").text($variable);
$('#result').html('loading...');
$.getJSON('program-bilgileri.php', function(JSON){
$('#result').empty();
$.each(JSON.$variable, function(i, program){
$('#result')
.append(program.isim +'<br />')
.append(program.bilgi+'<br />')
.append(program.adres+'<hr />');
});
});
})
.trigger('change');
program-bilgileri.php returns;
{
"programlar":[
{
"isim":"Zone Alarm",
"bilgi":"bilgisayarın güvenliğini sağlar",
"adres":"www.zonealarm.com"
},
{
"isim":"Opera",
"bilgi":"güvenli ve hızlı bir web tarayıcısıdır",
"adres":"www.opera.com"
},
{
"isim":"Photoshop",
"bilgi":"güçlü bir imaj işleme yazılımıdır",
"adres":"www.adobe.com"
}
]
}
The problem is here "$.each(JSON.$variable, function(i, program)" if I define $variable in JSON it isn't working.
Any idea?
The problems i see are
Inside the change event you are using $("select option:selected") which finds all select elements in the page, and not the changed one only.
use $(this).children('option:selected') instead.
I am assuming that you are allowing multiple selection on the select element and that is why you are doing += with the $variable.. (you are also adding a space at the end). That means, though, that the variable will be something like "programlar " or "programlar somethingelse".
Your returned JSON though has a key of programlar. A single word, no spaces.. so when you do JSON[$variable] which is the correct way to access an element based on the name in a variable, it does not match.
If the <select> element does not allow multiple selection then the solution is
$("select").change(function() {
var $variable = $(this).children("option:selected").text();
$("div.yaz").text( $variable );
$('#result').html('loading...');
$.getJSON('program-bilgileri.php', function(JSON) {
$('#result').empty();
$.each(JSON[$variable], function(i, program) {
$('#result')
.append(program.isim + '<br />')
.append(program.bilgi + '<br />')
.append(program.adres + '<hr />');
});
});
}).trigger('change');
If indeed it is a multiselect and each option can appear in the JSON then you must check for each option found in the variable.
$("select").change(function() {
var $variable = $(this).children("option:selected").map(function(){
return $(this).text();
}).get();
$("div.yaz").text( $variable.join(' ') );
$('#result').html('loading...');
$.getJSON('program-bilgileri.php', function(JSON) {
$('#result').empty();
for (index=0, length = $variable.length; index < length; index ++) {
$.each(JSON[$variable[index]], function(i, program) {
$('#result')
.append(program.isim + '<br />')
.append(program.bilgi + '<br />')
.append(program.adres + '<hr />');
});
}
});
}).trigger('change');
Try
$.each(JSON['programlar'], function(i, program) ... );
This will iterate over this part of your returned JSON object from PHP:
{
"isim":"Zone Alarm",
"bilgi":"bilgisayarın güvenliğini sağlar",
"adres":"www.zonealarm.com"
},
{
"isim":"Opera",
"bilgi":"güvenli ve hızlı bir web tarayıcısıdır",
"adres":"www.opera.com"
},
{
"isim":"Photoshop",
"bilgi":"güçlü bir imaj işleme yazılımıdır",
"adres":"www.adobe.com"
}
Related
I don't know why my code is giving error while making the ajax call and not responding or working at all. I ran this on an html file. I took this function - getParameterByName() from another stackoverflow answer.tweet-container tag is down the code below outside this script and an empty division.I tried some jquery also.
<script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
$(document).ready(function(){
console.log("working");
var query = getParameterByName("q")
// console.log("query");
var tweetList = [];
function parseTweets(){
if (tweetList == 0){
$("#tweet-container").text("No tweets currently found.")
} else {
//tweets are existing, so parse and display them
$.each(parseTweets, function(key, value){
//console.log(key)
// console.log(value.user)
// console.log(value.content)
var tweetKey = value.key;
var tweetUser = value.user;
var tweetContent = value.content;
$("#tweet-container").append(
"<div class=\"media\"><div class=\"media-body\">" + tweetContent + "</br> via " + tweetUser.username + " | " + View + "</div></div><hr/>"
)
})
}
}
$.ajax({
url:"/api/tweet/",
data:{
"q": query
},
method: "GET",
success:function(data){
//console.log(data)
tweetList = data
parseTweets()
},
error:
function(data){
console.log("error")
console.log(data)
}
})
});
</script>
strong text
Fix the quotes to resolve your syntax error:
$("#tweet-container").append("<div class=\"media\"><div class=\"media-body\">" + tweetContent + " </br> via " + tweetUser.username + " | " + "View</div></div><hr/>")
I'd like to receive the value of type of an input.
Docs: KendoTooltip
$("input").kendoTooltip({
content:
function () {
return '<div>' + this.attr("type") + '</div>';
}
});
But I can't finy any way to work with this..
It was so simple: e.target.attr("value")
content:
function (e) {
var text = e.target.attr("value");
return '<div>' + text + '</div>';
}
I have a Kendo Grid and I want to pass a parameter to my Controller Action. I am able to use the transports read.data successfully but I'm trying to learn how to use the parameterMap functionality.
Here is what I have that works:
<script>
$(document).ready(function () {
var employeeNumber = #(ViewBag.EmployeeNumber); //passed in from controller
$("#ShoppingCartGrid").kendoGrid({
dataSource: {
dataType: "json",
type:"GET",
transport: {
read: {
url:"../Requisitions/GetShoppingCartSummary/",
data: {
employeeNumber:employeeNumber //passing param this way works
},
}
},
schema: {
...... //omitted for brevity
</script>
Here is what does not work but I don't know what I should put here:
<script>
$(document).ready(function () {
var employeeNumber = #(ViewBag.EmployeeNumber);
$("#ShoppingCartGrid").kendoGrid({
dataSource: {
dataType: "json",
type:"GET",
transport: {
read: {
url:"../Requisitions/GetShoppingCartSummary/"
},
parameterMap:function(options,operation){ // here is where I'm
if (operation == "read") { // running into issues- even
return employeeNumber:"140412"; // hard coding param- no joy
}
};
},
schema: {
...... //omitted for brevity
</script>
I have looked for hours for a solution but I can't seem to find a post that explains this concept well enough for me to grasp. Please don't send links to Kendo's documentation, been there, have the mental scars to prove it. Thanks for any suggestions.
Your transport datatype is Json, therefore you need to return valid Json parameters. Kendo appends result of function provided in parameterMap to the method name you defined in your url.
In your case - employeeNumber:"140412" is not a valid Json, you need to provide parmas in following format { paramname : value , otherparamname : value }.
It is very handy to use JSON.stringify(o) to get your params correct.
Below structure for parameterMap works for me:
parameterMap: function (o, operation) {
var output = null;
switch (operation) {
case "create":
output = '{ id: ' + JSON.stringify(o) + ' }';
break;
case "read":
output = '{ id: ' + globalVariable + ' , filters: ' + JSON.stringify(o) + '}';
break;
case "update":
output = '{ id:' + JSON.stringify(o) + '}';
break;
case "destroy":
output = '{ id : ' + o.param+ ' }';
break;
}
return output;
}
Bit more detail as per your comment :
parameterMap: function (o, operation) {
var output = null;
switch (operation) {
case "read":
var txt1 = $('#myTextBox1').val();
var txt2 = $('#myTextBox2').val();
var txt3 = $('#myTextBox3').val();
output = '{ textBoxValue1: ' + txt1 + ', textBoxValue2: ' + txt2 + ',textBoxValue3: ' + txt3 + '}';
break;
}
return output;
}
Server side method signature should look like :
GetShoppingCartSummary(string textBoxValue1, string textBoxValue2, textBoxValue3);
OK, I figured it out. I had to enclose the return statement in curly brackets.
Here is what I ended up with that works:
<script>
$(document).ready(function () {
var employeeNumber = #(ViewBag.EmployeeNumber);
$("#ShoppingCartGrid").kendoGrid({
dataSource: {
dataType: "json",
type:"GET",
transport: {
read: {
url:"../Requisitions/GetShoppingCartSummary/"
},
parameterMap:function(options,operation){
if (operation == "read") {
return{
employeeNumber:employeeNumber
};
};
} //parameterMap
}, //transport
schema: {
....Omitted for Brevity
</script>
I would still like to figure out some other options like how to build an array of optional parameters and then return the array. But this is the answer to the question I asked. Hope it helps someone else.
i have to items on my html
a Input text (company) field and a select (Company_List)
when user types in the text field i want jQuery to use /Home/SearchSynonym/ to get the names and display it in select (the SearchSynonym takes the value user types and do a wildcard search and returns ID and NAME )
can some one help , am new ti jQuery
Leb
You need to clarify as to in which format does SearchSynonym return the IDs and NAMEs? Is it in JSON? If it is in JSON, then try the following:
var companyList = $("#Company_List");
$("#company").change( function(){
$.getJSON("/Home/SearchSynonym/",{ query: $(this).val() }, function(response){
var responseList = "";
$.each(result, function(index, item){
responseList += "<option value='" + item.id + "'>" + item.name + "</option>";
});
companyList.html(responseList);
});
});
This would work if your 'company' text field bears the id="company" in the tag decleration, your 'Company_List' dropdown bears the id="Company_List" in the tag decleration and your server end receives the parameter "query" for pulling records.
You can use setTimeout. Try this:
var companyList = $("#Company_List");
$("#company").change( function(){
setTimeout( function() {
$.getJSON("/Home/SearchSynonym/",{ query: $(this).val() }, function(response){
var responseList = "";
$.each(result, function(index, item){
responseList += "<option value='" + item.id + "'>" + item.name + "</option>";
});
companyList.html(responseList);
});
}, 2000);
});
The value of 2000 indicates a 2 second delay.
I have a plugin which retrieves JSON data from external file and appends it to the "div#slider", the data is retrieved and is working fine but the easySlider is not initialized after retrieving the data successfully . and the slide does not starts.
I have codes on http://lkamal.com.np/r3dImage
my plugin code is as follows:
(function($) {
$.fn.r3dImage = function(options){
var defaults = {
url: 'ajax/test.txt',
pause: 2000,
};
var options = $.extend(defaults, options);
//retrive json file
return this.each(function() {
obj = $(this);
var body = obj.html();
getJson();
});
function getJson(){
$.ajax({
type: "POST",
url: options.url,
dataType: "json",
cache: false,
contentType: "application/json",
success: function(data) {
//alert("Success");
$.each(data.dashboard, function(i,post){
obj.html('<li><img src="' + post.ImageUrl + '" title="' + post.OverlayText +'" /></li>');
});
$(obj).easySlider({
pause: options.pause
});
},
error: function(xhr, status, error) {
alert(xhr.status);
}
});
};
/* this.each(function() {
$(options.container).easySlider({
pause: options.pause
});
});*/
};
})(jQuery);
and another is easy slider 1.7.
or
can i do it inside the easyslider plugin.
How Can i merge this two plugin and make one.
I got solution for this also.
$(function() {
$.fn.r3dImage = function(param) {
var options = {
url : "",
pause : 2000,
feedFetchDelay : 10
};
this.each(function() {
var element = $(this);
//alert(element.attr('id'));
element.html("<ul></ul>");
options = $.extend(options,param);
if(options.url=="") { console.log("URL is not specified"); }
else {
getJsonFeed(element); //retrives json feed and appends to respective div
setInterval(getJsonFeed, options.feedFetchDelay*1000*60); //Time interval in milli seconds converted to minute using delay*1000*60
}
});
function getJsonFeed(element){
//function to retrive json feed start using post of json data
$.post(
options.url,
function(data) {
//alert(data.dashboard);
html = '';
$.each(data.dashboard, function(k,v) {
html += '<li>';
html += '<a href="'+v.TargetUrl+'" target="'+v.Target+'">';
html += '<img src="' + v.ImageUrl + '" alt="' + v.Alt +'" title="' + v.OverlayText +'" />';
html += '</a><p>'+v.OverlayText+'</p></li>';
});
//alert(html);
$("ul", element).append(html); //appending the json data with respective div
//initialize the slider to easy slider
$(element).easySlider({
auto: true,
continuous: true
});
},
"json"
);
}
}
});