This is the Javascript with the Ajax call, everything is working fine, I don't need to parse JSon 'cause it already comes parsed and the object has an array inside. The problem is when I try to print the array output using the for loop into html, it does not recognize the "data.d.lenght" for some reason. I changed it for an Int to test and all the values were printed in HTML. I even used .done in case the Ajax call was being done after the javascript was running and it changed nothing. I don't know what else I can do besides getting a variable with the array size from codebehind but that is a last resort.
<script type="text/javascript">
function GetColaboradores() {
var url = "GetColaboradoresWebService.asmx/GetColaboradores";
$("#UpdatePanel").html("<div style='text-align:center; background-color:yellow; border:1px solid red; padding:3px; width:200px'>Please Wait...</div>");
var request = $.ajax({
type: "POST",
url: url,
data: "{}",
contentType: "application/json; charset-utf-8",
dataType: "json"
});
request.done(function (data) {
var TableContent = "<table border='0'" +
"<tr>" +
"<td> Nome </td>" +
"</tr>";
for (var i = 0; i > data.d.lenght; i++) {
TableContent += "<tr>" +
"<td>" + data.d[i].Nome + "</td>"
"</tr>";
}
TableContent += "</table>";
$("#UpdatePanel").html(TableContent);
});
request.fail(function () {
});
}
</script>
Thanks everyone, I finally found what was wrong. Not only length was written wrongly but also the condition on the for cycle was wrong. It was "<" and not ">".
Related
Passing one parameter (report.id) to removeUser function works fine, but when I want to pass two parameter (report.id and report.name) I get Uncaught SyntaxError: Invalid or unexpected token.
I tried '(" +report.id +","+ report.name +")'
I tried '(" +report.id report.name +")'
but none works, what I am doing wrong here
$.ajax({
url: "xxx",
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
var html = '';
$.each(result, function (key, report) {
html += '<tr>';
html += '<td>' + report.id + '</td>';
html += '<td>' + report.name + '</td>';
html += "<td><a onClick='removeUser(" +report.id + report.name +")'" + "'> Remove </a></td>";
html += '</tr>';
});
$('#users').html(html);
},
function removeUser(id, name) {
alert("ID: "+ id + "Name: "+ name)
}
You need commas between the parameters, and you need quotes only around report.name.
It's much easier to write this using a template literal rather than concatenation.
html += `<td><a href="#" onClick='removeUser(${report.id}, "${report.name}")'> Remove </a></td>`;
Also, since you're doing this with an a element, you should set its href so it doesn't try to link to another page after running the onclick function.
I am just making a simple UI for display orders from Woocommerce shop. I am successfully getting the JSON response and put it into a HTML table. But I need to update the table without refreshing the whole page or table. Actually i need like, whenever Woocommerce get an order, the HTML table should get updated while highlighting the row. I am using AJAX to update the table but its not updating.
Note - I tried to set particular time interval for refreshing the page but i thought it won't be a good solution.
So far i got this below.
**
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: "https://localhost/site/wp-json/wc/v3/orders?consumer_key=key&consumer_secret=key1",
dataType: 'json',
type: 'get',
cache:false,
success: function(data){
console.log(data);
var event_data = '';
$.each(data, function(index, value){
/*console.log(value);*/
event_data += '<tr>';
event_data += '<td>'+value.id+'</td>';
event_data += '<td>'+value.billing.first_name + value.billing.last_name+'</td>';
event_data += '<td>'+value.date_created+'</td>';
event_data += '<td>'+value.billing.phone+'</td>';
event_data += '<td>'+value.billing.address_1 + ", " + value.billing.address_2 + ", " + value.billing.city + value.billing.postcode +'</td>';
event_data += '<td>'+value.total+'</td>';
event_data += '</tr>';
});
$("#data").append(event_data);
},
error: function(d){
/*console.log("error");*/
alert("404. Please wait until the File is Loaded.");
}
});
});
</script>
**
Any suggestions please.
So the problem is that I'm loading JSON files from url into my html and it's working perfectly besides for the fact that it shows the information twice..
Does anyone know why this is the case?
Here's the Jquery/Javascript code that I use to load the JSON into my html.
$.ajax({
url: 'http://datatank4.gent.be//bevolking/totaalaantalinwoners.json',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
i = 0;
var access;
var url;
$(data).each(function(index, value) {
wijkname = value.wijk;
year = value.year_2010;
i++;
$('#pagewrap2').append(
'<div class="dataond col col-xxs-12 col-md-3"> <h2> ' + wijkname + '</h2><p>' + year + '<div id="maps">' + "<iframe width='100%' height='100%' frameborder='0' scrolling='no' marginheight='0' marginwidth='0' src='https://maps.google.com/maps?&q="+ encodeURIComponent( wijkname + ' ' + 'Gent' ) +"&output=embed'></iframe>" + '</div>' + '</p></div>'
);
});
}
});
First check the response of this ajax call.
If the response look fine maybe you're making the ajax call twice.
For example when you add an event listener twice. (add off() function before click() if you're using jquery)
I've found the problem. Really stupid but I linked my file twice in my index.html...
Thanks everyone for your replies.
<script type="text/javascript">
$(document).ready(function() {
var categoriesId = [];
$.getJSON("http://datatank4.gent.be//bevolking/totaalaantalinwoners.json", function(data) {
$.each(data, function(index, item) {
categoriesId.push(item.wijk);
}
);
for (i = 0; i < categoriesId.length; i++) {
alert(categoriesId[i]);
var newInProductPriceDiv = document.createElement('div');
newInProductPriceDiv.setAttribute('id', "recentlyViewedProductPriceDiv" + i);
newInProductPriceDiv.setAttribute('class', "subcategoryListPriceDiv");
newInProductPriceDiv.innerHTML = newInProductPriceDiv.innerHTML + categoriesId[i];
document.getElementById('pagewrap2' + i).appendChild(newInProductPriceDiv);
}
}
);
}
);
</script>
if you have any confusion then tell me ok . and if you not get your exactly output then also tell me.
I'm new on Rails, and i think this is super simple, just not used to the syntax.
this is the jQuery part,
$.ajax({
type: "get",
contentType: "application/json; charset=utf-8",
url: "/users/search_users",
data: {
name: name
},
dataType: "text",
success: function (result) {
var test = "<%=get_user_list_html(result)%>";
if (result == "User not found") {
alert("User not found");
} else {
//console.log(result);
var peopleData = jQuery.parseJSON(result);
var resultHTML = "<tr>";
resultHTML += "<th></th><th style='display:none'>User ID</th>" + "<th>First Name</th><th>Last Name</th><th>Email Address</th>" + "<th style='display:none'>Time Zone</th>";
resultHTML += "</tr>";
$.each(peopleData, function (index, obj) {
resultHTML += "<tr>";
resultHTML += "<td><input type='checkbox'></td>" + "<td style='display:none;'>" + obj.id + "</td>" + "<td>" + obj.firstname + "</td>" + "<td>" + obj.lastname + "</td>" + "<td>" + obj.email + "</td>" + "<td style='display:none;'>" + "Etc/GMT+9 (Japan)" + "</td>";
//consider now
resultHTML += "</tr>";
});
$("#internal_table").html(resultHTML);
}
},
error: function () {
window.alert("something wrong!");
}
});
in here, i'm going to call get_user_list_html, which is in the helper.
But my problem is, how can i use the result from the respone, i have to send this as a param?
if i just put it like that, it says undefined var.
Ruby code must be executed on the server side, this line: var test = "<%=get_user_list_html(result)%>"; won't work after an ajax call, and it should be in a .erb file.
You can have a ruby + javascript view template with .js.erb extension but ruby code is always executed before your document loads.
I don't know what the helper does but this is not the way to do it.
Solution 1: Render a HTML partial instead of JSON from server. That's make things much easier in you case.
Solution 2: Use a template to render JSON response, say jQuery template or Underscore template.
The usage in your case is not good. You missed better part in both server and client side.
I am dynamically creating a table using data from an AJAX call. I am using a "select/dropdown box" .on('change') function to send values to my PHP. Once the table displays, I want to set focus to a search box dynamically created on the table.
The trouble seems to be that since the table takes a couple seconds to become visible, the .focus() command fires before the table is visible. I would like to have the .focus() command fire after the create table function completes.
Javascript/Jquery Code:
$('#t6F3Box1').on('change', function()
{
var $newTable ='<table id="tempEmployerTbl" class="studentTables"><thead><tr>';
var $searchStr=new RegExp("ID");
var $tableContainerDiv="#t6F3TableCont";
var $rowFlag=0;
var $responseDataValue=[]
var $employerState=$('#t6F3Box1').val();
var $getTableDataPhp="../application/employer.php";
var $data=[];
$('#t6F3ErrDiv').text('');
$('#t6F3TableCont, #t6F3HLine2, #t6F3HLine2').show();
$data += "&employerState=" + encodeURIComponent($employerState);
$.ajax({
type: 'POST',
async: false,
url: $getTableDataPhp,
cache: false,
datatype: 'json',
data: $data,
success: function($responseData)
{
//Loop through the responsdata returned in a JSON Array
//dynamically create the Employer drop down box
if (!$responseData.authenticationError)
{
//Create the header for the Employer Table
$.each($responseData, function($key, $value)
{
if($rowFlag==0)
{
$responseDataValue=$responseData[$key];
$.each($responseDataValue, function($keys, $values)
{
if ($searchStr.test($keys))
{
$newTable += '<th class="tableDataHide">' + $keys + '</th>';
}
else
{
$newTable += '<th class="tableDataShow">' + $keys + '</th>'
}
});
$rowFlag=1;
}
});
$newTable +='</tr></thead><tbody>';
//Create the body for the Employer Table
$.each($responseData, function($key, $value)
{
$newTable += '<tr>'
$responseDataValue=$responseData[$key];
$.each($responseDataValue, function($keys, $values)
{
if ($searchStr.test($keys))
{
$newTable += '<td class="tableDataHide">' + $values + '</td>';
}
else
{
if($values==null)
{
$values="";
}
$newTable += '<td class="tableDataShow">' + $values + '</td>'
}
});
$newTable +='</tr>';
});
$newTable +='</tbody></table>';
$($tableContainerDiv).html($newTable);
$("#tempEmployerTbl").dataTable();
$('#tblSearchBox').focus();
}
}
});
I don't see where you even call .focus in your example, but the solution is simply to call it after the $($tableContainerDiv).html($newTable); -- i.e. after it's appended by the ajax callback.