Getting variable into JS via PHP assigned id - javascript

I have the following Javascript to generate a silent call to another sheet to update a database value without refreshing the page
function UpdateDB(table,column,type){
var value = $("#Assigned").val();
$.post("UpdateValuation.php?Table=" + table + "&Value=" + value + "&Column=" + column + "&Type=" + type, {}).done();
};
This works perfectly but only for the "Assigned" table row since it is statically assigned.
I use the following php to generate the table entry with button
print "<tr><td>" . $stuff['Status'] . "</td><td ><input type=\"text\" id=\"" . $stuff['Status'] . "\" name=\"" . $stuff['Status'] . "\" value=". $stuff['Value'] ." size = \"4\" style = \"text-align: center\"/><button onclick=\"UpdateDB('NOCstatus','Status','". $stuff['Status'] ."');\">Update</button></td></tr>";
Which after variables are assigned looks like this for my "Pending" row
<input id="Pending" type="text" style="text-align: center" size="4" value="120" name="Pending"> </input>
<button onclick="UpdateDB('NOCstatus','Status','Pending');">
Update
</button>
My problem is that passing "this.value" or trying to use a variable in the javascript portion I always come up with a blank value, the only time I can get a value to be correct is by statically assigning the "#Assigned" or "#Pending" in the value field. I have hundreds of entries so I don't want to write the function over for each of these. I know there is probably something extremely simple I am missing but I cannot get the pieces to fit.
I need to pass the typed in value in the input field to the function to update the database. Please help.

function UpdateDB(table,column,type){
var value = $('#'+type).val();
$.post("UpdateValuation.php?Table=" + table + "&Value=" + value + "&Column=" + column + "&Type=" + type, {}).done();
};
?

Related

Why do I get this php object cut off in javascript?

I am adding this object as data attribute to an element I create in Javascript :
var get_encode_obj = document.getElementById('centered_id' + location_id).getAttribute('data-whole_object');
var new_card_header = '<p data-whole_object=' + get_encode_obj + ' id="centered_id' + location_id + '" class="location_id_field">' + location_id + '</p><span onclick="edit_button_request(' + location_id + ')"></span>';
And the HTML (when the page is loaded initially):
<p data-whole_object='<?php echo json_encode($cards) ?>' id="centered_id<?php echo $cards['id']; ?>" class="location_id_field"><?php echo $cards['id']; ?></p>
getting the attribute in Javascript is done correctly if the HTML element is created initially in HTML DOM but after I create a new one using JS it gives me this:
"{"id":31,"name":"This"
as you can see that cut off somehow, and it is cut off right before first space after "This".
P.S: when I create the element in JS I am passing the entire object, it is not cut off.
What's going on here, any idea?

I am getting duplicate data on table while selecting values from multiple select box

I am using html select2 jQuery select box..on selecting any value my table gets relevant information about the value i selected
If there are values like one , two ,three on select box...
When i select one , i gets the information about option one in html table below
When i select two also.. now i am getting values from one plus one again and two.which is quite obvious ..
I am appending to the table using jQuery each function..
I know also clearing the table first will solve my problem but the thing is in table i have a check box control as well which i select.... If i clear the table i loose the checked check box
New values gets appended to the table after clearing the table first ..
Now the problem is i want no dublicate values for like one. And when i select two . I will get
Results of 1 and 1 and 2 appended...
Second i want the checkbox to retain the checked state which i made previous..
Hope i made my question understandable... Please help me
I am stuck...
Thanks in advance ..
Have a good day...
You just need to check if a row already exists by:-
Add dynamic id to each row like id='row_"+obj.Item_Id+"' i have added.
Check if the row exists by checking the length $("#tblItemsBody tr#row_"+obj.Item_Id).length ==0
Code:-
$.ajax({
...options,
success: function(data) {
$.each(data, function (i, obj)
{
if($("#tblItemsBody tr#row_"+obj.Item_Id).length ==0 ){
$('#tblItemsBody').append("<tr id='row_"+obj.Item_Id+"'> <td> <input type='checkbox' class='chk' id=" + obj.Item_Id + "> "+
<label for=" + obj.Item_Id + " class='p-0'></label> </td> <td> " + obj.SalesOrderId + " </td> <td> " + obj.Item_Code + "</td> <td> "
+ obj.AEGG_Description + " </td> <td> " + obj.Manufacturer + "</td> <td>" + obj.OEM_Reference + " </td> </tr>"))
}
});
})

How to pass a value from a Javascript generated button to a controller?

My code generates a table with a button at the end of each row. When the user clicks a button how can I pass a property u.userEmail to the controller via the button? Will the value being sent to the controller be a string?
My (non-working) attempt:
<script>
$(document.body).append("waiting on async table to load<br>");
$(document).ready(function () {
$.getJSON("/Account/LoadClaimsTable", function (crewResponse) {
//returns a List<UserClaims>
$(document.body).append("<table>")
crewResponse.forEach(function (u) {
var s = "";
s+="<tr><td>" + u.userEmail + "</td>";
u.userClaims.forEach(function (k) {
console.log("added claim"+k.value);
s += ("<td>" + k.type + "</td><td>" + k.value + "</td><td>" +
"<input type=\"hidden\" name=\"userEmail\" value=\"`${u.userEmail}`\" />"+
"<input type=\"button\" value=\"Create\" onclick=\"location.href='#Url.Action("EditClaims", "Account")'" />
+"</td>");
});
s += "</tr>";
$(document.body).append(s);
s = "";
});
$(document.body).append("</table>")
});
});
</script>
AccountController.cs contains:
public ActionResult EditClaims(string userEmail)
{
return View("StringView", userEmail);
}
You have to pass it on the url of the action. Not sure if you want to pass u.userEmail, but it could looks like this:
crewResponse.forEach(function (u) {
var s = "<tr><td>" + u.userEmail + "</td>";
u.userClaims.forEach(function (k) {
console.log("added claim"+k.value);
s += ("<td>" + k.type + "</td><td>" + k.value + "</td><td>" +
"<input type=\"hidden\" name=\"userEmail\" value=\"`${u.userEmail}`\" />"+
"<input type=\"button\" value=\"Create\" onclick=\"location.href='#Url.Action("EditClaims", "Account")?userEmail=" + u.userEmail + "'\"/></td>");
});
s += "</tr>";
$(document.body).append(s);
});
There are multiple ways to do it. One is mentioned in the answer above by Felipe. Here is another alternate approach using unobtrusive js
Add the email as html5 data attributes to the button along with another attribute which we will use bind the click behavior.
u.userClaims.forEach(function (k) {
// Add quotes as needed if you want multiline ( i just removed those)
s += "<td>" + k.type + "</td><td>" + k.value + "</td><td>
<input type='button'
clickablebutton data-email='" + u.email + "' value='Create'/></td>";
});
Now, in your document ready, bind a click event handler to those elements (with our custom attribute) and read the data attribute and build the url you need.
$(document).on("click", "input[clickablebutton]", function (e){
var url = '#Url.Action("EditClaims", "Accounts")?useremail=' + $(this).data("email");
window.location.href = url;
});
Some other suggestions
Use the appropriate element. Button is better than input (Consider accessibility)
If it is for navigation, Use an anchor tag instead of a button.
Inline javascript is not great. Let the browser parses your markup without any interruptions and you can add the behavior scripts later (that is the whole point of uobutrisive js approach)
The approach you appear to be taking would be Ajax, response, render a template. With that being said, you may want to rethink your approach.
Step 1.
Build a template
<template id="...">
<button type="button" value="[action]" onclick="[url]">[text]</button>
</template>
Step 2.
Create your request.
axios.get('...').then((response) => {
// Retrieve template.
// Replace bracket with response object model data.
html += template.replace('[action]', response.action);
});
Step 3.
Have the JavaScript render your template.
The above can create a clear concise codebase that is easier to maintain and scale as the scope changes, rather than an individual request performing a change with embedded markup. This approach has worked quite well for me, also I feel it'll make you troubleshooting and definition easier, as the controller is handing an object back to your JavaScript instead of a markup / view data. Which will be a better finite control for the frontend and clear modifications in future.

<pattern> & required doesn't work on dynamically created form

I'm trying to implement client-side input validation for a datatables-editor that I'm rewriting. The form is created dynamically and then added to a bootstrap-modal.
I have encountered a problem where adding <pattern> and/or required doesn't result in any added functionality at all. The form just accepts the input and submits, and I'm quite confused as to why that is.
EDIT:
I have added the relevant code to a plunkr
I have now added the full project. Specifically the issue is connected to the _openEditModal function and _openAddModal function, where i generate the forms dynamically and add the pattern='patternVariable'.
The pattern for this example (however it doesn't work no matter what pattern I use):
^[a-zA-Z0-9\.]+$
Creating the form:
var data = "";
data += "<form name='altEditor-form' role='form'>";
for(var j = 0; j < columnDefs.length; j++){
data += "<div class='form-group'><div class='col-sm-3 col-md-3 col-lg-3 text-right' style='padding-top:7px;'><label for='" + columnDefs[j].title + "'>" + columnDefs[j].title + ":</label></div><div class='col-sm-9 col-md-9 col-lg-9'>";
if(columnTypes[j].type.includes("text")){
data += "<input type='" + columnTypes[j].type + "' id='" + columnDefs[j].title + "' pattern='" + columnPattern[j].pattern + "' title='" + patternErrMsg[j].msg + "' required name='" + columnDefs[j].title + "' placeholder='" + columnDefs[j].title + "' style='overflow:hidden' class='form-control form-control-sm' value='" + adata.data()[0][newaData[j].name] + "'>";
}
if(...){...}
data +="</div><div style='clear:both;'></div></div>";
}
data += "</form>";
As you can see I add the tags like so:
pattern='" + columnPattern[j].pattern + "' title='" + patternErrMsg[j].msg + "' required ...
The modal:
$('#altEditor-modal').on('show.bs.modal', function() {
$('#altEditor-modal').find('.modal-title').html('Edit Record');
$('#altEditor-modal').find('.modal-body').html(data);
$('#altEditor-modal').find('.modal-footer').html("<button type='button' data-content='remove' class='btn btn-default' data-dismiss='modal'>Close</button>\
<input type='submit' data-content='remove' class='btn btn-primary' id='editRowBtn'>Save Changes</input>");
I made sure that the button has type='submit' as I've read that this is what triggers the pattern-check.
editRowBtn code:
$(document).on('click', '#editRowBtn', function(e)
{
e.preventDefault();
e.stopPropagation();
that._editRowData();
});
To make sure that my code is actually adding the attributes to the input i checked the console:
Any help or advice is greatly appreciated as I'm kinda stuck here.
It's a little hard to read your examples (a plunkr would be nice :) ), but from what I can see, you've put your submit button outside your form.
That won't work, since the button won't know what it's submitting.
Try putting the submit button inside the form.
Alternatively, try using the form attribute on the submit button, which should reference the form ID. I've never used this myself, but according to MDN, it's part of the HTML5 spec.
Form attribute description from MDN:
The form element that the input element is associated with (its form owner). The value of the attribute must be an id of a element in the same document. If this attribute is not specified, this element must be a descendant of a element. This attribute enables you to place elements anywhere within a document, not just as descendants of their form elements. An input can only be associated with one form.

textarea value = undefined on page with dynamic forms

I do not understand why I cannot access field values on forms generated dynamically via AJAX / MySQL.
The form template looks like this:
<form class="dishform" id='" + d.dish_id + "FF' action="#" method="post">
<fieldset>
<label for="dish_name">Name</label>
<textarea onblur="changedField(this);" id='" + d.dish_id + "n' name="dish_name" class="textarea-comment dish_name valid" maxlength="80">
default text from MySQL
</textarea>
<label for="dish_decription">Description</label>
<textarea onblur="changedField(this);" id='" + d.dish_id + "d' name="dish_description" class="textarea-comment dish_description valid" maxlength="240">more default text from MySQL here</textarea>
<img src="/wp-content/uploads/menu-icons/save-dish.png" alt="Save current dish changes" class="action-menu-buttons save-curr-dish" onclick="saveDish(\'' + d.dish_id + '\')">
</fieldset>
</form>
The d.dish_id value is the unique table key and it looks something like "DSH0000000001".
When I hit saveDish button I call alerts to show contents of name field, and I get UNDEFINED for the value, but the right figure for defaultValue:
function saveDish(thisId) {
var NameId = thisId + 'n' <--- all ids for "name" are created as "d.dish_id + n"
alert("NameID= " + NameId); <--- this shows "DSH0000000001n" so correct
alert("DINAM= " + document.getElementById(NameId).defaultValue); <--- this shows the defaultValue correctly to what is in the textarea from load
alert("VAL= " + document.getElementById(NameId).Value); <--- this one shows UNDEFINED
alert("HARD CODED ID VAL= " + document.getElementById('DSH0000000001n').Value); <--- this one shows UNDEFINED
};
Even if I hard code an ID to one of the ones I can see in inspect (that is the textarea exists with the right id), I still get UNDEFINED.
Any help is appreciated/
in saveDish, .Value needs to be lowercased .value

Categories

Resources