Get selected value in jquery script - javascript

I have a list of elements which are gotten from a xml file and I write them down in a table. In every row, I have a form which send the input field values to a jquery script, but it always pass the first value of the table, Does anyone knows how to pass the selected value?
This is my html and php code:
<?php
$licenseElement = "";
foreach ($xml->xpath("/Resultado/Registro") as $licenseElement):?>
<form>
<input type="hidden" id="desactivate" name="desactivate" value="" />
<input type="hidden" id="name" name="name" value="<?php echo $licenseElement->nombre; ?>" />
<input type='button' value='Desactivate' onclick='myCallDesactivate(desactivate,name);' />
</form>
<?php endforeach; ?>
And this is the jquery script:
<script>
function myCallDesactivate(desactivate,name) {
var val1 = $('#desactivate').val();
var val2 = $('#name').val();
var request = $.ajax({
url: "mypage.php",
data: { desactivate: val1, name: val2 },
type: "POST",
dataType: "html"
});
request.done(function(msg) {
$("#mybox2").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
}
</script>

Related

Is there a way to autocomplete textbox in dynamic textbox? PHP Codeigniter

How can I use autocomplete textbox in a dynamic textbox
In the image below, the first textbox is working, autocomplete is showing but the second and third or 4th textbox autocomplete does not work. The textbox/input should show autocompletion of names.
Is there a way to fix this?
My Input texts
<td><input type="text" name="name[]" id="autouser" placeholder="Enter Signatory Name" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">+</button></td>
Dynamically add inputs - I have tried to place #autouser in the script codes but still it does not work
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td>'+
'<input type="text" name="name[]" id="autouser" placeholder="Enter Signatory Name" class="form-control name_list" />'+
'</td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button>'+
'</td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
</script>
Autocomplete input code.
<script type='text/javascript'>
$(document).ready(function(){
// Initialize
$("#autouser").autocomplete({
source: function( request, response ) {
// Fetch data
$.ajax({
url: "<?php echo base_url(); ?>users/userList",
type: 'post',
dataType: "json",
data: {
search: request.term
},
success: function( data ) {
response( data );
}
});
},
select: function (event, ui) {
// Set selection
$('#autouser').val(ui.item.label); // display the selected text
$('#userid').val(ui.item.value); // save selected id to input
return false;
}
});
});
</script>
If ever needed:
Controller:
Use for autocomplete
public function userList(){
// POST data
$postData = $this->input->post();
// Get data
$data = $this->user_model->getUsers($postData);
echo json_encode($data);
}
Model
function getUsers($postData){
$response = array();
if(isset($postData['search']) ){
// Select record
$this->db->select('*');
$this->db->where("username like '%".$postData['search']."%' ");
$records = $this->db->get('employees')->result();
foreach($records as $row ){
$response[] = array("value"=>$row->employee_id,"label"=>$row->username);
}
}
return $response;
}

How to get rid from the same id in while loop when submitting form using ajax

I am submitting form using ajax in the while loop but because of loop the same form id is using many times , so as a result the form is submitting only once . I think i have to make unique id every time in the loop for the form but don't know how.
Here is my code so far,
<?php
$get_cmt ="SELECT * FROM comments WHERE post_id = $post_id ORDER BY id DESC";
$query_cmt = mysqli_query($db_conx,$get_cmt);
while($row_cmt=mysqli_fetch_array($query_cmt,MYSQLI_ASSOC)){
$comtr_id = $row_cmt['comtr_id'];
$comment_id = $row_cmt['id'];
?>
<form id="subcmt_smt" method="post">
<textarea name="subcmt"></textarea>
<input type="hidden" value="<?php echo $comment_id;?>" name="comment_id">
<input type="hidden" value="<?php echo $pager_id;?>" name="comtr_id">
</form>
<?php } ?>
<script src="jQuery v2.1.1"></script>
<script>
$("#subcmt_smt").submit(function(e) {
var form = $(this);
var url = form.attr('action');
e.preventDefault();
$.ajax({
type: "POST",
url: "submit_subcmt.php",
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
</script>
submit_subcmt.php
<?php
$comtr_id =$_POST['comtr_id'];
$comment_id =$_POST['comment_id'];
echo $comtr_id;
echo $comment_id;
?>
Try this.
<?php
$get_cmt ="SELECT * FROM comments WHERE post_id = $post_id ORDER BY id DESC";
$query_cmt = mysqli_query($db_conx,$get_cmt);
while($row_cmt=mysqli_fetch_array($query_cmt,MYSQLI_ASSOC)){
$comtr_id = $row_cmt['comtr_id'];
$comment_id = $row_cmt['id'];
?>
<form class="subcmt_smt" method="post">
<textarea name="subcmt"></textarea>
<input type="hidden" value="<?php echo $comment_id;?>" name="comment_id">
<input type="hidden" value="<?php echo $pager_id;?>" name="comtr_id">
</form>
<?php } ?>
<script src="jQuery v2.1.1"></script>
<script>
$(".subcmt_smt").submit(function(e) {
var form = $(this);
var url = form.attr('action');
e.preventDefault();
$.ajax({
type: "POST",
url: "submit_subcmt.php",
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
</script>
To illustrate the comment I made above you could try something similar to this perhaps.
<?php
$get_cmt ="SELECT * FROM comments WHERE post_id = $post_id ORDER BY id DESC";
$query_cmt = mysqli_query($db_conx,$get_cmt);
while( $row_cmt=mysqli_fetch_array($query_cmt,MYSQLI_ASSOC) ){
$comtr_id = $row_cmt['comtr_id'];
$comment_id = $row_cmt['id'];
?> <!-- use a class attribute here -->
<form class="subcmt_smt" method="post">
<textarea name="subcmt"></textarea>
<input type="hidden" value="<?php echo $comment_id;?>" name="comment_id">
<input type="hidden" value="<?php echo $pager_id;?>" name="comtr_id">
</form>
<?php
}//end loop
?>
<script src="jQuery v2.1.1"></script>
<script>
/* and assign event handlers to form objects with this class as per above */
$("form.subcmt_smt").submit(function(e) {
var form = $(this);
var url = form.attr('action');
e.preventDefault();
$.ajax({
type: "POST",
url: "submit_subcmt.php",
data: form.serialize(),
success: function(data) {
alert(data);
}
});
});
</script>

json increments one id but displays all ids

i am using json for like button. when users clicks it correctly increases the like count and stores in database for corresponding id but it shows increment for all ids in browser which is wrong. i want to display for only id where users has liked but it shows for all.
test url is http://way2enjoy.com/app/check/test/indexp.php
indexp.php file is
<?php
include('/home/xxx/con.php');
$query="Select * from users_jokes order by id desc limit 10";
$result=mysql_query($query);
?>
<html>
<head>
<meta charset="utf-8">
<script src="jquery-3.1.0.min.js"></script>
<script type="text/javascript">
var ajaxSubmit = function(formEl) {
var url = $(formEl).attr('action');
var comment=document.getElementById("jokes_comment").value;
var joke_id=document.getElementById("joke_id_hidden").value;
$.ajax({
url: url,
data:{
'action':'addComment',
'comment':comment,
'joke_id':joke_id
},
dataType: 'json',
type:'POST',
success: function(result) {
console.log(result);
$.ajax({
url: url,
data:{
'action':'getLastComment',
'joke_id':joke_id
},
dataType: 'json',
type:'POST',
success: function(result) {
$('#jokes_comment').val("");
console.log(result[0].description);
$("#header ul").append('<li>'+result[0].description+'</li>');
},
error: function(){
alert('failure');
}
});
},
error: function(){
alert('failure');
}
});
// return false so the form does not actually
// submit to the page
return false;
}
var ajaxLike=function()
{
var joke_id=document.getElementById("joke_id_hidden").value;
// setup the ajax request
$.ajax(
{
url: 'likeskk.php',
data:{
'action':'increment_like',
'joke_id':joke_id
},
dataType: 'json',
type:'POST',
success: function(result)
{
$.ajax(
{
url: 'likeskk.php',
data:{
'action':'display_like',
'joke_id':joke_id
},
dataType: 'json',
type:'POST',
success: function(result)
{
console.log(result);
$("label[for='like_counter']").text(result.likes);
},
error: function(result)
{
alert("error 2");
},
});
},
error: function()
{
alert('failure');
}
});
return false;
}
</script>
<p>commnet list</p>
<div id="header">
<ul id="commentlist" class="justList">
<?php
$query="Select * from comment where joke_id='2'";
$result=mysql_query($query);
while($data = mysql_fetch_array($result)){
$cont = $data['description'];
?>
<li><?php echo $cont;
?></li>
<?php
}
?>
</ul>
</div>
<?php
?>
<form method="post" action="processkk.php" onSubmit="return ajaxSubmit(this);">
<input type=text id="jokes_comment" name="jokes_comment">
</input>
<input type="submit" value="comment">
</form>
</body>
</html>
<?php
while($data = mysql_fetch_array($result)){
$id = $data['id'];
$cont = $data['content'];
$likes = $data['likes'];
?>
<p><?php echo $cont;?></p>
<input type="hidden" value="<?php echo $id ;?>" id="joke_id_hidden">
<p><button onClick="ajaxLike();">Like</button> <label for="like_counter"><?php echo $likes;?></label></p>
<?php }
?>
</body>
</html>
likeskk.php
<?php
include('/home/xxxxxxx/con.php');
$action=$_POST['action'];
if($action=="increment_like")
{
$joke_id=$_POST['joke_id'];
$query="update users_jokes set likes =likes+1 where id='".$joke_id."'";
$result=mysql_query($query);
// setup our response "object"
$retVal=array("Success"=>"true");
print json_encode($retVal);
}
if($action=="display_like")
{
$joke_id=$_POST['joke_id'];
$query = "select likes from users_jokes where id = '$joke_id'";
$qry = mysql_query($query);
while($rows = mysql_fetch_array($qry)){
$likes = $rows['likes'];
}
header('Content-Type: application/json');
// print json_encode(array('foo' => 'bar'));
print json_encode(array('success'=>'true','likes'=>$likes));
}
?>
when i click on one like all like increases. when i post comment on one id it appended and displays in all id
Copy and paste it.
<html>
<head>
<script>
function clickCounter(element)
{
element.value = parseInt(element.value) + 1;
}
</script>
</head>
<body>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
</body>
</html>
Because you are using the same id. id must be unique
<input type="hidden" value="4638" id="joke_id_hidden">
Rather than using a hidden input for each entry you could use a dataset on the button itself with the corresponding ID. When the button is clicked the javscript function could read that dataset value and use that in the ajax POST request. So, as an example:
<!doctype html>
<html>
<head>
<title>Like the jokes...</title>
</head>
<body>
<form id='bttns'>
<?php
/* pseudo generate some jokes with buttons and labels to emulate your page */
for( $i=1; $i < 20; $i++ ){
$random=rand(1,20);
echo "
<p>Funny joke...[{$i}]</p>
<input type='button' value='Like' data-id='$i' />
<label class='counter'>{$random}</label>";
}
?>
</form>
<script type='text/javascript'>
var col=document.querySelectorAll('#bttns input[type=\"button\"]');
for( var n in col )if(col[n].nodeType==1)col[n].onclick=function(e){
var el=typeof(e.target)!='undefined' ? e.target : e.srcElement;
var label=el.nextSibling.nextSibling;
var id=el.dataset.id;
label.innerHTML=parseInt( label.innerHTML )+1;
alert( 'use ajax to POST this id: '+id );
}
</script>
</body>
</html>
I should add perhaps that the ajax callback function would be the place to update the value of likes for each joke rather than as here - it's just example code showing how you could do away with hidden fields and the problem of duplicate ids.

Passing javascript value to php and back

I am having some trouble with passing a javascript value to php and back.
The idea is that I have a form where a user fills out a postal code and is then (onBlur) presented with the correct street and city in two different input fields. The street and city are collected by POST method from an external php file (getAddress.php).
I know that the php script returns the correct values and the complete() function is called onBlur, but I don't know whether the value gets passed onto the php script and back.
Javascript
<script language="javascript">
function complete() {
var postalCode = document.getElementsByName("postalCode")[0].value;
if(postalCode.length === 6) {
var dataString = "postalCode=" + postalCode;
$.ajax({
type: "POST",
url: "getAddress.php",
dataType: "html",
data: dataString,
success: function(results) {
var json = JSON.parse(results);
document.getElementById("street").value = json.street;
document.getElementById("city").value = json.city;
}
});
}
}
</script>
getAddress.php
<?php
$postalCode = $_POST['postalCode'];
$postalCode = substr_replace($postalCode, ' ', 4, 0);
$sql = 'SELECT * FROM postalCodes WHERE postalCode="'.$postalCode.'"';
$res = $con->query($sql);
$res->data_seek(0);
while($row = $res->fetch_assoc()) {
$ID = $row['ID'];
$street = $row['street'];
$city = $row['city'];
$results[] = array('ID' => $ID, 'street' => $street, 'city' => $city);
}
echo json_encode($results);
?>
HTML
<input name="postalCode" type="text" maxlength="6" onBlur="complete()" /><br />
<input name="street" id="street" type="text" disabled /><br />
<input name="number" type="text" maxlength="6" /><br />
<input name="city" id="city" type="text" disabled /><br />
Change dataType: "html", to dataType: "json", and your $results is array so you need to use index
Try this:
function complete() {
var postalCode = document.getElementsByName("postalCode")[0].value;
if (postalCode.length === 6) {
var dataString = "postalCode=" + postalCode;
$.ajax({
type: "POST",
url: "getAddress.php",
dataType: "json",
data: dataString,
success: function(results) {
document.getElementById("street").value = results[0].street;
document.getElementById("city").value = results[0].city;
}
});
}
}
As you are getting 500 internal server error message one of the reason can be that
$con->query($sql) is failing, make sure $con is initialized and table and field name are correct.

Using AJAX to post form data to PHP page

I am simply trying to use the data submitted in a search form to query the database and bring back results similar to the search. My form looks like this:
<div id="searchform">
<form method="get">
<form id="submitsearch">
<input id="shop" name="shop" type="text" placeholder="Find a shop" />
<input id="submitbutton" type="submit" value="Go"/>
</form>
</form>
<div id="searchresults">
</div>
</div>
the Javascript I've got is:
$("#submitsearch").submit(function(event) {
event.preventDefault();
$("#searchresults").html('');
var values = $(this).serialize();
$.ajax({
url: "external-data/search.php",
type: "post",
data: values,
success: function (data) {
$("#searchresults").html(data);
}
});
});
return false;
I have also tried...
$("#submitbutton").click(function(){
var form_data = $("#submitsearch").serialize();
$.ajax({
url: "external-data/search.php",
type: 'POST',
data: form_data,
success: function (data) {
$("#searchresults").html(data);
}
});
return false;
});
And this seems to work slightly as it shows results, the first doesn't do anything. It's not sending the data to the PHP page but the PHP I've got is:
<?php
$str_shops = '';
$shop = $_POST['form_data'];
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM shops WHERE name LIKE '%$shop%'";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shops .= "<strong>" . $row['name'] . "</strong><br>" .
$row['address'] . "<br><br>";
}
mysqli_free_result($result);
echo $str_shops;
mysqli_close($db_server);
?>
Any help would be greatly appreciated! Thanks in advance.
You have two form tags. This won't work. You want one form tag with two attributes
<form method="get">
<form id="submitsearch">
to
<form method="get" id="submitsearch">
you can do it without using html form.
first you call the php page and then display a data within html.
this is what I do?!
<div>
<input id="shop" type="text" placeholder="Find a shop" />
<input id="submitbutton" type="button" value="Go"/>
</div>
<div id="searchresults">
</div>
<script type="text/javascript">
$(function() {
$("#submitbutton").click(function(){
try
{
$.post("root/example.php",
{
'shop':$("#shop").val().trim()
}, function(data){
data=data.trim();
$("#searchresults").html(data);
// this data is data that the server sends back in case of ajax call you
//can send any type of data whether json or json array or any other type
//of data
});
}
catch(ex)
{
alert(ex);
}
});
});
</script>

Categories

Resources