Passing multi parameter to Td inline JavaScript function - javascript

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.

Related

Why is my data not displaying when onClick function is added?

My code could display the data without the onclick function but when it's added the data does not display in my table. There are no errors being displayed as well.
This is the code to get the json data and display:
<script>
var url = "http://127.0.0.1:8080/Assignment2/video/backend/RestController.php?view=all";
$('#viewUser').on('click',function (e){
$.ajax({
method: "GET",
cache: false,
url: url,
success: function(data) {
var student = '';
// ITERATING THROUGH OBJECTS
$.each(data, function (key, value) {
//CONSTRUCTION OF ROWS HAVING
// DATA FROM JSON OBJECT
student += '<tr>';
student += '<td>' +
value.id + '</td>';
student += '<td>' +
value.username + '</td>';
student += '<td>' +
value.videoName + '</td>';
student += '</tr>';
});
//INSERTING ROWS INTO TABLE
$('#table').append(student);
},
error:function(exception){alert('Exeption:'+exception);}
})
e.preventDefault();
});
</script>
This is the code for the button (for onclick function):
<h2>View Stored User</h2>
<button type="button" id="viewUser">GO</button>
[The error i'm receiving from the console log of the browser tho it's not related][1]
[1]: https://i.stack.imgur.com/7TZ3a.png

Cannot print JSON array from ajax call using the array length

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 ">".

How to call Rails form helper with params in jQuery AJAX?(SUPER SIMPLE)

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.

All Dynamic Posts defaults to first Object

I am currently working on an app to retrieve feeds from a wordpress site and list individual posts in a jquery mobile list format. Below is the JS code:
$(document).ready(function () {
var url = 'http://howtodeployit.com/category/daily-devotion/feed/';
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&output=json_xml&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function (data) {
var postlist = data.responseData.feed.entries;
var html = '<ul data-role="listview" data-filter="true">';
for (var i = 0; i < 6; i++) {
var entry = postlist[i];
console.log(entry);
html += '<li>';
html += '<a href="#articlepost" onclick="showPost(' + entry.id + ')">';
html += '<div class="etitle">' + entry.title + '</div>';
html += '<div class="esnippet">' + entry.contentSnippet + '</div>';
html += '</a>';
html += '</li>';
}
html += '</ul>';
$("#devotionlist").append(html);
$("#devotionlist ul[data-role=listview]").listview();
}
});
});
function showPost(id) {
$('#articlecontent').html("Loading post...");
$.getJSON('http://howtodeployit.com/category/daily-devotion/?json=get_post&post_id=' + id + '&callback=?', function (data) {
var html = '';
html += '<h3>' + data.post.title + '</h3>';
html += data.post.content;
$('#articlecontent').html(html);
});
}
When I click on any of the 6 posts displayed, only the contents of the first Post gets displayed instead of the contents of the individual posts.
How did I workaround this?
Step1: From my WordPress Permalink Settings, I selected Custom Structure and added /%postname%/%post_id% This means my RSS XML output results for my 'Link' element will be in this format:
<myurl>/<postname>/<postID> (http://howtodeployit.com/xxx/111/)
Step2: To make it easier for me instead of writing a regex query I used a Split command like this:
var postlink = entry.link;
var id = postlink.split(/\//)[4];
(///)[4] would simply split the URL by the number of slashes and take only that 4th bit which is where my postID is.
I hope this comes in handy for others in my position

Difficulty calling JavaScript function on click after dynamically generating table

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();
});

Categories