Fetch value of Dynamic textbox in javascript - javascript

I am dynamically creating a textbox at runtime using javascript and passing its value to my servlet page using a href(which is also created at run time along with the textbox) but somehow the value is being passed as "Null". I am not understanding it why..Can anyone help me on this ??
Here is my javascript code :
//here I am creating textbox
var td1 = document.createElement("TD");
var strHtml1 = "<INPUT TYPE=\"text\" NAME=\"in_name\" id =\"in_nm\" SIZE=\"18\" STYLE=\"height:24;border: 1 solid;margin:0;\">";
td1.innerHTML = strHtml1.replace(/!count!/g, count);
//Here I am fetching its value
var nm=document.getElementById("in_nm");//this value is being passed null
//Here I am passing it through a href tag
var strHtml3 = "<a id=\"link\" href=\"UserHandler?action=insert&&name="+nm+"\">Add Row</a>";
td3.innerHTML = strHtml3.replace(/!count!/g, count);
var dt=document.getElementById('in_dt');

You never put your HTML string into the document, so you can't fetch it from the document.

The DOM you have created never been placed in the document so you can't catch it.
In addition, if you immidietly catch the element it will be empty all the time.
You can append the input field to the body as hidden and then to fetch it.
strHtml1.style.display = 'hidden';
document.body.appendChild(strHtml1);
// At this point the dom is in the HTML and it is not visible and now you can use it.
Add it before your fetching the value.

For those who are facing similar problem as mine, I am posting the solution for their reference
The problem was solved by fetching the value onchange and passing request through ajax as :
$(".edit_trr").click(function() //edit_trr is my class of the dynamic row added
{
}).change(function()
{
var nam=$("#in_name").val(); //in_name is my id of the textfield
var datastr='name='+nam;
if(nam.length >0) //checks if there is value in textfield
{
$.ajax({
type: "POST",
url: "add.jsp", //link of my jsp page where data is added in database
data: datastr,
cache: false,
success: function(html)
{
alert('Inserted');
}
});
}
else
{
alert('Enter Something');
}
});
On JSP page request send can simply be fetched as :
request.getParameter("name");

Related

On click function that sends data with AJAX to a php file for it to be saved in the database only works once

I am trying to create a remove button in an "edit form" code I've been working in. The button 1) gets the ID of the its div parent and then 2) gets the value of the inputs inside of named parent in order to 3) send them with an AJAX call to a PHP file that works on 4) inserting that information inside a table in the database.
At first, the code works as it should. It inserts the information into the database and retrieves it while modifying an existing div. But it only works once. When other button with the same class (and therefore the same function) is clicked, the success:function works just fine and shows the corresponding data, but does not save the data into the database as the previous button did. If I reload the page, again, any button works, but the data it's being saved just once.
I've tried using cache: false, but when I place it into my AJAX call, the buttons stop working completely.
$(document).on('click','.removeQe',function(e) {
var reId = $(this).attr('id');
var box = $('#'+reId+'').parent().parent().attr('id');
var input1 = $('#'+box+'').find('.del-exam-id').val();
var input2 = $('#'+box+'').find('.del-id').val();
var input3 = $('#'+box+'').find('.del-table').val();
var input4 = $('#'+box+'').find('.del-id-form').val();
var values = {
'examID': input1,
'questionID': input2,
'Info': input3,
'idForm': input4
};
$.ajax({
url: "edit-delete.inc.php",
type: "POST",
data: values,
success: function(data)
{
$('.show-data').html(data);
$('#'+box+'').remove();
$('.countTQ').each(function(index) { $(this).find('h3').html('Question #'+(index+1)+''); });
$('.audio-box').each(function(index) { $(this).find('h3').html('Audio #'+(index+1)+''); });
}
});
});

display ajax result on new page

I would like to display the results of an ajax request on a new page rather than the page the ajax call was made from. Essentially I have a membership directory page. When the user clicks on the member ID cell on that page, an ajax call sends the ID to the server and completes an HTML table to display that member profile. If I add a <div> element below the membership directory page, I can make the profile information table display below the membership directory table. But I want the profile table to display on different page.
JavaScript:
$jq.ajax({
url : ajax_mmmp.ajax_url,
type : 'post',
data : {
action: 'mmmp_profile_member_id_callback',
mem_id : member_id
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
// Return response to client side
alert("Submit Success");
$jq('#display_profile').html( data );
return false;
},
error: function(errorThrown){
console.log(errorThrown);
}
}); // End of AJAX function
But when I create a new page with the same <div> element and try to open that page prior to the ajax call, the result does not display.
var mem_profile = "http://localhost:81/wordpress/view-member-profile"
window.open (mem_profile,'_self',false)
$jq.ajax({
url : ajax_mmmp.ajax_url,
type : 'post',
data : {
action: 'mmmp_profile_member_id_callback',
mem_id : member_id
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
// Return response to client side
alert("Submit Success");
$jq('#display_profile').html( data );
return false;
},
error: function(errorThrown){
console.log(errorThrown);
}
}); // End of AJAX function
Putting aside the question of whether it is a good idea to take that approach, the answer to your question is yes. You can open a new window and write the resulting HTML to it:
// open a new window with no url and a title. check the docs for other args to open()
let win = window.open('','My New Window');
// write some HTML to that window
win.document.write('<table><tr><th>test</th></tr></table>');
After some further research, I'm almost there. I do not presently have a "form" to submit. The user simply clicks on a table cell which contains a member ID number. I want to 'submit' that value as input on another page which displays the membership profile. I have been successful in temporarily adding a HTML form that works as desired if I type the member ID in an input field. So I decided what was needed was to create a hidden form in JS that used the ID value that was clicked on. It appears that I can not insert revised code into a comment, so I opted to 'Answer' my original question with updated code.
Working HTML Form included on Membership Directory Page:
$site_url = site_url();
$location = $site_url . "/view-member-profile";
?>
<form action="<?php echo $location;?>" method="post">
<input type="text" class="input_member_id" id="input_member_id" name="Member_ID">
<input type="submit" id="submit_member_id" name="submit_member_id" value="Submit">
</form>
My attempt to create a similar hidden form in JS:
var $jq = jQuery.noConflict();
$jq(document).ready(function(){
// Add listener for Member ID click in member directory
$jq("#mem_dir").delegate(".member_id", "click", function() {
var mem_id = $jq(this).text();
var mem_id = mem_id.trim();
alert ("ID is: " + mem_id);
var site_url = document.location.origin + '/wordpress';
var form_location = site_url + '/view-member-profile';
alert ("Submit to location is: " + form_location);
var form = $jq('<form method="post" class="js:hidden">').attr('action', form_location);
//var input = $jq('<input type="hidden"'>).attr('value', mem_id );
//form.append(input);
//$jq('body').append(form);
form.submit();
}); // End of Click Member ID Listener
}); // End of Main Document Ready Function
The problem I am having with the JS file is with inserting the mem_id value into the input form. The JS file correctly opens the new View Member Profile page. (Note the 3 // lines just prior to the form.submit). When uncommented, the Profile page opens, but table values are empty (i.e. mem_id value was not passed to the page).
Thanks for any advice. If I was supposed to list this as a new question, please let me know.

Laravel 5 attach with Ajax?

I have this laravel code in my controller detach function.
$input = Input::all();
$product= Products::findOrFail($input['product_id']);
$product->tags()->detach($input['tag_id']);
$product= Products::where('customer_id', Auth::user()->customers_id)->get();
return view('products.tagsdelete', [
'products' => $product,
]);
This works fine, it deletes the tag realation from my pivot table. The only thing that bugs me it that I don't want to reload the page everytime I press the delete button on my view.
( Of course I could make a selection of all tags the user want to delete, but I want to to this live with Ajax )
My problem is, I couldn't find anything that helps me with detachment from laravel + Ajax. I'm quite okay with Javascript and Jquery but Ajax is still a new thing for me..
So can anybody help me there? I'm really stuck.
Thanks for taking your time :)
#Wiriya Rungruang
current controller code:
public function detach()
{
$input = Input::all();
$product= Products::findOrFail($input['product_id']);
$product->tags()->detach($input['tag_id']);
$product= Products::where('customer_id', Auth::user()->customers_id)->get();
}
my button:
<button type="submit" class="delete-tag-btn" data-product_id="{{ $product->id }}" data-tag_id="{{ $tag->id }}"><i class="glyphicon glyphicon-trash"></i></button>
at the bottom of the code the JS:
<script>
$(".delete-tag-btn").on('click', function(){
var url = "{{ route('detach') }}"; // Url to deleteTag function
url += "product_id=" + $(this).data('product_id');
url += "&tag_id=" + $(this).data('tag_id');
// Now url should look like this 'http://localhost/deletetag?product_id=2&tag_id=5
// Send get request with url to your server
$.get(url, function(response){
alert("success");
});
});
</script>
First : You should create function detach tag from product in your controller and return status success or failure(or nothing)
In your controller
function detachTag(){
$input = Input::all();
$product= Products::findOrFail($input['product_id']);
$product->tags()->detach($input['tag_id']);
$product= Products::where('customer_id', Auth::user()->customers_id)->get();
return "Some state for checking it a success or not";
}
Second : Create javascript function for checking when you click on delete button send request with parameter to function that we created in the first step and rerender or remove that tag from your HTML page
**Parameter is mean product_id and tag_id that your want to detach it
In your js
$(".delete-tag-btn").on('click', function(){
var url = "localhost/deletetag?"; // Url to deleteTag function
url += "product_id=" + $(this).data('product_id');
url += "&tag_id=" + $(this).data('tag_id');
// Now url should look like this 'http://localhost/deletetag?product_id=2&tag_id=5
// Send get request with url to your server
$.get(url, function(response){
// Do what you want
});
});
So when you click on .delete-tag-btn It will send request for detach it
While you can right a simple ajax call, send data and return html and replace it with the old html
lets begin :)
first step is to write ajax, and send it when form is submit or any button is clicked (as per your code)
this one is sample ajax, just fill in your data in it.
var BASEURL = window.location.origin + "/your_domain_name/";
$.ajax({
url: BASEURL + "your_route",
type: "POST/GET", //any_one
data: {
// Your data comes here (object)
},
beforeSend: function () {
},
success: function (response) {
console.log(response); // your html in return
},
complete: function (response) {
}
});
now a call will be send with your data to controller respective to specified route you mentioned, processing will be normal.
It will return only html. You can do whatever you want with this html.
One important problem you might face if considering these instructions is, right now the view you are returning is probably of whole page (because the page is been refresh every time), but if you are thinking to replace it with new html, your will only have to return that part of the page may be a single row or something like that. So break your view in many sub views. Php #include(//path) (blade) might come handy. Thats how I use to work. :)

VBA Excel run javascript form event

I’ve already tried to get the element by id, however, the html does not include it. As shown below, this is the script for the drop down that I am trying to change automatically. It will change the name with
appIE.Document.getElementById("supervisor").Value = "Sup_name"
However, it doesn’t fire the event that generates a list of people.
The top of the form also includes <form id='filterform' action="javascript:void(0);">
The JavaScript containing the function I need to call is below.
<script type="text/javascript">
$(function() {
$('#supervisor').change(function() {
document.getElementById('results').innerHTML = '<img src="/img/busy.gif" />';
var str = $('#filterform').serializeArray();
$.ajax({
url: 'ajax.php?p=agentrosters&mode=1&field=supervisor',
type: 'POST',
data: str,
success: function(j) {
//alert(j);
document.getElementById('results').innerHTML = j;
document.getElementById('lastsearch').value = 'supervisor';
resetscript('supervisor');
},
failure: function() {
document.getElementById('results').innerHTML = 'There has been an error, please try again';
resetscript('null');
}
})
})
})
</script>
Any Ideas on how I can get this to work?
If the element is part of a form you may to submit the form, alternatively you can use the onchange event on the element itself. So you may want to change appIE.Document.getElementById("supervisor").Value = "Sup_name" to
With appIE.document.getElementById("supervisor")
.Value = "Sup_name"
.onchange
End with
And if it is part of a form change the ".onchange" to
".parentElement.Submit"
This worked for me.

How to use HTML data from ajax call

i have a load more button on some content that is pulled from a database via ajax.
The ajax call looks like so:
// JavaScript Document
// load more builds function
$(document).ready(function(){
var pageIndex = 1;
$('#loadmorebuilds-div').click(function() {
$.ajax({
url: 'includes/loadmorebuilds.php?type=' + type + '&pageIndex=' + pageIndex,
success: function(html) {
$("#buildcontainer").append(html).waterfall('reflow');
$("#loadmorebuilds-div").stop().fadeOut();
pageIndex++;
var rowCount = MAKE THIS THE VALUE THAT IS APPENDED;
$('.testcount').html(rowCount);
if (rowCount < 18) {
$('#loadmorebuilds-div').remove();
$('.countvar').detach();
} else {
$('.countvar').detach();
}
}
});
});
});
In the appended items, is a div that contains a value of the row count for the database query that has been carried out via the above ajax call.
Normally, i would put this value into a JSON return and simply do e.g.:
rowCount = response.rowCount
However i am not using a JSON datatype but HTML.
How can i get this value from the appended div in the data and use it to set a var?
Thanks!
Use either:
val = $("#thatDiv").text();
or
val = $("#thatDiv").attr("value");
The latter of which, is if you put the value in a pseudo attribute...

Categories

Resources