Send jquery array via ajax into rails controller - javascript

i need to send one array into rails controller via jquery ajax
jquery CODE
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<input type="text" placeholder="Role" name="Role' +
counter +
'" id="textbox' + counter + '" value="" > <input type="text"
placeholder="Search" name="search' + counter +
'" id="se" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#getButton").click(function () {
var fd = new FormData($("#movie-form")[0]);
var name = document.getElementById("file").files[0].name;
var arr = [];
var msg = '';
for(i=1; i<counter;i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
arr[i] = $('#textbox' + i).val();
}
$.each(arr,function(index, item)
{
alert(index);
alert(item);
}
);
fd.append( 'file', name);
fd.append( 'file22', name);
$.ajax({
url: '/create',
data: {fd:fd,arr:arr},
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
return false;
});
But it shows the error
Error occurred while parsing request parameters.
Contents:
REXML::ParseException (The document "[object Object]" does not have a valid root):

To do an ajax POST request via jquery the data has to be a string.
$.ajax({
url: "/create",
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(formData),
function(data){
alert(data)
}
});
Watch out for JSON being undefined in IE6/7. If you need to target those browsers, use this: https://github.com/douglascrockford/JSON-js

Could you console.log your array? That'll be much easer and you can inspect the sub elements when you click on it. In FireFox (with FireBug plugin installed) or in Chrome press F12 to open the dev tools and see the console.
I don't think this will work for IE but you can convert a JavaScript object to JSON with JSON.stringify so you can send your msg as JSON:
try:
for(i=1; i<counter;i++){
arr[i] = $('#textbox' + i).val();
}
msg= JSON.stringify(arr)
The error you're having is from your rails app but you have not posted any code where that error happens.
I'm not sure what rexml does in rails so can't realy help you with that one.

Related

Getting attribute from XML with my script

I try to read a specific value of a XML feed. Evertyhing is working but I want to read the "StartTime=" value too.
This is the XML:
<Program StartTime="17:00:00" EndTime="17:30:00">
<Name>name</Name>
</Program>
And this is the code:
$.ajax({
type: "GET",
url: "./data.xml",
dataType: "xml",
error: function (e) {
alert("An error occurred while processing XML file");
console.log("XML reading Failed: ", e);
},
success: function (response) {
$("ul").children().remove();
$(response).find("Program").each(function () {
var _name = 'Program: ' + $(this).find('Name').text();
console.log(_name);
var _time = 'Time: ' + $(this).find('StartDateTime').text();
// add content to the HTML
$("ul").append('<li>' + _name + '</li>');
$("ul").append('<li>' + _time + '</li>');
});
}
});
}
I found some interesting information, but I can't actually use it...
The StartTime is an attribute of <Program>, not an element/node inside it. find() is for elements that are descendants.
Use attr() instead
Try:
var _time = 'Time: ' + $(this).attr('StartDate')

400 bad request for ajax call with GET request parameter passed to controller in spring

i'm showing a drop down list in a page based on the selection i have to show dependent drop down by passing the selected value in drop down list to the controller and return json data as response.please find below code and help me for resolving this .
Please find below ajax code
<script type="text/javascript">
jQuery(document).ready(function () {
$.ajax({
type: 'POST',
dataType : 'json',
contentType : "application/json",
url : "${home}getOPList",
cache: false,
success: function(response){
// var str = JSON.stringify(response);
var operatorList;
// alert("yes");
// alert(str);
for (var i = 0; i < response.length; i++ )
{
console.log(response[i].listOfOperators);
operatorList +="<option value =' "
+ response[i].sno +
" '>"
+ response[i].listOfOperators +
"</option>"
}
$('#opList').html(operatorList);
},
error: function(){
alert('Error while request..');
}
});
$("#opList").change(function(){
$.ajax({
type: 'GET',
dataType : 'json',
contentType : "application/json",
url : "${home}partnerDetails?operator =" +opList,
cache: false,
success: function(response){
// var str = JSON.stringify(response);
var partnerList;
alert("yes");
alert("oplist " + opList);
for (var i = 0; i < response.length; i++ )
{
console.log(response[i].campaignName);
partnerList +="<option value =' "
+ response[i].sno +
" '>"
+ response[i].campaignName +
"</option>"
}
$('#ptList').html(partnerList);
},
error: function(){
alert('Error while request in partners..');
}
});
});
});
</script>
above is the ajax code and when the code gest executed it is directly showing " Error while request in partners.. ".in console it says it is a bad request with 400 response code for the below url.
http://localhost/Promotions/partnerDetails
please suggest on this

How to save the data into database in jquery and display upon the screen using web api

I want to add the values inot the database but I am not to able to do that.
var Array;
$(document).ready(function ()
{
$.ajax({
url: '../api/Emp/GetAll',
type: 'Get',
cache: false,
datatype: 'json',
success: function (text) {
Array = text.Table;
var List = JSON.stringify(text);
for (var i = 0; i < data.length; i++) {
var Id = Array[i].id;
var Name =Array[i].name;
var city = Array[i].city;
$('#table body').append('<tr><td>' + Id + '</td><td><input type="text" value="' + Name + '" id="txt' + Id + '" /></td><td>' + city + '</td> </tr>');
}
}
})
If you need to put it back into the database you just need to reverse the process.
Use post for your type and send the data back with ajax to a php script page that inserts the data into your database.
You can edit the data on the php page before you insert it into the database or you can edit the data with javascript then send it back to php page.
Create an ajax post
$.ajax({
type: "post",
datatype: "json",
url: "insertPage.php",
data: {dataNameHere: editedDataGoesHere},
success: function(data){
alert("SUCCESS");
},
error: function(e){
alert("ERROR");
}
});
And then in your PHP:
$obj = $_POST['dataNameHere'];
and insert it into your database like you normally would.

Jquery each data object attribute

I am trying to create table rows containing data from each attribute from my object response using $.each, however the Id, Purpose, and Amount are coming back undefined. I have tested the response in Fiddler and the data is all being received correctly, the problem just seems to be in the "item" part. Here is my Jquery:
$.ajax({
type: "GET",
url: "https://chad-test4.clas.uconn.edu/api/Commitments/GetCommitmentPurposes/2",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (response) {
var purposes = $("#purposes tbody");
if (response.Success == true) {
purposes.empty();
var buttons = '<tr><td><button type="button" class="btn-primary">Save</button>'
+ '<button type="button" class=".btn-danger">Delete</button></td>'
var list = response.Data;
$.each(list, function (i, item) {
purposes.append(buttons + '<td><select id=' + item.Id + '>' + item.Purpose + '</select>'
+ '<td><input type="text" val =' + item.Amount + '/>')
});
}
}
});
});
Could you post a snippet of JSON aswell ?
Basically I believe what you need to do is to access the entries by an identifier:
$.each( list.items, function(i, item ) {
But posting JSON would clarify if that is true.

load local json file issues

I'm having as issue loading a localhosted json file. The url path is correct. I have no idea why it isnt working. IDeas would be lovely
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: '../json/test.json',
success: function(json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var title = json.results[i].event;
var href = json.results[i].event;
var button =
"<button class='redirect-button' color='green' data-url='" +
href + "'>Compare</button>";
$("#apple").append("<tbody><tr><td>" + title +
"</td><td>" + button + "</td></tr></tbody>"
);
$("#apple").find(".redirect-button").click(function() {
location.href = $(this).attr("data-url");
});
}
},
error: function(error) {
console.log(error);
}
});
Think u're using the wrong parametr on the $.parseJSON, cause u defined the json as the name of the return variable on the succes: function(json) and is using the not declared data as the variable to the parsing, try to replace it to $.parseJSON(json) instead, or change the sucess: function(json) to sucess: function(data)

Categories