Get row id value VIA Ajax - get

Having line :
<tr id = "internal_route_id" name ="internal_route_id" value="'.`$data[1]['id']`.'">
I want to get the value that returns $data[1]['id'] and post it VIA AJAX.
I try like this:
data: $("#first_step").serialize()
+ '&internal_route_id=' + $("#internal_route_id").val()
Note that first_step is the table name.
Thank you!

Use following approach to get the value of tr and post it
<tr id ="internal_route_id" name="internal_route_id" value="'.`$data[1]['id']`.'">
$(function(){
var datavalue=$("#first_step tr").attr('value');
//posting ajax use following
$.ajax({
url:'',
data:{id: datavalue},
success:function(data)
{
//success code goes here...
}
});
});

Related

POST FORM in node and receive data response back to same webpage

I have a webpage that takes form details, POSTS the data and should then show the results. I'm using express for my routing.
This all works fine by resending the data with the HTML template after the POST but I think there must be a better way by hiding the "results" HTML section then just showing it once the data is known from the form. I've shown a cutdown version of my pages below.
On first load, the page says "your result is undefined", which I would expect but is ugly.
I could remove the "result" section and create a 2nd HTML page to resend from the POST route with it in which would work but I think there must be a better way.
I want to hide the result section on 1st page load then make it appear on the button submit with the result data. I can get the section hide/unhide but I can't get the data results back to display them. On button submit the form results just appear in the weburl www.mywebsite.com/?data almost like a GET request
I have tried using FormData and npm 'form-data' in a POST but can't get it working following these examples https://javascript.info/formdata and https://www.npmjs.com/package/form-data.
My structure in Node is
Router.js file
return res.send(htmlFormTemplate({}));
});
router.post('/css',
[],
async (req, res) => {
let {data} = req.body;
///
result= do some calculation on {data}
///
return res.send(htmlFormTemplate({result}));
});
The htmlFormTemplate is a js file
module.exports = ({result}) => {
return `
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form class="box" method ="POST">
<inputname="data" />
<button>Submit</button>
</form>
<script>
///tried form processing here
</script>
<section id="Results">
<ul><li>Your result is ${result}</li></ul>
</section>
</body>
</html>
`;
};
I'm self-taught and new so hope this makes sense and thanks for any help/ideas
You can check if the result variable is null before it gets to the section div:
${ result === null ? '' :
`<section id="Results">
<ul><li>Your result is ${result}</li></ul>
</section>`}
Like this, it wont show the result div if result if null.
There is a very simple to solve this problem,
just use some templating engine for ex EJS, its very easy to use and will help you better,
and your result is undefined because your using a promise and it might have happened that the response might have not come and you loaded the page. Just use await
return await res.send(htmlFormTemplate({result}));

Grails 3.3.9: Call controller action when checkbox is checked

I am fairly new to Grails and frameworks in general, so this is most likely a very basic problem. The only promising looking solutions I was able to find were working with the Tag, which is apparently deprecated in Grails 3. Similar questions do exist, but all from the time when was still a thing.
I am trying to program a way of displaying products that are grouped in subcategories which are then grouped in categories. When my page loads the subcategories and categories are requested from my database and selection options (Select-tag and checkboxes) are rendered in the view.
When one of the checkboxes representing the subcategories is checked i need to run a database query to get the product information and update an HTML-element by rendering a template for every row I get back. I have a controller action that does all that. My only problem is that I need a way to call the controller action whenever one of the checkboxes is checked.
I could maybe work around it by using actionSubmit and a hidden submit button that is clicked by javascript whenever a checkbox is checked, but that doesn’t seem like a proper solution.
I am probably missing some very basic functionality here but I did already thoroughly search and haven’t come across a proper solution by now, probably because I didn't use the right search terms. I would be so happy, if anyone could help me with this. Thanks a lot already!
The following example uses a javascript function activated in response to the checkbox being checked/unchecked, the value of which is passed to an action from which you can do whatever with the value of the checkbox, run your query etc. At present the action renders a template to update the view with the database results.
index.gsp
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main" />
<script type="text/javascript">
$(document).ready(function(){
$( '#cb' ).click( function() {
var checked = $(this).is(":checked");
$.ajax( {
url: "/yourController/yourAction?checked=" + checked,
type: "get",
success: function ( data ) {
$( '#resultDiv' ).html( data )
},
error: function(jqXHR, textStatus, errorThrown) {
console.log( 'Error rendering template ' + errorThrown )
}
} );
})
});
</script>
</head>
<body>
<div id="resultDiv"></div>
<g:form>
<g:checkBox name="cb" />
</g:form>
</body>
YourController
class YourController {
def yourAction() {
// you may want to do something with the value of params.checked here?
def dbResults = YourDomain.getStuff()
render ( template: 'theTemp', model: [dbResults: dbResults] )
}
}
_theTemp.gsp
<table>
<caption>Table of stuff</caption>
<g:each in="${dbResults}" var="aThing">
<tr>
<td>${aThing}</td>
</tr>
</g:each>
</table>

Post does not include all values

I am playing with node.js and jade and currently have this simple template:
extends layout
block content
h1 #{title}
br
form(action="/updateingredient", method="post")
table.table.table-striped.table-bordered
tr
td Name
td Category
td Available
if (typeof ingredients === "undefined")
tr
td
else
each ingredient in ingredients
tr
td #{ingredient.name}
td #{ingredient.category}
td
input(type="checkbox", name="#{ingredient.id}",
value="#{ingredient.available}", checked=ingredient.available)
button.btn(type="submit") Update Ingredients
When submitting this I get hit in upgradeIngredients as expected:
updateIngredient: function (req, res) {
console.log(req.body);
}
My problem lies in. That the Post only includes the checkboxes that are checked, also the value of checked boxes always seem to be false. I presume that is because that was the value before the form Post.
What I preferably would like is to get all checkbox values in the form, checked or not. Is this possible?
The current output from the updateIngredient method gives me the following when a checkbox is checked (currently just testing with one item):
{ 'b56a5f79-b074-4815-e7e0-4b746b2f65d8': 'false' }
and when unchecked:
{}
Edit
Looking at the constructed HTML I see this for an item:
<tr>
<td>Ost</td>
<td>Mælkeprodukt</td>
<td>
<input
type="checkbox"
name="b56a5f79-b074-4815-e7e0-4b746b2f65d8"
value="false"
checked="false">
</td>
</tr>
Verify that the checkbox HTML is correctly constructed
look in console for errors and warnings
ensure that the boxes all have either "true" or "false" for the checked value.
This example contains working syntax:
Node Express Jade - Checkbox boolean value
After searching some more here on SO, I found this answer: Post the checkboxes that are unchecked
It seems like checkboxes, which are not checked are not part of a form when posting HTML. This is exactly what I am seeing.
I did change my checked code to the following before going down another path.
checked=ingredient.available?"checked":undefined
This did not change anything, and did not give me any data in my form post when unchecked.
So I used the JavaScript approach, adding a submit event handler to my form. I added a new checkbox.js file in my javascripts folder, this code is taken from this answer:
// Add an event listener on #form's submit action...
$("#updateform").submit(
function() {
// For each unchecked checkbox on the form...
$(this).find($("input:checkbox:not(:checked)")).each(
// Create a hidden field with the same name as the checkbox and a value of 0
// You could just as easily use "off", "false", or whatever you want to get
// when the checkbox is empty.
function() {
console.log("hello");
var input = $('<input />');
input.attr('type', 'hidden');
input.attr('name', $(this).attr("name")); // Same name as the checkbox
// append it to the form the checkbox is in just as it's being submitted
var form = $(this)[0].form;
$(form).append(input);
} // end function inside each()
); // end each() argument list
return true; // Don't abort the form submit
} // end function inside submit()
); // end submit() argument list
Then I added the script to the end of my layout.jade file:
script(src='/javascripts/checkbox.js')
And I modified my form to include an ID:
form#updateform(action="/updateingredient", method="post")
And removed the value from the checkbox:
input(type="checkbox", name="#{ingredient.id}",
checked=ingredient.available?"checked":undefined)
Now I get the following when value is unchecked:
{ 'b2a4b035-8371-e620-4626-5eb8959a36b0': '' }
And when checked:
{ 'b2a4b035-8371-e620-4626-5eb8959a36b0': 'on' }
Now in my method I can find out whether it was checked or not with:
var available = req.body[ingredient] === "on" ? true : false;
Where ingredient is the key.

How to get textbox value in Action in asp.net MVC 5

I want to send the value of textbox to the Action Method for searching the technology for that i want to get the value of textbox in Action.
I have the following code :-
#Html.TextBox("technologyNameBox", "", new { id = "technologyName", #class = "form-control", #placeholder = "Search For Technology" })
<span class="input-group-btn" style="text-align:left">
<a class="btn btn-default" id="searchTechnology"
href="#Url.Action("SearchTechnology", "Technology",
new {technologyName="technologyName",projectId=ProjectId })">
<span class="glyphicon glyphicon-search "></span>
</a>
</span>
Question :- How to get the value of textbox "technologyNameBox" in Action ?
Please help me out. Thanks in Advance!
You'd have to append the value to the URL via JavaScript before directing the user. Using jQuery (since that generally comes packaged with ASP.NET), it might look something like this (with a good bit of manual conditional checks for blank values or query string parameters):
$('#searchTechnology').click(function (e) {
e.preventDefault();
var url = '#Url.Action("SearchTechnology", "Technology", new { projectId=ProjectId })';
var technologyName = $('#technologyName').val();
if (technologyName.length < 1) {
// no value was entered, don't modify the url
window.location.href = url;
} else {
// a value was entered, add it to the url
if (url.indexOf('?') >= 0) {
// this is not the first query string parameter
window.location.href = url + '&technologyName=' + technologyName;
} else {
// this is the first query string parameter
window.location.href = url + '?technologyName=' + technologyName;
}
}
return false;
});
The idea is that when the user clicks that link, you would fetch the value entered in the input and append it to the URL as a query string parameter. Then redirect the user to the new modified URL.

Meteor Facebook Profile Picture not Displaying

On first sign I have the following code:
Accounts.onCreateUser(function(options,user){
if (typeof(user.services.facebook) != "undefined") {
user.services.facebook.picture = "http://graph.facebook.com/" + user.services.facebook.id + "/picture/?type=large";
}
return user;
});
Which results in the following URL string
http://graph.facebook.com/[myfacebookid]/picture/?type=large
Yet when it renders that url and returns
<img scr="http://graph.facebook.com/[myfacebookid]/picture/?type=large" alt="My Name">
All I see is a broken image. How can I pull this in so that it renders the facebook profile picture?
I use a helper function based off of the Facebook ID of the user to grab the image on the server. I notice my url has /picture? and your has /picture/? Hope this helps.
userPicHelper: function() {
if (this.profile) {
var id = this.profile.facebookId;
var img = 'http://graph.facebook.com/' + id + '/picture?type=square&height=160&width=160';
return img;
}
},
I don't know how I missed this before, but is this the src attribute on the image tag is actually written as scr:
<img scr=
Should be...
<img src=
You have http instead of https.
So:
"https://graph.facebook.com/" + id + "/picture/?type=large";
This was my problem.

Resources