I've tried and succeeded. but there are 2 row, only the first row is updated, not for the second row. if more than one row, the second row and others row will not be updated.
Can anyone help me implement with ajax ?
cart.php :
<td>
<form method="post" action="cart-update.php">
<input type="text" name="cart_id" value="<?php echo $row['cart_id']?>">
<input type="text" name="item_id" value="<?php echo $row['item_id']?>">
<input type="text" name="id" value="<?php echo $row['cdid']?>">
<center>
<button type="submit" class="qtyminus" field="quantity" name="minus" id="value-minus2" onclick="minusqty()">-</button>
<input type="text" name="quantity" class="qty" id="value2" value="<?php echo $row['qty']?>">
<button type="submit" class="qtyplus" field="quantity" name="plus" id="value-plus2" onclick="plusqty()">+</button>
</center>
</form>
</td>
//ajax & javascript
<script type="text/javascript">
function minusqty() {//update when press button -
var quantityVal = $("input[name='quantity']").val();
var qtyVal = quantityVal-1;
var idVal = $("input[name='id']").val();
var itemidVal = $("input[name='item_id']").val();
var cartidVal = $("input[name='cart_id']").val();
$.ajax({
url: 'cart-update.php',
method: 'GET',
data: {qty: qtyVal, item_id: itemidVal, id: idVal, cart_id: cartidVal },
cache: false,
dataType: 'html',
success: function(data) {
},
});
}
</script>
<script type="text/javascript">
function plusqty() {////update when press button +
var quantityVal2 = $("input[name='quantity']").val();
var qtyVal2 = quantityVal2-(-1);
var idVal2 = $("input[name='id']").val();
var itemidVal2 = $("input[name='item_id']").val();
var cartidVal2 = $("input[name='cart_id']").val();
$.ajax({
url: 'cart-update.php',
method: 'GET',
data: {qty: qtyVal2, item_id: itemidVal2, id: idVal2, cart_id: cartidVal2 },
cache: false,
dataType: 'html',
success: function(data) {
},
});
}
</script>
cart-update.php :
<?php
include 'config.php';
$cart_id = $_GET['cart_id'];
$id = $_GET['id'];
$item_id = $_GET['item_id'];
$qty = $_GET['qty'];
$myqry=mysqli_query($conn,"UPDATE cart_order_detail SET qty='$qty'
WHERE cart_id='$cart_id'
AND item_id='$item_id'
AND id='$id'");
?>
I've tried and succeeded. but there are 2 row, only the first row is updated, not for the second row. if more than one row, the second row and others row will not be updated.
I think its wrong here :
var quantityVal = $("input[name='quantity']").val();
On your onclick attributes in html, add event parameter
id="value-minus2" onclick="minusqty(event)">-</button>
id="value-plus2" onclick="plusqty(event)">-</button>
On your ajax scripts, add parameter to functions to catch event, then add preventDefault to prevent page refresh
function minusqty(e) { // minusqty
e.preventDefault()
function plusqty(e) { //plusqty
e.preventDefault()
Then on minusqty and plusqty ajax success, you do the changing of value of textbox
success: function(data) { // minusqty ajax success
quantityVal = qtyVal;
},
success: function(data) { // plusqty ajax success
quantityVal2 = qtyVal2;
},
Update:
Having many quantity fields, you should use
var quantityVal = $(this).closest("input[name='quantity']").val();
Related
I want to post my form by ajax to php then get values from inputs ( I did it and it works fine ) but I also want to post a JS variable i one ajax.
There is my FORM section.
<form action="new_alias.php" method="post" id="theForm">
<div class="form-group">
<label for="exampleInputEmail1">Wpisz nazwę aliasu</label>
<input type="text" name="alias" id="alias" class="form-control" id="exampleInputEmail1"
aria-describedby="emailHelp" placeholder="Nazwa aliasu">
</div>
<div class="form-group">
<label class="col-form-label">Wybierz domenę</label>
<?php
if ($resultt->num_rows > 0) {
echo '<select name="name" class="custom-select">';
// output data of each row
while ($row = $resultt->fetch_assoc()) {
echo "<option value='$row[name],$row[id]'>$row[name]</option>";
}
echo '</select>';
} else {
echo "0 results";
}
?>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Wpisz adresy docelowe</label>
<input type="text" name="source" id="source" placeholder="Adresy mailowe" autocomplete="nope"
autocomplete="off" class="typeahead tm-input form-control tm-input-info" />
</div>
<button type="submit" name="add" id="add" class="btn btn-primary mt-4 pr-4 pl-4">Utwórz</button>
</form>
and there is my script
<script>
$(document).ready(function () {
var tagApi = $(".tm-input").tagsManager({
hiddenTagListName: 'hiddenTagListA'
});
var x = '';
var test = '';
jQuery(".typeahead").typeahead({
name: 'source',
displayKey: 'source',
source: function (query, process) {
return $.get('ajaxpro.php', {
query: query
}, function (data) {
data = $.parseJSON(data);
console.log(data);
return process(data);
});
},
afterSelect: function (item) {
tagApi.tagsManager("pushTag", item);
x = document.getElementsByName("hiddenTagListA");
test = x[0].value;
console.log('to jest z afterSlect: ', test);
}
});
$(".btn").click(function (e) {
e.preventDefault();
$.ajax({
type: "post",
url: 'new_alias.php',
data: {
$("#theForm").serialize()
},
success: function () {
alert("Form Submitted: ");
},
});
});
});
</script>
I am using tagsManager which created hidden input with ID hiddenTagListA
I am trying to put all values from hiddenTagListA to var testand it works.
But now I want to post this variable also to my php because I want to put it into my DB. Taking all values from form woks but I must also post test variable.
In my console I am getting value from test like: something, something2, something3... ( tags separated by comma) It can be just string
If you use .serialize then you need to parse the string first to get posted data using AJAX. PHP function parse_str reads string & convert that into array.
Refer: http://php.net/manual/en/function.parse-str.php
You can use .serializeArray function instead of .serialize which make sure to give data in array format, which is easily retrievable in PHP using $_POST variable.
JS CODE
$(".btn").click(function (e) {
e.preventDefault();
var inputData = $("#theForm").serializeArray(); // .serializeArray gives data in array format instead of string format.
// you can insert new variables like below
inputData.push({"name":"hiddenTagListA", "value": document.getElementsByName("hiddenTagListA")[0].value});
$.ajax({
type: "post",
url: 'new_alias.php',
data: inputData,
success: function () {
alert("Form Submitted: ");
},
});
});
if you got the value in test, just put it in ajax
$(".btn").click(function (e) {
e.preventDefault();
$.ajax({
type: "post",
url: 'new_alias.php',
data: {
form: $("#theForm").serialize(),
hiddenTagListA: test
},
success: function () {
alert("Form Submitted: ");
},
});
});
I would like to get the 2 values separately in order to fill automatically the input in the first file from the PHP via AJAX, but when i console.log(data) I get all the data and I want to retrieve it separately in order to put it in different tags
<input id="regist" type="text" name="regist" onblur="passdata();">
<input id="atyp" type="text" name="atyp" >
<input id="mtow" type="text" name="mtow" >
<script>
$(document).ready(function(){})
function passdata() {
var regist = $('#regist').val();
$.ajax({
type: 'post',
url: 'checkdb.php',
data: 'regist='+regist,
success: function(data){
var atyp = $('#myvalue1').val();
var mtow = $('#myvalue1').val();
$('#atyp').text(atyp);
$('#mtow').text(mtow);
alert (aty+mtow);
console.log(data);
}
})
}
</script>
and PHP file.... of course with db connection
$regist = $_POST['regist'];
$conn = mysqli_connect($host,$user,$pwd,$db);
$sql= ("SELECT * FROM aircrafts where regist='$regist'");
$datas = mysqli_query($conn,$sql);
foreach ($datas as $row) {};
if(mysqli_num_rows($datas) == 0) {
echo 'non ce niente';
} else { ?>
<span id="myvalue1"><?php echo $atyp = $row['atyp'];?></span>
<span id="myvalue2"><?php echo $atyp = $row['mtow'];?></span>
<?php };
?>
Change your Ajax request to:
$.ajax({
type: 'post',
url: 'checkdb.php',
data: 'regist='+regist,
dataType: 'json', // NEW LINE
success: function(data) {
//var atyp = $('#myvalue1').val();
//var mtow = $('#myvalue1').val();
//$('#atyp').text(atyp);
//$('#mtow').text(mtow);
var atyp = data.atyp;
var mtow = data.mtow;
alert ('aty: ' + aty , 'mtow: ' + mtow);
console.log(data);
}
})
and in your PHP: change these lines
else{?>
<span id="myvalue1"><?php echo $atyp = $row['atyp'];?></span>
<span id="myvalue2"><?php echo $atyp = $row['mtow'];?></span>
<?php };
to this exactly lines
else {
echo json_encode( $row );
}
EDIT
Regarding your "DOM-event"-handling ("document onready" and "input#regist onblur") I recommend to do it like this.
HTML:
<!-- <input id="regist" type="text" name="regist" onblur="passdata();"> -->
<input id="regist" type="text" name="regist">
<input id="atyp" type="text" name="atyp">
<input id="mtow" type="text" name="mtow">
JavaScript:
function passdata(event) {
$.ajax({
type: 'post',
url: 'checkdb.php',
data: 'regist=' + $(event.target).val(),
dataType: 'json',
success: function(data){
console.log(data);
}
})
}
$(document).ready(function(){
// on blur event
$('#regist').on('blur', passdata)
// on input event | maybe this would be also an interesting option as it fires immidiately on input
// $('#regist').on('input', passdata)
})
This bootstrap seperates the logic from the markup which is a good practice in general.
I have a dynamically generated form.It has only one text input which value is ID dynamically fetched from database table (table_one). My aim is to submit this ID to another table(table_two). On my page I can see these IDs fetched from the table_one say: 1, 2, 3, 4 ,5, but when I submit any of these IDs say '2', it is only the last ID '5' that will be submitted to table_two. How can I amend my code so that when I submit row 2, ID '2' will be submitted not '5'? Below is my code.
HTML
<form>
<input type="text" id="name" name="name" value="<?php echo $name_id;?>" >
<button type="submit" onclick="return chk()">Edit</button>
</form>
JAVASCRIPT
function chk(){
var name = document.getElementById('name').value;
var dataString = 'name='+ name;
$.ajax({
type:"post",
url:"test.php",
data:dataString,
cache:false,
success: function(html){
$('#msg').html(html);
}
});
return false;
}
PHP
$name = $_POST['name'];
echo "$name";
You must add unique identifier or use the DOM. Simple solution to your case is:
HTML
<input type="text" id="name-<?php echo $name_id;?>">
<button type="submit" onclick="return chk(<?php echo $name_id;?>)">Edit</button>
Javascript
function chk(name_id){
$.ajax({
type:"post",
url:"test.php",
data: {
id: name_id,
name: $('#name-'+name_id).val()
},
cache:false,
success: function(html){
$('#msg').html(html);
}
});
return false;
}
And pass the id of the row you want to change. On the server you process both values from the $_POST. Hope this helps.
btw you don't need form element in this AJAX scenario.
Ok so i have a little problem with something.
I have a javascript/DOM script that submits a user comment to a php page via ajax, and there it works excellent.
But now i need to implement it on another page, a little differently. And can't seam to make it work . Would appreciate if someone could help me point my errors.
HTML part:
<form name="comment-form-<?php echo $comment['comment_id'];?>" id="comment-form-<?php echo $comment['comment_id'];?>" method="POST">
<div id="comments-approval">
<h1><?php echo $article['naslov'];?></h1>
<h2><?php echo $comment['comment_text'];?></h2>
<h3>[<?php echo date('d\. m\. Y\. H:i', $comment['comment_time']);?>] --- [ <?php echo $comment['comment_name'];?> ]</h3>
</div>
<input type="hidden" name="article_id" id="article_id" value="<?php echo $comment['comment_article_id'];?>" />
<input type="submit" value="✗" onclick="remove_comment('comment-form-<?php echo $comment['comment_id'];?>'); return false;" /> <!-- IKS -->
<input type="submit" value="✔" onclick="add_comment('comment-form-<?php echo $comment['comment_id'];?>'); return false;" /> <!-- OTKACENO -->
</form>
After the php foreach there are N-number of forms created, and every form has it's own unique ID
After that the moderator clicks on the button and calls the function ether ADD or REMOVE which send through the form ID in which the buttons are located.
The javascript part:
function add_comment(formid){
var target = String('"#'+formid+'"');
$(target).submit(function(){
$.ajax({
type: "POST",
url: "approvecomment.php",
data: $(this).serialize(),
dataType: 'text',
success: function(msg){
switch(msg) {
//message
}
}
});
return false;
});
}
I know that maybe it's a dumb mistake but i really don't have a clue what am I doing wrong.
EDIT:
Javascript part:
function add_comment(formid){
var target = '#'+formid;
alert(target);
$(target).submit(function(){
alert($(this).serialize());
$.ajax({
type: "POST",
url: "approvecomment.php",
data: $(this).serialize(),
dataType: 'text',
success: function(msg){
switch(msg) {
//message
}
}
});
return false;
});
}
Ok, so the first alert posts #comment-form-1
And the second does nothing.
and the form with the ID comment-form-1 exists in the document.
If you're already using JQuery - why not just bind the submit buttons to JQuery's .click() handler instead of hard coding it in the HTML itself?
(Note that I'm assuming your AJAX function for removing comments is "removecomment.php")
Updated HTML:
<form name="comment-form-<?php echo $comment['comment_id'];?>" id="comment-form-<?php echo $comment['comment_id'];?>" method="POST">
<div id="comments-approval">
<h1><?php echo $article['naslov'];?></h1>
<h2><?php echo $comment['comment_text'];?></h2>
<h3>[<?php echo date('d\. m\. Y\. H:i', $comment['comment_time']);?>] --- [ <?php echo $comment['comment_name'];?> ]</h3>
</div>
<input type="hidden" name="article_id" id="article_id" value="<?php echo $comment['comment_article_id'];?>" />
<input type="submit" class="comment-remove" value="✗" /> <!-- IKS -->
<input type="submit" class="comment-add" value="✔" /> <!-- OTKACENO -->
Updated JS:
//COMMENT ADD CLICK HANDLER
$("input.comment-add").click(function() {
$.ajax({
type: "POST",
url: "approvecomment.php",
data: $(this).parent().serialize(),
dataType: 'text',
success: function(msg){
switch(msg) {
//message
}
}
});
return false;
});
//COMMENT REMOVE CLICK HANDLER
$("input.comment-remove").click(function() {
$.ajax({
type: "POST",
url: "removecomment.php",
data: $(this).parent().serialize(),
dataType: 'text',
success: function(msg){
switch(msg) {
//message
}
}
});
return false;
});
I want to insert data into table using ajax so data will insert without reload of page.
This code insert data into table very well but code also reload the page.
But I want insert without reloading of page.
How can i do this ?
<?php
include('connection.php');
if(isset($_POST['cmt'])){
$comment = addslashes($_POST['cmt']);
$alertid = $_POST['alert_id'];
mysql_query("INSERT INTO `comments` (`id`, `alert_id`, `comment`, `username`) VALUES (NULL, '".$alertid."', '".$comment."', 'tomas')");
}
?>
<script>
function submitform(){
var comment = $("#comment").val();
var alertid = $("#alertid").val();
$.ajax({
type: "POST",
//url: "ana.php",
data:{cmt:comment,alert_id:alertid}
}).done(function( result ) {
$("#msg").html( result );
});
}
</script>
<form method = "POST" onsubmit = "submitform()">
<textarea onFocus = "myFunction(1)" onBlur = "myFunction(0)" style="margin: 0px 0px 8.99305534362793px; width: 570px; height: 50px;" rows = "6" cols = "40" id = "comment"></textarea><br />
<input type = "text" placeholder="Enter Maximium 100 Words" id = "alertid" value = "10">
<input type = "submit" name = "submit" value = "Comment">
</form>
try this add this to form onsubmit = "return submitform();"
function submitform(){
var comment = $("#comment").val();
var alertid = $("#alertid").val();
$.ajax({
type: "POST",
//url: "ana.php",
data:{cmt:comment,alert_id:alertid}
}).done(function( result ) {
$("#msg").html( result );
});
return false;
}
return false from your event handler function.
onsubmit="submitform(); return false;">
Consider moving to modern methods of event binding.
You have to create a php file that insert into your table the posted data and call it with ajax like that :
$.ajax({
url: "/file.php",
type: "POST",
cache: false,
dataType: "json",
data: postValue,
success: function(results) {
bootbox.alert(results.message, function() {
bootbox.setIcons(null);
window.location.reload();
});
},
error: function(results) {
bootbox.alert(results.message, function() {
bootbox.setIcons(null);
});
}
});