Ajax to read from form - php

I'm writing a store system for my game,
it worked quite well until I found out that it only takes the amount of first entered Item.
function pbuy(buyitem) {
var amountc = "amount-"+buyitem,
var amount = $("#"+amountc+"").val();
$.ajax({
type: "POST",
url: "store2.php",
data: "buyitem="+ buyitem+"&amount="+amount,
success: function(resp){
document.getElementById('ajaxDiv').innerHTML = resp;
},
error: function(e){
alert('Error: ' + e);
}
});
}
I'm trying to give it it the Id of the form like so:
function pbuy(buyitem) { var amountc = "amount-"+buyitem, var amount = $("#"+amountc+"").val();
But nothing happens.
The code the creation of the forms is:
<tr>
<td class='items' width='80%' align='center' valign='top'>
<?PHP echo $itemstore->itemname;?>
</td>
<td width="20%">
Price:<?PHP echo $itemstore->newprice;?>
<form method="post">
<input type='text' id='amount-<?PHP echo $row;?>)' />
<input name="itembid" type="button" onclick="pbuy(<?PHP echo $row;?>)" value="Buy" />
</form>
</td>
</tr>
If I hardcode the amount in the ajax function it all runs fine like it should.

You're getting a javascript error before the AJAX-request is being sent since you are defining your amountc and amount variables separated by a comma. Either do
var amountc = "amount-"+buyitem;
var amount = $("#"+amountc+"").val();
semicolon separated, or keep the comma and skip the second var
var amountc = "amount-"+buyitem,
amount = $("#"+amountc+"").val();

Did you checked the response of the AJAX request?

Related

Ajax .click from list only picking up first line values

Hi my HTML list with Buttons linked to Ajax script is only picking up on the first line.
PHP Page
<?php
$sql="SELECT * FROM scanns WHERE `site` = '$csite' AND `date` BETWEEN '$sdate' AND '$edate' ";
$result_set=mysqli_query($link,$sql);
while($row=mysqli_fetch_array($result_set))
{
?>
<tr>
<td><?php echo $row['date']; ?></td>
<td><?php echo $row['site']; ?></td>
<td><?php echo $row['file_name']; ?></td>
<td>view scann</td>
<td>
<input class='date' type='hidden' value= "<?php echo $row['date']; ?>"/>
<input class='site' type='hidden' value= "<?php echo $row['site']; ?>"/>
<input class='filename' type='hidden' value= "<?php echo $row['file_name']; ?>"/>
<input class="submit" type="button" value="Delete Scan">
</td>
<td>
<input class="stamp" type="button" value="Post File">
</td>
</tr>
<?php
}
?>
</table>
Ajax call
$(document).ready(function(){
"use strict";
$('.submit').click(function(){
var date = $('.date').val();
var site = $('.site').val();
var filename = $('.filename').val();
var dataString = 'date='+ date + '&site='+ site + '&filename='+ filename;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "cscanndelete.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
return false;
});
$('.stamp').click(function(){
var date = $('.date').val();
var site = $('.site').val();
var filename = $('.filename').val();
var dataString = 'date='+ date + '&site='+ site + '&filename='+ filename;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "scanstamp.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
return false;
});
});
If you click on any of the buttons it only pickups the values of the first line not sure how to fix or even if i can.
$('.date').val() will return the value of the first matching element. Since there are many matching elements on the page, it's always returning that first table row.
You're in the context of the $('.submit') selector, so you can use that as a starting point to traverse the DOM and find the specific element you want. Something like this:
var date = $(this).closest('tr').find('.date').val();
That should start at this (the submit button), examine up to the containing tr (which has all of the elements you're looking for in this case), and then find the matching element(s) just within that context. As long as there's only one .date element within that parent tr, it'll return the value from that one element.
In your case you may also make use of something like .prev('.date'), or only traverse up to the td instead of the tr, etc. There are a number of ways to go about it, depending on how robust it may need to be if the markup changes slightly.
$('.date').val()
will always return the value of the first matching element. If you want to get the value of the clicked element, you can do it like this:
$('submit').click(function(){
$(this).closest('input').find('.date').val();
$(this).closest('input').find('.site').val();
... });

ajax not returning to php index page

pleae note that i m trying jump to test.php page from index.php/html using ajax and mysql, simple if text-input not found in table so it should go to test.php else stay on index.php/html page with ajax alerts, but from index page everytime receiving NOT AVAILABLE and sometime submit button not functional, below code FYR...
//index.php $(document).ready(function() {
//default form not submitted
$("#submit").data("submitted",false);
//preventing enter key in input field from submitting form
$("#welcome").on("submit", function(e){
if($('#submit').data("submitted")===false) {
e.preventDefault();
}
});
//trigger form submission
$("#submit").on("click",function(){
validate();
});});
//default form not submitted
//$("#submit
function validate() {
var num = $('#invst_num').val();
$.ajax({
type: 'POST',
url: 'check_test.php',
data: num,
cache: false,
dataType: "json",
success: function(data) {
if(data){
alert("NOT AVAILABLE");
} else {
$("#submit").data("submitted", true);
$("#welcome").submit();
}
}}</script> <form action="check_test.php" method="post" name="welcome" id="welcome" /> <table width="550" border='0' align='center' cellpadding='0' cellspacing='0'> <tr>
<td align="center"><label>
Enter Inv. # *:
<input name="invst_num" type="text" id="invst_num" size="40" />
<input name="submit" type='submit' id='submit' /> </label></td> </tr></table> </form>
//check_test.php <?php
include ("config/config.php");
//get the username
if (isset($_POST['submit'])) {
$invst_num = $_POST['invst_num'];
//mysql query to select field username if it's equal to the username that we check '
$sql = mysql_query("select invst_num_ar from shareholders_ar where invst_num_ar = '$invst_num' ");
if ($result = mysql_num_rows($sql)>0) {
echo ($result);
}
}
?>
// if not found...test.php should load
<html>
<form
...
Register Data
/form>
</html>
Your conditional is backwards
if(data){
Should be
if(!data){
Or the alert should be flipped with the listener adding logic.
var num = $('#invst_num').val();
$.ajax({
type: 'POST',
url: 'check_test.php',
data: num,
ajax call is sending value frome data key, so you send only the text field content.
You probably should send sth like this:
$.ajax({
type: 'POST',
url: 'check_test.php',
data: { 'invst_num': num },
...
Open Dev tools in your browser and check what content is being sent during ajax call.

Get Ajax variable from the PHP foreach loops (part II)

Due to dianuj's great help I solved my Ajax looping issue yesterday.
Click here!
The solution helps me to send and get quantity variable (class="qty") every time I change the number in the input area.
Now I want to revise my Ajax and PHP loop a little bit to get the "total" variable (the quantity * the price).
I try to get the "price" variable by puting an "hidden" input area with price values.(please see the following script attached).The script get the variable of quantity (class="qty") and price (class="price") without problem.
However, when I put different quantity the script only picks the very first price and multiplies my changed quantity number.
For example, I have three items in the function with three differnt prices:
1. apple $1 x1
2. orange $10 x3
3. banana $2 x4
the script result will show $1 * (2+3+4) instead the correct $1*2+$10*3+$2*4
(the ajax script still gets the variable of price and quantity without problem).
My Ajax and PHP loops are as follows, it seems they can get and send the qty and price variable without problem (but only the fixed price of the very first item):
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseleave( function() {
//get qty value and price value from the loop
var totalVal =0;
$( ".qty" ).each(function() {
totalVal += ($(this).val()*$(".price").val());
});
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: {
//sent the total variable to php script (xml)
total : totalVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('total').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
</head>
<body>
<div id="display">
<form action="sessionCartUpdate.php">
<table width="780" border="0" align="center" cellpadding="4" cellspacing="0">
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td bgcolor="#CCCCCC" font color="black"><?php echo $_SESSION["psn"][$i];?></td>
<td bgcolor="#CCCCCC"><?php echo $_SESSION["pname"][$i];?></td>
<td bgcolor="#CCCCCC"><?php echo $_SESSION["price"][$i];?></td>
<td bgcolor="#CCCCCC"><input type="text" class="qty" name="qty[]" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<input type="hidden" class="price" value="<?php echo $_SESSION["price"][$i];?>" >
<td bgcolor="#CCCCCC"><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr><br />
<?php
}
?>
<tr><td colspan="5" align="center">the total:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div>
<div id="result2" class="box" style="height=350px;"></div></td></tr>
</table>
</form>
I also include my php script as follows serving as xml for the ajax script above:
<?php
// XML
header("Content-Type: text/xml");
header("Content-Type:text/html; charset=utf-8");
//get total value ("qty * price") from the ajax
$total = (isset($_POST["total"]) ) ? $_POST["total"] : $_GET["total"];
echo "<?xml version=\"1.0\" ?>";
echo "<caculation>";
echo "<total>" . $total . "</total>";
if ($total==0)
echo "<caution>"."please put number!"."</caution>";
else if ($total<=500)
echo "<caution>"."You should buy more!"."</caution>";
echo "";
echo "</caculation>";
?>
I would be very grateful you could offer invaluble advice to help me fix the above bug!
There is a problem the .each loop is for qty not for the price so it is picking the first price because the loop is for qty not for the price you should do something like this
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseleave( function() {
//get qty value and price value from the loop
var totalVal =0;
$( ".qty" ).each(function(i) {
totalVal += ($(this).val()*$(".price:eq("+i+")").val());
});
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: {
//sent the total variable to php script (xml)
total : totalVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('total').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
Use the index of .each loop and get the price placed at that index i have used the jquery selector :eq(index here) and i believe there will be price value for each quantity
I haven't confirmed the following code, but it should at least get you on the right track
var totalVal =0;
$('.qty').each(function() {
var price = $(this).closest('tr').find('.price').val();
totalVal += ($(this).val()*price);
});

issue when insert text to db using js

i try to submit text to db, but in the db field not inserted any text.
can you analyze where my false?
i try like this.
Thanks for your help.
<script type="text/javascript">
$(document).ready(function() {
$('#myForm').submit(function() {
var namaklasifier = document.getElementByName("tfklasifier").value;
var inputpos= document.getElementByName("tacaripos").value;
var inputnet = document.getElementByName("tacarinet").value;
var inputneg = document.getElementByName("tacarineg").value;
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
$('#resultcoba').html(data);}
})
return false;
});
})
</script>
<form id="myForm" method="post" action="proses.php">
<td align="center" valign="top" style="width:420px"><textarea style="width:420px" name="tacaripos" rows="4" cols="70"><?PHP echo htmlspecialchars($_POST['tacaripos']);?></textarea></td>
<td align="center" valign="top" style="width:420px"><textarea style="width:420px" name="tacarinet" rows="4" cols="70"><?PHP echo htmlspecialchars($_POST['tacarinet']);?></textarea></td>
<td align="center" valign="top" style="width:420px"><textarea style="width:420px" name="tacarineg" rows="4" cols="70"><?PHP echo htmlspecialchars($_POST['tacarineg']);?></textarea></td>
</tr>
<td align="center"><input type="submit" name="btklasifier" id="btklasifier" value="Buat" /></td></form>
proses.php
<?php
$namaklasifier=$_POST['namaklasifier'];
$jadipos=$_POST['inputpos'];
$jadinet=$_POST['inputnet'];
$jadineg=$_POST['inputneg'];
$link=mysqli_connect("localhost", "root", "","skripsi");
mysqli_select_db($link,"skripsi");
mysqli_query($link,"INSERT INTO namaklasifier(username,datapos,datanet,dataneg,user) VALUES('$namaklasifier','$jadipos','$jadinet','$jadineg','{$_SESSION['username']}')"); ?>
Thanks :)
You are trying to access the GET data under the variable names you have declared here:
var namaklasifier = document.getElementByName("tfklasifier").value;
var inputpos= document.getElementByName("tacaripos").value;
var inputnet = document.getElementByName("tacarinet").value;
var inputneg = document.getElementByName("tacarineg").value;
Yet you are sending them using $(this).serialize() which means you must access the GET variables using the input name as this is what serialize does (creates an object from the form elements using their names). e.g.
$jadipos=$_POST['tacaripos'];
$jadinet=$_POST['tacarinet'];
$jadineg=$_POST['tacarineg'];
Also you need to change $_GET to $_POST as that is the method you are using.
In proses.php, change the $_GET into $_POST.
Since you are using POST method to submit data, naturally, you have to use the $_POST variables.
They are POST values not the GET ones
$jadipos=$_POST['inputpos'];
$jadinet=$_POST['inputnet'];
$jadineg=$_POST['inputneg'];
And try to use mysqli_* functions or PDO statements,instead of mysql_* functions due to they are deprecated
EDIT:also try like
var namaklasifier = document.getElementByName("tfklasifier").value;
var inputpos= document.getElementByName("tacaripos").value;
var inputnet = document.getElementByName("tacarinet").value;
var inputneg = document.getElementByName("tacarineg").value;
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: {inputpos:inputpos,inputnet:inputnet,inputneg:inputneg},
success: function(data) {
$('#resultcoba').html(data);}
})
return false;
});

copy textfield value from one tabs to another tabs

i'm using jquery tabs..
i'm use tabs-1 as input form and tabs-2 as show input data...
i want after submit..all value inside textfield which have been type at tabs-1 can copy into textfield at tabs-2...
where part that i must modify?at form or at process page?what's code that can make it works?
<script type="text/javascript">
$(document).ready(function() {
$("#input").click(function() {
if($("#submit").valid()) {
var params=$("#submit").serialize();
$.ajax({
type:"post",
url:"process1.php",
data:params,
cache :false,
async :false,
success : function() {
that is for submitting form inside tabs-1...at tabs-2:
<tr>
<td width="100"><input type="text" id="showline" name="showline"<? echo "$_postVar('line')" ?>/></td>
<td width="100"><input type="text" id="showmodel" name="showmodel"<? echo "$_postVar('model')" ?>/></td>
<td width="100"><input type="text" id="showNIK" name="showNIK"<? echo "$_postVar('id')" ?>/></td>
</tr>
Well, if I understand this correctly, you can use the callback on the AJAX function to do that (so that the submitted info is only displayed if the request was successful):
[...]
success : function() {
$('#showline').val($('#faline').val());
$('#showmodel').val($('#modelnm').val());
$('#showNIK').val($('#NIK').val());
};
[...]
assuming that #faline, #modelnm and #NIK are the IDs of the input fields in the form from which the data is being submitted.
Also, in the HTML you don't need to echo anything anymore (which has incorrect syntax - it would be value="<? echo ... ?>" anyways) since the values will be added by jQuery.
Hope this helps !
$("#model").change(function() {
var barcode;
barCode=$("#model").val();
var data=barCode.split(" ");
$("#model").val(data[0]);
$("#serial").val(data[1]);
var str=data[0];
var matches=str.match(/[T|EE|EJU].*D/i);
$("#input").click(function() {
if($("#submit").valid()) {
var params=$("#submit").serialize();
$.ajax({
type:"post",
url:"process1.php",
data:params,
cache :false,
async :false,
success : function() {
$('#showline').val($('#line').val());
$('#showmodel').val($('#model').val());
$('#showNIK').val($('#id').val());
$("#model").val("");
$("#serial").val("");
$("#line").val("");
i put freekOne code before set .val("");

Categories