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.
Related
I'm using a plugin called "Jquery-ui-multisearch" which offers an autocomplete in an input element based on either an array you provide or an external source (ajax/api/etc). Found here: http://bseth99.github.io/jquery-ui-multisearch/index.html
I'm currently attempting to use the plugin to provide an autocomplete suggestion based on an array of strings returned from an ajax database call, but I can't figure out what format the plugin wants to see this in.
Here is the example initalization of the plugin.
$(function() {
$("#myMultiSearch").multisearch({
source: function ( term, callback ) { ... } //A function can implement a data search and should call the passed in callback with the results.
});
});
And here's what my code looks like:
$("#search").multisearch({
source: function (term, callback) {
$.ajax({
type: 'POST',
url: postUrl,
data: {searchterm:term},
})
.done(function(data) { //data == ["abc","abcd","abcde"];
callback(data);
});
});
Looks similar to what they do here: http://bseth99.github.io/jquery-ui-multisearch/examples/movies.html - which looks like this:
source: function( term, callback ) {
movies.search( term ).done( function() { callback( movies.toJSON() ); } );
},
I have also tried callback(data.toJSON()); or changing the output data to things like {"abc","abcd","abcde"} or ("abc","abcd","abcde") etc. etc. All result in either undefined results or a box coming up with no results at all.
So how do I pass the returned array of items to the multisearch function so that it can display it in the results?
Please let me know if I need to communicate anything more specifically - I know it's hard to diagnose problems especially on third party plugins when the asker isn't very clear.
I had posted this as an issue on github last month and the writer got back to me here: https://github.com/bseth99/jquery-ui-multisearch/issues/2
I had to take the array from php and create a new array of hashes from it. Here's my code.
.done(function(data) {
var jsonparse = JSON.parse(data);
var hashArray = [];
jsonparse.forEach(function(entry) {
hashArray.unshift({name: entry});
});
//console.log(hashArray);
callback(hashArray); //Same format as the line below.
//callback([{ name: "item1" },{ name: "item2" }]); //This works.
})
Thanks for your help guys!
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);
});
I'm doing the following jQuery call:
$.getJSON(
"http://localhost:9000/user?name=",
"test",
function(data) {
alert(data.aaData[0]);}
);
but it doesn't work because the data param "test" will be "&test" in the actual call (at least that's what firebug tells me).
I'm a total beginner with JavaScript and jQuery, can anyone tell me how to remove the &-sign in front of the data param?
So that the actual call is http://localhost:9000/user?name=data and not http://localhost:9000/user?name=&data
You could pass the data as an object, like this:
$.getJSON(
"http://localhost:9000/user",
{ name: "test" },
function(data) {
alert(data.aaData[0]);
}
);
The data-object will then be converted to a string and URL-encoded before it is added to the URL. From the jQuery documentation of .getJSON():
If the value of the data parameter is an object (map), it is converted
to a string and url-encoded before it is appended to the URL.
You have to set the get variables to be sent in the correct way:
$.getJSON("http://localhost:9000/user", "name=test", function(data) {
alert(data.aaData[0]);
});
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.