got all values of input box are same - javascript

I am creating a update form. In this when i click on update button i got same values every time that's why update functionality is not working. I already tried to get values using ID attribute of input box but not working. I am new in this field and this task take lots of time. Thanks in advance.
$(document).ready(function() {
$(".update").click(function() {
var id = $(this).data('id');
var uname = $(".name1").val();
var email = $(".email1").val();
$.post("operation.php", {
ID: id,
operation: 'update',
name: 'uname',
email: 'uemail'
}, function(data) {
$("#result").html(data);
});
});
});
for($i = 0; $i < $num_of_records; $i++)
{
echo "<tr><td>";
echo "<input type='text' value=".mysql_result($all_records, $i,"name")." class='name1' id='name' placeholder='Name'><input type='text' value=".mysql_result($all_records, $i,"email")." class='email1' id='email' placeholder='Email'><input type='submit' data-id=".mysql_result($all_records, $i,"id")." class='delete' name='delete' id='delete' value='Delete'><input type='submit' data-id=".mysql_result($all_records, $i,"id")." class='update' name='update' id='update' value='Update'>";echo "</td></tr>";
}

The Javascript needs to select the inputs from the same row as the button that was clicked.
$(document).ready(function() {
$(".update").click(function() {
var row = $(this).closest("tr");
var id = $(this).data('id');
var uname = row.find(".name1").val();
var email = row.find(".email1").val();
$.post("operation.php", {
ID: id,
operation: 'update',
name: 'uname',
email: 'uemail'
}, function(data) {
$("#result").html(data);
});
});
});

A better solution do it like this,
I am giving you a small example as your code is bit tidy.
<?php
foreach($answers as $a)
{
?>
<a href="javascript:void(0)" data-answerid="<?php echo $a->id;?>" class="upvote_link" />Edit</a>
<?php
}
?>
jquery Onclick to get clicked value
$('.upvote_link').click(function(){
var unique_id = $(this).data('answerid');
console.log(unique_id);
});
Shoot a comment if you have any issue executing this.You should always write unique id in html elements. Javascript should be knowing that particular link is been clicked.

That's because your ids are same, so jQuery stops searching as soon as it matches the first element with that ID.
To prevent this from happening, use the .siblings() function, like so:
$(document).ready(function() {
$(".update").click(function() {
var id = $(this).data('id');
var uname = $(this).siblings(".name1").val();
var email = $(this).siblings(".email1").val();
$.post("operation.php", {
ID: id,
operation: 'update',
name: 'uname',
email: 'uemail'
}, function(data) {
$("#result").html(data);
});
});
});

Related

Getting updated input value for further update in jQuery

I use an Ajax form (with JQuery Validation Plugin) on my site. It works except for the following problem: if I enter something in a text field and then click on the send button, the value is updated. With each next update, however, the old value is always used. I already understand that I may have to work with .on or .keyup, but I understand how to properly integrate it into the code, after the click or outside ...
Update:
I have several fields in the form. Here is simplified code. I also noticed that after the first update of the form, no fields can be updated with newly entered values. All values remain old.
HTML:
<form id="org-684" class="org">
<input class="org-name" type="text" name="name" value="" required>
<button type="submit" class="updateOrg">Update</button>
</form>
JS:
$(document).ready(function(){
$('.updateOrg').click(function() {
var id = $(this).closest(".org").attr("id");
id = id.split('-');
id = id[1];
var org_id_attr = "#org-"+id;
var org_name = $(org_id_attr).find(".org-name").val();
$(org_id_attr).validate({
submitHandler: function() {
$.ajax({
type: "POST",
url: "update.php",
data: ({
id: id,
org_name: org_name
}),
success: function(response){
var result = jQuery.parseJSON(response);
$(org_id_attr).find(".org-name").val(result.name);
},
error: function() {
},
cache: false
});
return false;
}
});
});
})
PHP:
<?php
$orgId = $_POST['id'];
$orgName = $_POST['org_name'];
$select = "
SELECT
name
FROM
org
WHERE
id = $orgId
";
$result = $mysqli->query($select);
$row = $result->fetch_row();
$res = array(
'name' => $row[0]
);
echo json_encode($res);
I solved the problem. You just have to put the variables from the form behind the "SubmitHandler".
$(org_id_attr).validate({
submitHandler: function() {
var org_name = $(org_id_attr).find(".org-name").val();
$.ajax({
type: "POST",

Jquery-ui Auto complete with dynamic input field and multi dimension array in Laravel

I need to add products for sale with dynamic input field. The field use autocomplete from Jquery ui and later I want to fetch both ui.label and ui.value.
My dynamic Input Field Code
$(document).ready(function () {
var count = 1;
dynamic_field(count);
function dynamic_field(number) {
html = '<tr><div class="input_fields_wrap">';
html += '<td><input type="text" name="productname[]" class="form-control producttarget" id="product"/></td></div>';
html += '<td><input type="text" name="amount[]" class="form-control" /></td>';
if (number > 1) {
html += '<td><button type="button" name="remove" id="" class="btn btn-danger remove">Remove</button></td></tr>';
$('tbody').append(html);
} else {
html += '<td><button type="button" name="add" id="add" class="btn btn-success">Add</button></td></tr>';
$('tbody').html(html);
}
}
$(document).on('click', '#add', function () {
count++;
dynamic_field(count);
});
$(document).on('click', '.remove', function () {
count--;
$(this).closest("tr").remove();
});
});
I want to fetch productname, productid (which using autocomplete) and amount. and store it to database after form submit.
My Autocomplete Code
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$('body').on('click', '.producttarget', function(e) {
$(this).autocomplete({
source: function( request, response ) {
// Fetch data
$.ajax({
url:"{{route('autocomplete')}}",
type: 'post',
dataType: "json",
data: {
_token: CSRF_TOKEN,
search: request.term
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
$(this).val(ui.item.label); // this one worked
//this my problems.val(ui.item.value);
return false;
}
});
});
But the problem is, I don't know how to store ui.value in dynamic input
field when i use .onclick and target class for triggering autocomplete
function.
My Controller Code
public function search(Request $request)
{
$search = $request ->search;
$result = Product::where('productname', 'LIKE', '%'. $search. '%')->get();
$response = array();
foreach($result as $r){
$response[] = array("value"=>$r->id,"label"=>$r->productname);
}
echo json_encode($response);
exit;
}
Once i achieve that i probably gonna ask how to fetch the inputted array data into database. I feel stupid but this problem got me stuck for whole day, googling.
i found my solution, but i don't know if it is the best way. i add some increment for my id dynamic input with :
html += '<td><input type="text" name="productname[]" class="form-control target product" id="productname_' + count + '"/></td>';
html += '<td><input type="text" name="productid[]" class="form-control" id="productid_' + count + '"/></td></div>';
then i search the id of input which i want to store the data with :
var str = this.id;
var a = str.indexOf("_");
var b = str.length;
var number = str.substring(a+1, b);
$('#productid_'+nomor).val(ui.item.value);
i dont know if its a strange way to achieve this.
EDIT :
well i can store the ui.value now but when i add and remove the input field. the id is a mess. there are duplicate id for input field. so i guess i need to find the row count and append it to the id's.
EDIT 2:
just need to remove
$count--
in dynamic input code,
and the id duplicate gone.

How to write external PHP code to a div in another PHP file

So hear me out, I want to do a live search of employees in a database and have them show up in a page of my website. I want their employee data to appear on the screen along with some radio buttons to edit their information. Here are the components of the task I have so far:
Javascript: index.php
`
//Search bar functionality
$(document).ready(function() {
load_data();
function load_data(query) {
$.ajax({
url:"fetchUsers.php",
method:"POST",
data:{query:query},
dataType: 'json',
success:function(data) {
console.log(data);
function ajaxCall2(data){
$.ajax({
url:"showEmployees.php",
method:"POST",
data2:{data:data}
})
}
}
});
}
$('#search_text').keyup(function() {
var search = $(this).val();
if(search != '') {
load_data(search);
} else {
load_data();
}
});
});
</script>`
So the above code is doing the live search, the results are being stored in data. That works.
fetch.php
$db = new PDO('mysql:host=localhost;dbname=user_information;charset=utf8', 'root', 'root');
if(isset($_POST["query"]))
{
$users= $db->prepare("
SELECT * FROM login_information
WHERE user_name LIKE '%".$search."%'
");
$users->execute();
$users = $users->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($users);
}
else
{
return;
}
This is the PHP code that runs in the ajax call for the live search. NOW for each element in my array,$users, I want this code to be run and displayed in index.php:
echo "
<div class=employeeContainter>
<div class=employeeInformation>
<ul>
<li>User Name: " . $row['user_name'] . "</li>
<li>User ID: " . $row['user_id'] . "</li>
<li>User Email: " . $row['user_email'] . "</li>
<form action='editEmployee.php' method='POST'>
<label for='NotEmployed'>Not Employee</label>
<input type='radio' id='NotEmployed' name='Employee'";
if($row['isEmployee']==0) echo "checked='checked'/>";
else echo "/>";
echo "<br><label for='YesEmployed'>Employee</label>
<input type='radio' id='YesEmployed' name='Employee'";
if($row['isEmployee']==1) echo "checked='checked'/>";
else echo "/>";
echo "<br><input type='submit' name=updateButton value='Update User'/>
</form>
</ul>
</div>
</div>
";
https://gyazo.com/16899aa7a6426310e42ee9090eef3158
This is a picture of how I want things to work. I know how each part works individually but I cannot figure out how to get everything to work together. I know this is a long post but any help at all would be appreciated
EDIT:
So I've been recreating the PHP code in javascript here is where I'm at
function generateEmployeeData(employees){
employees.forEach(function(d){
var containerDiv = document.createElement('div');
var informationDiv = document.createElement('div')
var ul = document.createElement('ul');
var br = document.createElement('br');
var br2 = document.createElement('br');
//form
var form = document.createElement('form');
form.setAttribute("action","editEmployee.php");
form.setAttribute("method","POST");
//labels
var yesLabel = document.createElement('label');
var noLabel = document.createElement('label');
yesLabel.setAttribute("for","YesEmployed");
noLabel.setAttribute("for","NotEmployed");
//Radio buttons
//buttons need to have the same name so only one is selected
var yesButton = document.createElement('input');
var noButton = document.createElement('input');
yesButton.setAttribute("type","radio");
yesButton.setAttribute("name","Employee");
yesButton.setAttribute("id","YesEmployed");
noButton.setAttribute("type","radio");
noButton.setAttribute("name","Employee");
noButton.setAttribute("id","NotEmployed");
if(d.isEmployee == 1){
yesButton.setAttribute("checked","checked");
}
else{
noButton.setAttribute("checked","checked");
}
//submit button
var submit = document.createElement('input');
submit.setAttribute("type","submit");
submit.setAttribute("name","updateButton");
submit.setAttribute("name","updateButton");
submit.setAttribute("value","Update User");
containerDiv.setAttribute("id","employeeContainer");
// containerDiv.setAttribute("class","employeeContainer");
informationDiv.setAttribute("id","employeeInformation");
// informationDiv.setAttribute("class","employeeInformation");
document.getElementById('results').appendChild(containerDiv)
document.getElementById('employeeContainer').appendChild(informationDiv)
document.getElementById('employeeInformation').appendChild(ul)
var li = document.createElement('li');
li.innerHTML = "User Name: "
var li2 = document.createElement('li');
li2.innerHTML = "User ID: ";
var li3 = document.createElement('li');
li.innerHTML = "User Email: "
//generating the header for item card
var employeeHeaderDiv = document.createElement("div");
employeeHeaderDiv.setAttribute("class", "employeeHeader");
//generating the name div for the header
var employeeNameDiv = document.createElement("div");
employeeNameDiv.setAttribute("class", "employeeName");
var employeeNameTextNode = document.createTextNode(d.user_name);
var employeeEmail = document.createTextNode(d.user_email);
//prevent issues with display if the name for an item is too long
// if(employeeNameTextNode.length > 15){
// employeeNameTextNode = document.createTextNode(d.employeeName.slice(0,13) + "...");
// }
// employeeNameDiv.appendChild(employeeNameTextNode);
ul.appendChild(li);
ul.appendChild(li2);
ul.appendChild(li3);
li.innerHTML = li.innerHTML+ d.user_name;
li2.innerHTML = li2.innerHTML+ d.user_id;
li3.innerHTML = li3.innerHTML+ d.user_email;
ul.appendChild(form);
form.appendChild(noLabel);
noLabel.innerHTML = "Not Employee";
form.appendChild(noButton);
form.appendChild(br);
form.appendChild(yesLabel);
yesLabel.innerHTML = "Employee";
form.appendChild(yesButton);
form.appendChild(br2)
form.appendChild(submit);
});
}
This is what it looks like so far: https://gyazo.com/c5cb9cd6cae92ccba502a9d0efe82076
So I've made some progress, this function is being called in the success function of my ajax call so essentially on every keyup in the search bar. However, I have a few problems.
I can select both radio buttons but I need to be able to only select one at a time. Solved by giving each radio button the same name
If I continue typing new results are just appended below what I already have instead of updating what I have.
Any ideas?
Alright so I was able to solve my own problem but since someone may run into a similar problem as me one day I'll post my solution. The code in the edit is all set but as for updating the entries I just made another function called removeEmployeeData and placed it into my ajax function before I call generateEmployeeData:
function removeEmployeeData(){
$("div#employeeContainer").remove();
}
So my ajax function now looks like:
$.ajax({
url:"fetchUsers.php",
method:"POST",
data:{query:query},
dataType: 'json',
success:function(data) {
removeEmployeeData();
generateEmployeeData(data);
console.log(data);
}
});
Combine this with the above code and you now have a live search feature like this: https://gyazo.com/5efa11e50845afe8964c5dae6a9597e2

how to post the database value to next page using ajax

i am trying to post the database retrieved value to next page using ajax.i tried but it not posting, can any one guide me how to do it
php
connected with database
$sql = "SELECT * FROM `billingdatainputandexport` WHERE id='1'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
//print $sql;
$billingmonth=$rows['billingmonth'];
i want to pass this billing month to selectsuppliercostprice.php.
javascript
$(document).ready(function() {
$("#supplier").on("change", function() {
var billingmonth='$billingmonth';
var supplier = document.getElementById("supplier").value;
var mcc = document.getElementById("mcc").value;
var mnc = document.getElementById("mnc").value;
$.post('selectsuppliercostprice.php', { org: supplier,mcc: mcc,mnc: mnc,billingmonth: billingmonth }, function(result) {
$('#suppliercost').html(result);
}
);
});
});
selectsuppliercostprice.php.
$billingmonth=$_POST['billingmonth'];
Can you try this,
PHP
$billingmonth=$rows['billingmonth'];
echo '<input type="hidden" id="billingmonth" name="billingmonth" value="'.$billingmonth.'">'; // added hidden input
Javascript:
$("#supplier").on("change", function() {
var billingmonth= $('#billingmonth').val();
...
});
The post variable is $_POST not $POST so ... that should be right:
$billingmonth = $_POST['billingmonth'];
Also in Javascript you have to print the billingmonth variable. Javascript can't handle php-variables:
var billingmonth='$billingmonth';
to
var billingmonth='<?php echo $billingmonth; ?>';
Here is the latest code : u missed i guess the php tag inside ur script tag now try :)
$(document).ready(function() {
$("#supplier").on("change", function() {
var billingmonth='<?php echo $billingmonth ?>';
var supplier = document.getElementById("supplier").value;
var mcc = document.getElementById("mcc").value;
var mnc = document.getElementById("mnc").value;
$.post('selectsuppliercostprice.php', { org: supplier,mcc: mcc,mnc: mnc,billingmonth: billingmonth }, function(result) {
$('#suppliercost').html(result);
}
);
});
});
make hidden field and store your value in that and read that value in javascaript and pass it with ajax
<input type="hidden" name="some_name" value="<?php echo $billingmonth?>" id="some_name"/>
javascript code
$(document).ready(function() {
$("#supplier").on("change", function() {
var billingmonth=document.getElementById('billingmonth').value;
var supplier = document.getElementById("supplier").value;
var mcc = document.getElementById("mcc").value;
var mnc = document.getElementById("mnc").value;
$.post('selectsuppliercostprice.php', { org: supplier,mcc: mcc,mnc: mnc,billingmonth: billingmonth }, function(result) {
$('#suppliercost').html(result);
}
);
});
});
if you don't want to use it anyother place than
var billingmonth= '<?php echo $billingmonth?>';
Just Try.
Store $billingmonth value into any hidden input.
<input type="hidden" name="billing_month" id="billing_month" value="<?php echo $billingmonth; ?>"/>
Retrieve $billingmonth value in jQuery ready function using Hidden input id.
$(document).ready(function() {
$("#supplier").on("change", function() {
var billingmonth=$("#billing_month").val();
var supplier = $("#supplier").val();
var mcc = $("#mcc").val();
var mnc =$("#mnc").val();
$.post('selectsuppliercostprice.php', { org: supplier,mcc: mcc,mnc: mnc,billingmonth: billingmonth }, function(result) {
$('#suppliercost').html(result);
}
);
});
});

How to create/find right ID in multiple Form elements of same type $ajax function with jQuery Mobile?

I have a collapsible part of my jQuery Mobile page that are generated from PHP output from a MS Sql databas and content render as I like it to so that part is ok.
in each section I create a form with 3 buttons and they are supposed to have unique Id:s.
All forms are also created to have a unique id created in runtime.
actions.php (renders out my elements into mobilepage i a DIV)
$counter=0; reset counter for ID:s
while (odbc_fetch_row($rs)){
// data output from Db to make like 10 collapsible with different data
$html = "";
$html = "<div data-role='collapsible-set' data-mini='true'>";
$html.="<div data-role='collapsible' data-mini='true'>";
$html.="<h3><span style=float:left;><img src='../_pic/$image' alt='$imageText' /> ".substr($Time,0,16)." $Area</span><span style='float:right;' class='ui-btn-up-c ui-btn-corner-all' cnt> $data </span></h3>";
$html.="<p>ID: $ID $Id $Status<br />$Status $Description)</p>";
$html.="<form method='post' action=''>";
$html.="<button value='action1' id='action1$counter' data-mini='true' type='Submit'>Take Action1</button>";
$html.="<button value='action2' id='action2$counter' data-mini='true' type='Submit'>Take Action1</button>";
$html.="<button value='action3' id='action3$counter' data-mini='true' type='Submit'>Take Action1</button>";
$html.="<input type='hidden' id='id$counter' name='id' value='$dataName' />";
$html.="</form>";
$html.="</div>";
$html.="</div>";
echo utf8_encode($html);
$counter++; //upcount to make Id:s unique
} //end While
Then I have this function that listens for a button that submit:
$(':submit').live('click', function() {
var button = $(this).val();
if (button == 'action1') {
$.ajax({
url: '../_php/Functions.php',
data: 'button=' + $(this).val()+'&id='+$('#id').val(),
async: true,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
error: function (request,error) {
alert('error');
}
});
}
return false;
});
I cant seem to get another id than the first one since i need to make all ID:s unique in my forms and all I do now is to check: &id='+$('#id').val(). what I would like to have done is to link the button pressed-id number to my hidden field id-number so i get the right data out from it. As of now I only get the first form:s id evaluated...
If someone could point me in the right direction how to make that happen i´d be greatful.
functions.php (a switch statement is pre-testing for submit:ed action
function actions1(){
try {
if(isset($_GET['id'])){
do stuff with 'id'
}else{
do other stuff with 'id'
}
} catch(Exception $e) {
show error
}
}
If some part is unclear or if you feel I missed posting somepart - let me know. /thanks
Within event handlers this referes to the element
$(':submit').live('click', function(){
var id= this.id;
var button = $(this).val();
/* traverse within form to set hidden input, no need to worry about using ID's for them*/
$(this).closest('form').find('input[name=id]').val(id);
/* then in ajax */
data: 'button=' +button+'&id='+id,
})
Not full code....I left some of your code out for simplicity
You can use jQuery .attr() function to get an id or any other attribute value of an element.
$(':submit').live('click', function() {
var button = $(this).val();
var id = $(this).attr("id");
if (button == 'action1') {
$.ajax({
url: '../_php/Functions.php',
data: 'button=' + $(this).val()+'&id='+ id,
async: true,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
error: function (request,error) {
alert('error');
}
});
}
return false;
});
The solution was to go by attributes name of my hidden input.
var id = $(this).closest("form").find(':hidden').val();

Categories

Resources