How to get the value of dynamically populated input ajax - php

I have a textarea that has been dynamically populated,
<textarea class="materialize-textarea validate addCommentTxt"
value="" data-length="250" required name="addCommentTxt"></textarea>
My problem is that whenever I try to get the value of the textarea in ajax, with this code:
$('.btnCommentSubmit').click(function(e){
e.preventDefault();
var comment_identifier = $(this).data("value");
var comment_by = $(this).data("id");
$('#formAddComment').attr('action', '<?php echo base_url() ?>Discussion/addComment/');
var url = $('#formAddComment').attr('action');
var addCommentTxt = $('.addCommentTxt').val(); //GET THE VALUE OF TEXT AREA
$.ajax({
type: 'post',
url: url,
data: {
addCommentTxt:addCommentTxt,
comment_identifier:comment_identifier,
comment_by:comment_by,
},
success: function(){
alert("scs");
showAllComments(comment_identifier);
},
error: function(){
console.log(data);
alert('Could not add data');
}
});
});
The value that I get is from the first populated textarea, not from the textarea that I sent my data.
For example:
Textarea 1 - I have sent a "first String" comment and it has been inserted successfully.
Textarea 2 - I have sent a "second String" comment, but the inserted data will be "first String" which is from the textarea 1 not in the textarea 2

You need to get the addCommentTxt relative to your btnCommentSubmit so use closest to get your parent form and then use find to get the textarea value
var addCommentTxt = $(this).closest('form').find('.addCommentTxt').val();

Related

pass variable value of the clicked button (not button in a form) to ajax url?

In idx.php head tag, I have a script like this :
<script type="text/javascript">
$(document).ready(function(){
var alamat="1.php";
//$('button[name="test"]').click(function(){
//var alamat= $(this).val();
//alert(alamat);
//});
$('.search-box input[type="text"]').on("keyup input", function(){
/* Get input value on change */
var inputVal = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(inputVal.length){
$.get("backend-search.php", {term: inputVal}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val('');
$.ajax({
type: "POST",
//url: "1.php",
url: alamat,
data: {name: $(this).text()},
success: function(msg){
$("#hasil").html(msg)
},
error: function(){
alert("failure");
}
});
$(this).parent(".result").empty();
});
});
</script>
And in the same idx.php, in the body tag, I have this :
<button name="test" class="btn" value="1.php">THIS</button>
<button name="test" class="btn" value="2.php">THAT</button>
In the 2nd line of the script, I hardcoded the variable alamat value as "1.php"
then in $ajax for the url I use that alamat variable value.
The code runs as expected.
Now I'm trying to have the alamat variable is dynamic based on which button is clicked.
So I commented (//) the 2nd line of the script, and uncommented the 3rd to the sixth line.
When I click the first button, I see the alert window show "1.php"
and when I click the second button, I see the alert window show "2.php".
So I thought the alamat variable has a value, just like as if I hardcoded it.
But it seems the $ajax url has no value as it's just stand still after I click one of the ".result p" list. So it seems the alamat variable value from the clicked button is not passing to $ajax url call.
So my question is :
How do I code it in order to have the $ajax url value can be either "1.php" or "2.php" based on the clicked button ?
or
how to have the alamat variable value (resulted from the 3rd to the sixth line) go on to $ajax url:alamat ?
You're redeclaring alamat inside your function, which makes a whole new (locally scoped) variable. Just say:
alamat = $(this).val();
This will set the (global) alamat variable that you've already declared outside the function. So your completed code would be:
var alamat="1.php";
$(document).ready(function(){
$('button[name="test"]').click(function(){
alamat = $(this).val();
});
// ...
}

Ajax Live Search with Multiple Inputs

I am writing an ajax live search feature into my software. There are multiple input that need to be ajax searchable on each form. Everything works great except I want the list of results to be displayed in a hovering "p" element right below the input I am currently searching in. Right now I have a "p" with class = "options" right below each input to display the results. When I type, the results are displayed in EVERY "p", that is, hovering under every input. Is there a way to reference just the child of the current input or do I need to use a separate function explicitly referencing the desired for each input? I've tried a lot of child selector options on the internet and none of them have worked. The code is below. Thank you for your advice.
$(document).ready(function() {
//sets the chosen value into the input
$( ".options").on( "click", function(event) {
var item = $(event.target).text();
$('#acctname').val(item);//place chosed result into the acctname input
$('.options').hide();//hide result options after click
});
//On pressing a key in input field, this function will be called.
$(".textinput").keyup(function() {
var id = $(this).attr("id");
var val = $(this).val();
if (val === '') { //Validating, if "name" is empty.
$('div > p').html('').show();
}else {//If input is not empty.
$.ajax({
type: "POST",
url: "../model/ajax/livesearch.php",
data: {id: id, val: val},
success: function(html) {//place the result into the p element and set the proper css
$('div > p').html(html).show().css({"position":"absolute","z-index":"+1","cursor":"pointer","color":"black","background-color":"white"});
}
});
}
});
});
Update: this is how my HTML forms are structured.
<form action= "../model/dataentry.php?formname=enter_deposit" method="POST" id="ajaxform" name="ajaxform">
<div class = "label"><p1>Revenue Account Name</p1></div><div class = "field"><input class = "textinput" type="input" name="acctname" id="acctname" value = "" autocomplete="off">
<p class = "options"></p></div>
<div class = "label"><p1>Revenue Account Number</p1></div><div class = "field"><input class = "textinput" type="input" name="acctno" id="acctno" value = "" autocomplete="off">
<p class = "options"></p></div>
<input class = "submit" name = "Submit" type = "button" id = "ajaxsubmit" value = "Submit" >
<input class = "submit" name = "Close" type = "button" id = "close" value = "Close" >
</div>
</form>
Is this what you are looking for?
https://jqueryui.com/autocomplete/
I found a solution to the issue in case anyone is curious. By assigning each div with class "option" an id equal to its parent's id plus "_opt" (i.e. "acctname" input would have a child div with id "acctname_opt"), I can edit div ids dynamically in my functions to place the result list where I want it. Here is my new javascript code. Works flawlessly. Thanks for your help, everyone.
$(document).ready(function() {
//sets the chosen value into the input
$( ".options").on( "click", function(event) {
var item = $(event.target).text();
var clickedid = $(this).attr('id');
var targetid = clickedid.split('_'); //remove the '_opt' suffice to get the target id
$('#' + targetid).val(item);//place chosed result into the acctname input
$('.options').hide();//hide result options after click
});
//On pressing a key in input field, this function will be called.
$(".textinput").keyup(function() {
var id = $(this).attr("id");
var optid = id + '_opt'; //set the target element id
var val = $(this).val();
if (val === '') { //Validating, if "name" is empty.
$('#' + optid).html('').show();
}else {//If input is not empty.
$.ajax({
type: "POST",
url: "../model/ajax/livesearch.php",
data: {id: id, val: val},
success: function(html) {//place the result into the p element and set the proper css
$('#' + optid).html(html).show().css({"position":"absolute","z-index":"+1","cursor":"pointer","color":"black","background-color":"white"});
}
});
}
});
});

WMD Editor echoing value of wmd-preview div and inquiries about storing that value into a database

I am currently trying to add the WMD editor to my site. I have everything working so far but now I am running into wall: How to store the typed information into my database? I have created a JS/Ajax function that will assign the value of textarea to $wmdVal but instead i actually value of the wmd-preview since it contains the html formatted code. How can I get the value of the div wmd-preview and assigned it php variable? or what is the best way to store it in a database? Here is my EXAMPLE
JS/AJAX echoing value in realtime
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "test1.php",
data: dataString,
success: function(result){
$('#wmd_result').html( $('#resultval', result).html());
}
});
return false;
}
$('#wmd-input').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 1000);
var wmdVal = $("#wmd-input").val();
dataString = 'wmdVal='+ wmdVal;
});
});
</script>
PHP
<?
if (isset($_POST['wmdVal'])){
$wmdVal = $_POST['wmdVal'];
echo ('<div id="wmd_result"><span id="resultval"><h2>PHP Echo result:</h2>'.$wmdVal.'</span></div>');
}
?>
HTML WMD Editor
<div id="wmd-editor" class="wmd-panel">
<div id="wmd-button-bar"></div>
<textarea id="wmd-input"><? $wmdVal ?></textarea>
</div>
<div id="wmd-preview" class="wmd-panel"></div>
<div id="wmd-output" class="wmd-panel"></div>
<div id="wmd_result"></div>
Place a hidden field in your form and on submit, get the value of wmd-preview and assign it into the hidden field and let the form submit. then access your hidden field in $_POST array as a normal input field and save it.
you can access the wmd-preview as
$("#myhidden").val($("#wmd-preview").html());
If I understand you correctly I think you only have to replace
var wmdVal = $("#wmd-input").val();
with
var wmdVal = $("#wmd-preview").html();
in your code above.

How to get text filed value in ajax?

I have a table with dynamic data from database, each row consist of a text filed and 2 link (accept or reject). then if user clicks on any of these link, the row will disappear and the rest of the rows are only visible in table.
I get ID of each row with ajax by clicking on each link, however I also need to get the text-field value.
how can I get it?
I need to have in ajax cause after getting value I need to insert in database with php+sql.
this is my ajax part for link:
$('a.accept').click(function(d) {
d.preventDefault();
var parent = $(this).parent();
$.ajax({
type: 'get',
url: 'Test.php',
data: 'ajax=1&accept=' + parent.attr('id').replace('record-',''),
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function() {
parent.slideUp(300,function() {
parent.remove();
});
}
});
});
});
how can I include text filed value in it?
please comment me which I'm really in need to solve it,
Thanks
You can add manually your text to the GET request.
(snippet)
data: 'ajax=1&accept=' + parent.attr('id').replace('record-','') + '&text=VALUE',
Substitute text with the name you want to be received in PHP. Substitute VALUE with the text entered on the page that you want to grab - and don't forget to encode the value.
You will need the name of id of the textfield first. Then you could do something like this:
var textboxvalue = $('name or id of textfield').val();
Then you will need to append this value to your data string:
data: 'ajax=1&textvalue='+textboxvalue+'accept=' + parent.attr('id').replace('record-',''),
Then you can use $_GET['textvalue']; to get the value of textbox.
Use following and you're good to go. Also you had extra '});' at the end line of JS fragment. I had it removed. But make sure you give id to text fields in following pattern : text-fld-RECORD_ID where RECORD_ID is the ID of the record.
$('a.accept').click(function(d) {
d.preventDefault();
var parent = $(this).parent();
var id = parent.attr('id').replace('record-','');
//make sure that text field has ID in pattern 'text-fld-RECORD_ID'
var text_fld = $('#text-fld-'+id).val();
$.ajax({
type: 'post', // I suggest using post; get will be harmful in such occasions
url: 'Test.php',
data: {ajax:1,accept:id,text:text_fld},
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function() {
parent.slideUp(300,function() {
parent.remove();
});
}
});
});

form submitting in jquery tab

I started using jquery and jquery-ui. I am facing a problem trying to submit a form that is inside a tab. Once i hit 'submit', the page refresh itself, the tabs are gone, and the url is changed to the tab's function url. the submit button is working, and i get the desired result. However, it is not on the same page as the tabs.
Does anyone have any idea on how to keep the page from refreshing?
example of my problem:
I have a page called 'index.php' with 3 different tabs. one of the tabs is called 'submit form' where there I have a form using POST method, it is taking its source from 'form.php'. once i hit the 'submit' button, the page refreshes, the url changes from 'www.example.com' to 'www.example.com/form.php', i get the result there, but the page is "plain", means that its not under a tab, just a normal page.
I hope I explained myself correctly.
Thanks!
EDIT:
here is my submission code:
$submit = $_POST['submit'];
$name= $_POST['name'];
if($submit){
echo 'submitted <br><br>';
echo "hello $name";
}
Capture the form submission in jQuery and then stop it with preventDefault();
$(function(){
$('#formID').on('submit', function(e){
e.preventDefault();
var formSrc = $(this).attr('action');
var formMethod = $(this).attr('method');
var formData = $(this).serialize();
$.ajax({
url: formSrc,
type: formMethod,
data: formData,
success: function(data){
//work with returned data from requested file
alert(data);
}
});
});
});
EDIT:
i should add that I chose to use on(); as opposed to the default submit(). This is because the form may or may not be available at DOM.ready.
In answer to your 2nd question: "what if I wanned to run this information returned through a php code in the same tab, how could I do that?"
Have your php script return values as JSON like:
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
echo json_encode($row);
Then you can have javascript do whatever you wish with the returned values, such as -
$.ajax({
url: 'sc_getData.php?id=' + ID,
type:'GET'
})
.done(function(myData) { // data = array returned from ajax
myData = JSON.parse(myData);
for (var i in tFields){
thisSourceField = sFields[i];
thisTargetField = tFields[i];
targetID = '#' + thisTargetField;
thisValue = myData[thisSourceField];
$(targetID).val( thisValue );
console.log(targetID + ': ' + thisValue);
}
})
I've setup arrays for Target and Source Fields. The source field arrays match the field names returned by the php script while the target field arrays will match the form field id's to be filled with the returned values.

Categories