I'm trying to get the data returned from a page which is returning JSON to put itself into an array. This code works, however I can't put the variable (which should be the content) into the jQuery.parseJSON command. It works fine however when I use a ' ... ' string.
$.get( "server/php/index.php", function( data ) {
var data = jQuery.parseJSON(data);
});
If there is any other methods of doing this? What I'm trying to do is get the info from this page where it then puts itself into hidden input fields on a form.
Thanks in advance.
Don't pass the data into another variable called data. Call it something else and if you want to use it outside of your AJAX call then make sure you declare the variable elsewhere in your code so you can pass the data to it and use it.
var dataStorage;
$.get( "server/php/index.php", function( data ) {
dataStorage = jQuery.parseJSON(data);
});
Try removing the "var". Don't initialize data another time.
$.get( "server/php/index.php", function( data ) {
data = jQuery.parseJSON(data);
});
Related
as we use $_REQUEST in PHP to receive post/get values, I'm looking for a similar function/key to receive values sent through $.ajax.. in java script/j query
example:
<script>
function do_something(){
// here i want the value sent using ajax
return term;
}
$('#input').keyup(function(){
var term=$(this).val();
$.ajax({
url:do_something(),// << is this possible?? or should i try
//url:do_something(term) //<< this???
dataType:'json',
data:{term:term},
results:function(data){
alert(JSON.stringify(data));
}
});
</script>
document.location.search can get GET values of the current URL.
When used like this:
document.location.search.substr(1).split("&");
you can get an array containing all GET keys and values like key=value. Then by simply splitting them on = you get the value.
Using this answer How to get all child inputs of a div element (jQuery) I fetch all Inputs inside a specific <div>.
I further want to send the inputs via ajax, the number of inputs is not fixed so instead of manually putting each input into the json data to send, I want to use each() and - here comes the point where I don't know - append each name and value to json.
$('#mydiv :input').each(function(k, v) {
postData += [{ $(v).attr("name"): $(v).val() }];
}
$.post("url.htm", postData, function( data ) { /***/ });
There must be a tiny error inside this but I can't figure out.
Looks like the serializeArray function is what you need:
$.post("url.htm", $('#mydiv :input').serializeArray(), function( data ) { /***/ });
Since you want to send postdata, try making an array first, and then you need to do like this
var postData=[];
('#mydiv :input').each(function(k, v) {
postData.push({ $(v).attr("name"): $(v).val() });
}
$.post("url.htm", postData, function( data ) { /***/ });
A word of caution, when making POST call, do specify the 4th parameter as "json" in case the expected response is JSON.
I am having an issue trying to set the data name or the objects being passed in. I am writing a system that uses AJAX to send requests to the server which then returns the necessary data. However, I am trying to make things generic to where if the developer adds more "slates" then it will automatically send the request on its behalf. The code looks as following:
$(document).ready(function() {
$(".slate").each(function(){
$.get("requests.php", { $(this).attr('name') : "true" }, function(data){
});
});
});
in other words it takes the name of the element and applies it to the query string. JavaScript doesn't seem to like the
$(this).attr('name')
in the syntax which is understandable since it expects just text (not a var or a string). Is there a way to make this work? Any help is greatly appreciated!
$(document).ready(function() {
$(".slate").each(function(){
var data = {};
data[$(this).attr('name')] = "true";
$.get("requests.php", data, function(data){
});
});
});
I'm using coldfusion and jquery. This is my first real go at jquery and I've searched and read for a long time without cracking this so any help would be greatly appreciated...
Ok, I have an autocomplete returning an id. I'm then passing the id to a second function that returns an array of datatype json. The autocomplete works great and I can get the json to display in an alert box but am a bit stuck on how to use the json results.
I'm trying to loop through the json array and write the values into radio buttons, which then dynamically display on page... So the whole idea is this.
user is selected from drop box and id is returned
user id from selection is passed to user options function and user options are returned in json arrary.
json array is looped through and on each iteration a radio button is created with appropriate values.
all radio buttons are then output to screen for access and selection.
The code I have so far is this :
<script type="text/javascript">
// <!--
$(document).ready(function() {
$("#userName").autocomplete({
cache:false,
source: "/jqueryui/com/autocomplete.cfc?method=getUser&returnformat=json",
//setup hidden fields
select:function(event,ui) {
var uid = ui.item.id;
$("#userid").val(ui.item.id);
// start call to get user options
$.ajax({
type: "POST",
url: "/jqueryui/com/autocomplete.cfc?method=getUserOptions&returnformat=json",
data: ({ userid: uid }),
success: function(data) {
alert(data)
}
});
/// end call to get user options
}
});
});
// --->
</script>
The json displayed in the "alert(data)" popup, which looks fine, is this :
[{"productname":"licence free","quantity":1,"term":12,"id":1},
{"productname":"licence basic","quantity":1,"term":24,"id":1},
{"productname":"licence full","quantity":1,"term":12,"id":2}]
I need to know how to loop through this data and create a radio button for each option, probably something like this, and display them all on screen, which I'm guessing I'll just write to a via the dom once I have something to write :
<input type="radio" name="userOption" value="#id#|#qty#|#term#">#productname#
I have tried a few things, without success, such as :
for(var i =0;i<Data.length-1;i++)
{
var item = Data[i];
alert(item.productname + item.id);
}
And
$.each(data.items, function(i,item){
alert(item);
if ( i == 3 ) return false;
});
I couldn't get either of these to work.
Anyway this is getting a bit long winded. Hope it's clear, and again any help or suggestions appreciated.
Thanks!
First check the datatype of the data parameter returned. You might first need to use .parseJSON() to construct a JSON object.
Then your for loop syntax is not correct. this code works for me:
var data = [{"productname":"licence free","quantity":1,"term":12,"id":1},
{"productname":"licence basic","quantity":1,"term":24,"id":1},
{"productname":"licence full","quantity":1,"term":12,"id":2}];
for (var i=0; i<data.length; i++) {
alert(data[i].productname);
}
Here's a jsfiddle
Try checking parseJSON jquery function.
I quess that the type is a string? If so try it with the javascript function eval. It converts a string to a javascript type.. in your case something like this should work:
Var new_data = eval(data);
Now it should be a workable array/object
Edit: to stay with the data variable:
data = eval(data);
Edit 2:
Your ajax call misses the dataType property:
dataType: "json"
With this you dont need the stuff above i said
Use a each loop to get data and appendTo function to print data in an HTML element with result1 id:
dataType:"json", //nature of returned data
success: function(data) {
var content = '';
$.each(data, function(i, dbdata) {
content += '<p>' + dbdata.columnName + '<p>';
});
$(content).appendTo("#result1");
}
I'm trying to get data returned from a controller and append it to a div. Here is the code I have:
$(this).parent().find('list').append(__WHAT_GOES_HERE?__);
How should I get data to append using ajax in JQuery? I know this is a very basic question -- I'm new to JS :(
PS. Lets assume the controller's path is /ajax_get_items
I assume you want to load it into a class, so list would be .list
Something like:
$.ajax({
url: "/ajax_get_items",
type : "POST",
data : { // If you need data to be posted
id : 12,
num : "test"
},
success : function(result){
$(this).parent().find('.list').append(result);
// If a JSON object is returned, use the following line:
// $(this).parent().find('.list').append(result.html);
}
})
Or if you want to just load data without params (GET method):
$(this).parent().find('.list').load("/ajax_get_items");
If you want more information about ruby rails and jQuery: http://brandonaaron.net/blog/2009/02/24/jquery-rails-and-ajax
This is what you need:
$.ajax({
url: '/ajax_get_items',
success: function(data) {
$('#selector').parent().find('list').append(data)
}
});
Note that you can't use 'this' in this context depending on where this call is made, or you might end up with unexpected results
$('somelink').click(function(e) {
e.preventDefault();
$.ajax(url, data, success:function(resData) {
resultSet = resData.extract(resData);
}
}
Basically this part handles the response from the ajax call and extract is supposed to build up your required html from the returned data.
After this you can simply say
$(this).parent().find('list').append(resultSet);
But this assumes the major work is done in the function extract with the returned data.
There you build up your list (or whatever) html is needed.