Is it possible send an AJAX request when a form is submit, then show a list below the form? If use razor foreach my page will be reloaded. I would use a PartialView to solve that problem.
Can I use AJAX to submit and return the list? If the AJAX request is successful, I could create the code bellow.
for (int i = 0; i < data.lenght; i++) {
$('#MyElement').append('tr' +
'<td>' + data.Id + '</td>' +
'<td>' + data.Name + '</td>' +
+'</tr>');
}
I tried it, but without success. I would like to know if it is possible, or just PartialView.
First of all, change lenght to length. Check if data is properly fetched by using console.log(data) (check your browser console). if the data is printed in the console and you still can't loop and append the data to HTML DOM, then use this :
$.each(data,function(index, dataValue){
$('#myElement').append('<tr>'+'<td>' + dataValue.Id + '</td>' + '<td>' + dataValue.Name + '</td>' + '</tr>'
)
})
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 get the JSON output on the UI using the below function
$("#idvar").click(function(){
var d1 = document.getElementById("dText");
var d2 = document.getElementById("dJson");
var mytext = d1.textContent;
alert(mytext);
$.post(
url,
{doc: mytext},
function(data) {
console.log(Object.keys(data).length);
d2.textContent = data;
}
);
});
where d1 is the displaying the uploaded input document, d2 for the output generated from processing the document on a model. Currently, I am getting json format. I tried to implement the codes in these posts (Parsing JSON objects for HTML table, Convert json data to a html table), but I get [object, Object] in the text area. Is there a way to convert the json to table.
In the URL text area i get
[{"tag":"a1","relevance":0.5},
{"tag":"a2","relevance":0.3},
{"tag":"c3","relevance":0.2},{"tag":"d3,
...
Instead, I was hoping to get
enter image description here
You should traverse the data and print it in table format. First, make sure the element with id dJson is a <table> element. Then, you can change your success callback to something like:
function(data) {
console.log(Object.keys(data).length);
var html = '<tr><th>Tag</th><th>Relevance</th></tr>';
for(var i=0; i<data.length; i++){
html +=
'<tr>' +
'<td>' +
data[i].tag +
'</td>' +
'<td>' +
data[i].relevance +
'</td>' +
'</tr>'
;
}
d2.innerHTML = html;
}
Here you have a working example (without the $.post call): https://jsfiddle.net/cLbqmwa4/
I'm trying to run this ajax method for multi select drop down:-
success: function (data) {
var drop_down_option = '<select name="langOpt3[]" multiple id="langOpt3">';
var check = JSON.parse(data)
console.log(check);
for (var i in check) {
console.log(check[i].branchId + ',' + check[i].validbranches);
drop_down_option += '<option id="' + check[i].branchId + '">' + check[i].validbranches + '</option>';
}
drop_down_option += '</select>';
document.getElementById("checkID").innerHTML = drop_down_option;
},
async: false
When i use the static multi select drop down on the html it works without red box, image shown as below :-
And which is not working is shown in red box:-
These scripts i'm using :-
<link href="~/css/jquery.multiselect.css" rel="stylesheet" />
<script src="~/js/jquery.multiselect.js"></script>
<script src="/js/jquery.min.js"> </script>
The issue as i see is that in case of dynamic my scripts runs before page load and thus this dynamic ajax don't show drop down,but in case of static multi select drop down it works because this drop down is before the page loads and thus the script runs over it how do i run ajax before page call or before these scripts run.
Just call your .selectMultiple event function in your ajax success method after inserting your select tag in DOM
success: function (data) {
var drop_down_option = '<select name="langOpt3[]" multiple id="langOpt3">';
var check = JSON.parse(data)
console.log(check);
for (var i in check) {
console.log(check[i].branchId + ',' + check[i].validbranches);
drop_down_option += '<option id="' + check[i].branchId + '">' + check[i].validbranches + '</option>';
}
drop_down_option += '</select>';
document.getElementById("checkID").innerHTML = drop_down_option;
$('#langOpt3').selectMultiple(
//your code
);
}
I'm trying to get elements from my JSON API like in a example below.
The thing is it doesn't work properly. I'm getting only values from One Hub instead from all of them.
/api/hubsUser/:id - returs JSON with all my hubs and
/api/sensorsHub/:id - returns JSON with all my sensors which have hubID element.
var tableContent = '';
var wholeContent = '';
var hubList = [];
$.getJSON('/api/hubsUser/' + document.getElementById("txt").innerHTML, function (result) {
$.each(result.data, function () {
//alert(this.hubID);
hubList.push(this.hubID);
});
$.each(hubList, function (i, hub) {
// alert(hub);
$.getJSON('/api/sensorsHub/' + hub, function (data) {
$.each(data.data, function () {
//alert(this.sensorID);
tableContent += '<tr>';
tableContent += '<td>' + this.sensorID + '</td>';
tableContent += '<td>' + this.hubID + '</td>';
tableContent += '<td>' + this.desc + '</td>';
tableContent += '<td>' + this.state + '</td>';
tableContent += '</tr>';
});
wholeContent += tableContent;
});
});
$('#sensorList table tbody').html(wholeContent);
});
};
That's because after first ajax succeeds you make a lot of other ajax calls, async of course, and you don't wait for them to execute before you call $('#sensorList table tbody').html(wholeContent);. Strange you even get that one, probably because you are yet on localhost.
You should call $('#sensorList table tbody').html(wholeContent) after all your ajax calls return result. I think a route to follow is to use jQuery when option (see here) or 'promises'.
Another thing that you probably had in mind is to use var tableContent = '' in every secondary ajax instead of declaring it once in the beginning. Otherwise it will contain results of previous ajax calls and same content will be added to wholeContent multiple times.
Try adding .bind(this) to your $.each loops:
$.each(result.data, function () {
//alert(this.hubID);
hubList.push(this.hubID);
}.bind(this)); // <- force the loop to use the object context of your choice
I'm having difficulty making a clickable button in my dynamically generated table that would send data specific to the table cell that was clicked.
My table is generated and modified whenever the user types into the search box with this AJAX call:
$(document).ready(function(){
$("#data").keyup(function () {
$.ajax({
type: "POST",
dataType: "JSON",
data: "data=" + $("#data").val(),
url: "search1.php",
success: function(msg){
var output = "";
for(var i = 0; i < msg.length; i++) {
output += '<tr onmouseover=this.style.backgroundColor="#ffff66"; onmouseout=this.style.backgroundColor="#F0F0F0";>';
output += '<td>';
if (msg[i].website != ''){ output += '' + msg[i].name + '</td>';}
else output += msg[i].name + '</td>';
output += '<td class="description">' + msg[i].description + '</td>';
output += '<td><input type="button" onclick=' + submit() + ' value=' + msg[i].id + '></td></tr>'; // Here is where I'd like to put in a clickable button
}
$("#content").html(output);
$("#myTable").trigger("update");
}
});
});
});
If I make submit() simply alert("hello") it runs when the page is loaded for every instance of the onclick call to submit(). Could someone please explain to me how to make submit only get called when its button is clicked and not on page load. Thanks in advance.
You have to put the submit() call in a quoted string. Same goes for the msg[i].id. All values in HTML should be quoted.
output += '<td><input type="button" onclick="submit()" value="' + msg[i].id + '"></td></tr>';
You are trying to assign submit() to the button's onclick, but you are actually calling the function when you generate the string output. It needs to be in quotes inside the string, not concatenated in.
output += '<td><input type="button" onclick="submit()" value="' + msg[i].id + '"></td></tr>';
//----------------------------------------^^^^^^^^^^^^
A better strategy would be to leave out the onclick attribute entirely, and use jQuery's .on() to dynamically assign the method. It is often considered a better practice to bind events dynamically rather than hard-code them into HTML attributes.
// No onclick attribute in the string:
output += '<td><input type="button" value="' + msg[i].id + '"></td></tr>';
// And a call to .on() in the $(document).ready()
$('input[value="'+msg[i]+'"]').on('click', function() {
submit();
});