I have this table that receive from the server:
(with ajax):
$.each(data, function(i, item) {
$('#MyTable tbody').append("<tr>"d
+"<td>" +data[i].A+ "</td><td>"
+data[i].B
+"</td><td><input type='text' value='"
+data[i].C+"'/></td><td><input type='text' value='"
+ data[i].D+"'/></td>"
+ "</tr>");
});
C and D are edit text, that the user can change. after the changing by the user I want to "take" the all new data from the table and send it by ajax with JSON.
how can I read the data to a JSON?
I start to write one but I am stuck on:
function saveNewData(){
var newData= ...
$.ajax({
type: "GET",
url: "save",
dataType: "json",
data: {
newData: newData},
contentType : "application/json; charset=utf-8",
success : function(data) {
...
},
error : function(jqXHR, textStatus, errorThrown) {
location.reload(true);
}
});
}
thank you
Try something like this,
function getUserData()
{
var newData = new Array();
$.each($('#MyTable tbody tr'),function(key,val){
var inputF = $(this).find("input[type=text]");
var fileldValues = {};
fileldValues['c'] = $(inputF[0]).val();
fileldValues['d'] = $(inputF[1]).val();
//if you want to add A and B, then add followings as well
fileldValues['a'] = $($(this).children()[0]).text();
fileldValues['b'] = $($(this).children()[1]).text();
newData.push(fileldValues);
});
return JSON.stringify(newData);
}
function saveNewData(){
var newData = getUserData();
$.ajax({
type: "GET",
url: "save",
dataType: "json",
data: {
newData: newData},
contentType : "application/json; charset=utf-8",
success : function(data) {
...
},
error : function(jqXHR, textStatus, errorThrown) {
location.reload(true);
}
});
}
http://jsfiddle.net/yGXYh/1/
small demo based on answer from Nishan:
var newData = new Array();
$.each($('#MyTable tbody tr'), function (key, val) {
var inputF = $(this).find("input[type=text]");
var fileldValues = {};
fileldValues['c'] = $(inputF[0]).val();
fileldValues['d'] = $(inputF[1]).val();
newData.push(fileldValues);
});
alert(JSON.stringify(newData));
use the jquery on event binding
try somthing like this. Fiddler Demo
$('#MyTable').on('keyup', 'tr', function(){
var $this = $(this);
var dataA = $this.find('td:nth-child(1)').text() // to get the value of A
var dataB = $this.find('td:nth-child(2)').text() // to get the value of B
var dataC = $this.find('td:nth-child(3)').find('input').val() // to get the value of C
var dataD = $this.find('td:nth-child(4)').find('input').val() // to get the Valur of D
// $.ajax POST to the server form here
// this way you only posting one row to the server at the time
});
I don't normaly do that I would use a data binding libarray such as Knockoutjs or AngularJS
Related
I have been developing an app to connect with an API I recently built for testing (It is working fine) but I deem to be getting an unknown error with my code. I am a newbie trying out jQuery. This is my code:
$(document).ready(function(){
$.ajax({
url: 'api.lynmerc-enterprise.com/requests',
async: false,
type: 'GET',
//dataType: 'json',
success: function(data){
console.log(data);
var data2 = jQuery.parseJSON(data);
console.log(data2);
//assign parsed JSON to variables
var apiStatus = data2.status;
var apiMessage= data2.message;
var apiData = data2.data;
var data3 = $.parseJSON(apiData);
//Here we get Requester info and material JSON
console.log(data3);
var materials = data3.material;
var data4 = $.parseJSON(materials);
console.log(data4);
//loop through the data and assign needed info to table
$.each(data3, function(i,row){
var dateRequested = data3.date;
var projectCode = data3.p_code;
var requestNumber = data3.rq_no;
var materialName = data4.name;
var purpose = data4.purpose;
var quantity = data4.quantity;
var cost = data4.cost;
var total = data4.total;
$("table.table").append("<tr><td>"+dateRequested+"</td><td>"+projectCode+"</td><td>"+requestNumber+"</td><td>"+materialName+"</td><td>"+purpose+"</td><td>"+quantity+"</td><td>"+cost+"</td><td>"+total+"</td></tr>");
});
},
//error: function(){console.log('Error Encountered')},
beforeSend: setHeader()
});
});
//set required headers
function setHeader(xhr){
xhr.setRequestHeader('Api-Key','ZHhjZmIyMHdnazVtdWw=');
xhr.setRequestHeader('Content-Type','application/json')
}
The code is supposed to connect to the API with the Api-Key as a header then fetch Json of format
{
'status':success,
'data':'[{
"p_code":,"requester_id":,
"date":,"rq_no":,
"id":, "materials":[{
"name":,
"purpose":,
"cost":,
"quantity":,
"status":,
"rq_no":,"id":,
"total":},
...
]}
.....
]'
... The data is to be assigned to variables then appended to the main HTML table
I finally had it working perfectly:
<script type="text/javascript">
function fetchJson(){
$(document).ready(function(){
$.ajax({
url: 'http://api.lynmerc-enterprise.com/requests',
headers: {
'Api-Key':'ZHhjZmIyMHdnazVtdWw='
//'Content-Type':'application/json'
},
//async: false, //return value as variable not to make an async success callback
type: 'GET',
dataType: 'json',
success: function(data){
console.log(data);
//var data2 = JSON.parse(data.data);
var data2 = data.data;
var data2Array = [];
$.each(data2, function(idx, data2){
console.log(data2.p_code);
console.log(data2.date);
console.log(data2.rq_no);
var userfo = data2.user;
console.log(userfo.fullname);
console.log(userfo.project_site);
var material = data2.materials;
var dateRequested = data2.date;
var requestNumber = data2.rq_no;
var requester = userfo.fullname;
var projectSite = userfo.project_site;
$.each(material, function(idx, material){
console.log(material.name);
console.log(material.purpose);
console.log(material.quantity);
console.log(material.cost);
console.log(material.total);
console.log(material.status);
var materialName = material.name;
var purpose = material.purpose;
var quantity = material.quantity;
var cost = material.cost;
var total = material.total;
var requestStatus = material.status;
/*$('#dateRequested').append(dateRequested);
$('#requestNumber').append(requestNumber);
$('#requester').append(requester);
$('#projectSite').append(projectSite);
$('#materialName').append(materialName);
$('#purpose').append(purpose);
$('#quantity').append(quantity);
$('#cost').append(cost);
$('#total').append(total);
$('#requestStatus').append(requestStatus); */
var table = $("#requestsTable");
table.append("<tr><td>"+dateRequested+
"</td><td>"+requester+
"</td><td>"+projectSite+
"</td><td>"+requestNumber+
"</td><td>"+materialName+
"</td><td>"+purpose+
"</td><td>"+quantity+
"</td><td>"+cost+
"</td><td>"+total+"</td></tr>");
});
});
},
error: function(){console.log('Error Encountered')},
//beforeSend: setHeader()
});
});
/* var request;
function setHeader(request){
request.setRequestHeader('Api-Key','ZHhjZmIyMHdnazVtdWw=');
request.setRequestHeader('Content-Type','application/json')
}*/
}
</script>
When using dataType:'json' in the code, we dont parse the json again as jQuery does all that so when we try to parse again it returns an error. Then for it to be appended to html we use $(selector).append where the selector is the element id. In this case when appending to table, we append to so it will be $(#tableBodyId).append("what to append");
I am trying to implement a comment feature on my page. I have an itemID 123. on that page, I would like to display the comments that people have posted about itemID 123. However as of now, I am unable to display these comments on my page. There are no errors in the console.
Javascript:
function mywall() {
var url = serverURL() + "/viewwall.php"; //execute viewwall.php in the server
itemID = decodeURIComponent(getUrlVars()["itemID"]);
var JSONObject = {
"itemID": decodeURIComponent(getUrlVars()["itemID"])
};
$.ajax({
url: url,
type: 'GET',
data: JSONObject,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_mywallresult(arr); //success. execute _mywallresult()
},
error: function () {
validationMsg();
}
});
}
function _mywallresult(arr) {
var i;
//for all the shouts returned by the server
for (i = 0; i < arr.length; i++) {
//append the following:
//<b>
//time of posting </b>
//<br/>
//the message
//<br>
//userid
$("#wallcontentset").append("<b>" + arr[i].timeofposting + "</b><br/>" + arr[i].message + "<hr>" + arr[i].userid);
}
}
HTML:
<div data-role="content" class="ui-content" id="wallcontentset"></div>
Try the following :
success: function (response) {
_mywallresult(response.arr);
},
I have this div
<div class='additional_comments'>
<input type="text" id='additional_comments_box', maxlength="200"/>
</div>
Which will only sometimes appear on the page if jinja renders it with an if statement.
This is the javascript i have to send an ajax request:
$(document).ready(function() {
var button = $("#send");
$(button).click(function() {
var vals = [];
$("#answers :input").each(function(index) {
vals.push($(this).val());
});
vals = JSON.stringify(vals);
console.log(vals);
var comment = $('#additional_comments_box').val();
var url = window.location.pathname;
$.ajax({
method: "POST",
url: url,
data: {
'vals': vals,
'comment': comment,
},
dataType: 'json',
success: function (data) {
location.href = data.url;//<--Redirect on success
}
});
});
});
As you can see i get the comments div, and I want to add it to data in my ajax request, however if it doesnt exist, how do I stop it being added.
Thanks
You can use .length property to check elements exists based on it populate the object.
//Define object
var data = {};
//Populate vals
data.vals = $("#answers :input").each(function (index) {
return $(this).val();
});
//Check element exists
var cbox = $('#additional_comments_box');
if (cbox.length){
//Define comment
data.comment = cbox.val();
}
$.ajax({
data: JSON.stringify(data)
});
I'm trying to scrape this page
<script>
var convertToInt;
var allData = [];
$.ajax({
url: "http://en.wikipedia.org/wiki/Demographics_of_Europe",
type: 'GET',
cache: false,
success: function(data) {
var root, body, table;
root = $("<div></div>")
root.html(data.responseText)
var rows = root.find("table tr:not(:has(th))");
$.each(rows, function(index, value) {
var datatest = $(this.find("td"));
console.log(datatest);
});
},
error: function() {
return console.log("error");
}
});
But the console returns the error "Uncaught TypeError: Object #<HTMLTableRowElement> has no method 'find'"
It should be
datatest = $(this).find("td");
You missed the )
I am trying to populate a dropdownbox with data from a JSON page.
Here is the code I am using:
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$.ajax({
url: "json/wcf.svc/GetTax",
dataType: 'json',
data: data
});
$($.parseJSON(data.msg)).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#taxList');
});
</script>
And here is what the json data returns:
{"d":"{\"16\":\"hello\",\"17\":\"world\"}"}
I am getting an error that "data is undefined." Do I have to somehow tell JQ how to read the json data?
Firstly, the data variable you are passing to the ajax call is not defined (well, not in the code sample you provided), and secondly the ajax call is happening asynchornously, so you need to do something with the returned data, i.e. via a success callback. Example:
$(document).ready(function () {
var data = //define here
$.ajax({
url: "json/wcf.svc/GetTax",
dataType: 'json',
data: data, // pass it in here
success: function(data)
{
$(data.msg).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#taxList');
}
});
});
also you shouldn't need to parse the data returned from the ajax call, as jQuery will automatically parse the JSON for you, ( should need the $.parseJSON(data.msg))
EDIT
Based on the interesting format of the JSON, and assuming that it cannot be changed, this should work (ugly though)
$(document).ready(function () {
var data = //define here
$.ajax({
url: "json/wcf.svc/GetTax",
dataType: 'json',
data: data, // pass it in here
success: function(data)
{
data = data.d.replace(/{/g, '').replace(/}/g, '').split(',');
var obj = [];
for (var i = 0; i < data.length; i++) {
obj[i] = {
value: data[i].split(':')[0].replace(/"/g, '').replace('\\', ''),
label: data[i].split(':')[1].replace(/"/g, '')
};
}
var htmlToAppend = "";
for (var j = 0; j < obj.length; j++) {
htmlToAppend += '<option value="' +
obj[j].value +
'">' + obj[j].label +
'</option>';
}
$('#taxList').append(htmlToAppend);
}
});
});
You need to use the success option to return the data.
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$.ajax({
url: "json/wcf.svc/GetTax",
dataType: 'json',
success: function(data){
$(data.msg).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#taxList');
}
});
});
</script>