how to get the value from php with AJAX - javascript

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.

Related

update quantity with ajax

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();

Passing prompt data from javascript to php using ajax

First of all i know there are multiple topics about this on stackoverflow, i read most of them but i still cant figure out why the following is not working.
So i have a form like this:
echo "<td> <form action=\"admin.php\" method=\"GET\" onsubmit=\" modifyPassword();\">
this is the modifyPassword function:
function modifyPassword(){
var newpw=prompt("Enter a new password");
if(newpw !== null){
$.ajax({
type: "GET",
url: "admin.php",
data: newpw,
success: function(data)
{
console.log(data);
}
});
}}
And when the form is actually submitted i want to get the value from what is typed in like this:
echo $_GET['data'];
This is all in the same file.
The output of $_GET['data'] does not show anything.
Can someone tell me what i am doing wrong?
//edit, more code:
I am using multiple forms, so here is the code that handles the form:
}elseif (isset($_GET['Modify'])){
echo $_GET['data'];
Form itself:
echo "<td> <form action=\"admin.php\" method=\"GET\" onsubmit=\" modifyPassword();\">
<input type='hidden' name='counter' value=\"$count\"/>
<input type=\"submit\" value=\"Modify\" name=\"Modify\"/>
Function that is provided:
<script type="text/javascript">
function modifyPassword(){
var newpw=prompt("Enter a new password");
if(newpw !== null){
$.ajax({
type: "GET",
url: "admin.php",
data: {data: newpw}, // passing a key/value pair
success: function(data)
{
console.log(data);
}
});
}}
</script>
data: newpw, should be data: {data: newpw}, This will result in $_GET['data'] being populated. In this case 'data' becomes the key, while 'newpw' is the value.
function modifyPassword(){
var newpw=prompt("Enter a new password");
if(newpw !== null){
$.ajax({
type: "GET",
url: "admin.php",
data: {data: newpw}, // passing a key/value pair
success: function(data)
{
console.log(data);
}
});
}}
I will argue that you should not use so many variables with the same name - just to make things less confusing during bug hunting.

$_POST won't receive ajax

AJAX works fine, but $_POST does not have a value.
What I have tried:
$data = json_decode(file_get_contents('php://input'), true); &
$post = json_decode($data); into storecart.php
Changing the data into 'jCart=' + jData'
removing datatype (Jaromanda X)
answer (Umakant Mane)
cart is an array of objects
Javascript:
$(document).ready(function(){
$("#showcart").click(function(event){
event.preventDefault();
showcart();
url = 'cart.php';
$(location).attr("href",url);
});
});
function showcart(){
var jData = JSON.stringify(cart);
$.ajax({
url:"storecart.php",
type:"post",
data: {jCart : jData},
datatype: "json",
success: function(data){
console.log("SUCCESS")
console.log(jData);
},
error: function(data){
console.log("REDO")
}
});
}
storecart.php:
<?php
if(isset($_POST['jCart'])){
echo "Right";
}else{
echo "Wrong";
}
?>
How do get the $_POST to accept the json.stringify?
SOLUTION:
SOLVED:
All i did was add a form that has a hidden value
<form id = "postform" action = "cart.php" method = "post">
<input type = "hidden" id="obj" name="obj" val="">
<input type = "submit" value = "Show Cart" id = "showcart">
</form>
In the Javascript:
$(document).ready(function(){
$("#showcart").click(function(){
var json = JSON.stringify(cart)
$('#obj').val(json);
$('#obj').submit();
});
});
Thank you for everyone that has answered but hope this helps.
$(document).ready(function(){
var data = {one:"one", two:"two", three:"three"};
var jsonData = JSON.stringify(data);
$("#clickme").click(function() {
$.ajax({
url:"demo.php",
type:"POST",
data:{cart:jsonData},
success:function(response){
console.log(response);
}, error:function(err) {
console.log(err);
}
})
});
});
PHP
<?php
if(isset($_POST['cart'])){
echo "Right";
}else{
echo "Wrong";
}
?>

How to insert into mysql table using ajax?

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);
});
}
});

Using ajax to send form data to php

I want to send form data from ajax to php. My ajax retrieves the form data but it doesnt send it i dont see anything wrong with the code maybe i need a much more professional help. Thanks in advance
HTML5 syntax
<div align="center"><a id="hi">Header</a></div>
<a id="signup" data-add-back-btn="true" style="float:right;" data-icon="arrow-r">Sign- In</a>
</div>
<form class="check-user" action="php/sup.php" method="POST">
<label>Username</label>
<input id="Susername" name="username" placeholder="username" type="text" >
</div>
<div align="center" data-role="fieldcontain" style="width:100%;overflow:hidden" data-position="static">
<label>Email</label>
<input id="Semail" name="email" placeholder="email" type="email" >
</div>
<div align="center" data-role="fieldcontain" style="width:100%;overflow:hidden" data-position="static">
<label>Password</label>
<input id="Spassword" name="password" placeholder="password" type="password" >
</div>
<!---input type="submit" style="visibility:hidden;" id="send"/-->
</form>
Ajax syntax
$('#signup').live('click', function(){
//var name = document.getElementById('Susername').value;
//var email = document.getElementById('Semail').value;
//var pass = document.getElementById('Spassword').value;
var that = $('form.check-user'),
urls = that.attr('action'),
methods = that.attr('method'),
data = {};
that.find('[name]').each(function(index, element) {
var that = $(this),
name = that.attr('name'),
element = that.val();
alert(name+'='+element+' '+methods);
data[name] = element;
});
$.ajax(
{
url: urls,
type: methods,
data : data,
beforeSend: function(response){alert('Sending');},
success: function(response){ alert('success');},
error: function(response){alert('failed');},
complete: function(response){alert('finished');},
}
);
return false;
});
PHP syntax
session_start();
$name = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
if(isset($name) && isset($email) && isset($password))
{
echo $name;
$_SESSION['username'] = $name;
}
else
{
die('data not set');
}
You can use serialize method on form, it will gather everything correct.
$('#signup').live('click', function(){
var that = $('form.check-user'),
urls = that.attr('action'),
methods = that.attr('method'),
data = that.serialize();
$.ajax(
{
url: urls,
type: methods,
data : data,
beforeSend: function(response){alert('Sending');},
success: function(response){ alert('success');},
error: function(response){alert('failed');},
complete: function(response){alert('finished');},
}
);
return false;
});
Try this,
$('#signup').live('click', function(){
$.ajax({
url:’’,//url to submit
type: "post",
dataType : 'json',
data : {
'Susername' : $('#Susername').val(),
'Semail' : $('#Semail').val(),
'Spassword' : $('#Spassword').val()
},
success: function (data)
{
}
});
return false;
});
I solved it works this way on the php side you do this
$name = isset(json_decode($_POST['username']));//htmlentities($values[0]);
$email = isset(json_decode(($_POST['email'])));//htmlentities($values[1]);
$password = isset(json_decode($_POST['password']));//htmlentities($values[2]);
The Ajax side
$(document).ready(function(e) {
$('#signup').live('click', function(){
//var name = document.getElementById('Susername').value;
//var email = document.getElementById('Semail').value;
//var pass = document.getElementById('Spassword').value;
var that = $('form.check-user'),
urls = that.attr('action'),
methods = that.attr('method'),
data = {};
data = that.serialize();
console.log(data);
$.ajax(
{
url: urls,
type: methods,
dataType:'json',
data : data,
beforeSend: function(response){$.mobile.showPageLoadingMsg(true);},
success: function(response){ $.mobile.showPageLoadingMsg(false);},
error: function(xhr, textStatus, errorThrown){alert(textStatus);},
complete: function(response){},
}
);
return false;
});
});

Categories