I have a simple form before:
<form method="post" action="firstbillsubmitbal.php?id=#COL1#">
<input name="currentbal" type="text" id="currentbal" class="input-mini" />
<input type="submit" id="submit" value="Save" class="btn btn-success" />
</form>
Which calls this page for processing firstbillsubmitbal.php
$dealID = $_GET["id"];
$currentbal = mysql_real_escape_string(stripslashes($_POST['currentbal']));
$sql = mysql_query("UPDATE deals SET
currentbal = '$currentbal',
currentbalDone = 'Yes'
WHERE deals.dealID = '$dealID'") or die (mysql_error());
It was working fine for single transactions. But I need to edit it a bit since I am displaying my data in a table now. I now have this js code when I click on a btn on my table per row, passes my row_id and currentbal calue, I got it working but I would like to know from this js code how do I process my form?
function funcEdit(row_id){
var currentbal = document.getElementById('currentbal' + row_id).value;
var r=confirm("Are You Sure You Want To Proceed?");
if(r==true) {
alert("Record is saved");
} else {
alert("Cancelling Transaction");
}
}
The js code has two variables only at the moment which is
row_id = this is basically the ID of the db row and
currentbal = which is the value I want to upload to my db
My question basically is how do I call my firstbillsubmitbal.php file and what/how do I edit on my php file so that my row_id and currentbal are uploaded on my db since I am no long using POST.
Thank you for the replies. So I went thru some SO answers and some tutorials I found on google and this is what happened to my js code.
function funcEdit(row_id){
var currentbal = document.getElementById('currentbal' + row_id).value;
var dealID = row_id;
//organize the data properly
var data = 'currentbal=' + currentbal.val() + '&dealID=' + dealID.val();
//start the ajax
$.ajax({
url: "firstbillsubmitbal.php",
type: "GET",
data: data,
cache: false,
success: function() {
$('#message').html("<h2>Current balance has been updated!</h2>")
}
});
}
And this is what happened to my firstbillsubmitbal.php page
$dealID = $_GET['dealID']
$currentbal = $_GET['currentbal']
$sql = mysql_query("UPDATE deals SET
currentbal = '$currentbal',
currentbalDone = 'Yes'
WHERE deals.dealID = '$dealID' LIMIT 1") or die (mysql_error());
But nothing happens when I click on the button to call my function. What am I missing?
Also, here is how I call my function. #COL1# is my row ID value.
Update
Are your function getting called correctly with row_id data ?
if so then might be this will give you a trick,
function funcEdit(row_id){
var currentbal = document.getElementById('currentbal' + row_id).value;
var dealID = row_id;
//start the ajax
$.ajax({
url: "firstbillsubmitbal.php",
type: "GET",
//pass data like this
data: {currentbal:currentbal.val(),dealID: dealID.val()},
cache: false,
success: function(data) {
if (data=="1")
$('#message').html("<h2>Current balance has been updated!</h2>")
}
});
}
and in php file
$dealID = $_GET['dealID']
$currentbal = $_GET['currentbal']
$sql = mysql_query("UPDATE deals SET
currentbal = '$currentbal',
currentbalDone = 'Yes'
WHERE deals.dealID = '$dealID' LIMIT 1") or die (mysql_error());
echo "1" ; // if update successful
else echo "0" // if update unsuccessful
HTML :
<form method="post" action="firstbillsubmitbal.php">
<input name="currentbal" type="text" id="currentbal" class="input-mini" />
Update
</form>
JS :
function funcEdit(row_id){
var currentbal = $("#currentbal").val();
//organize the data properly
var data = 'currentbal=' + currentbal + '&dealID=' + row_id;
//start the ajax
$.ajax({
url: "firstbillsubmitbal.php",
type: "GET",
data: data,
cache: false,
success: function() {
$('#message').html("<h2>Current balance has been updated!</h2>")
}
});
}
Hope it works for you!
Related
Trying to use AJAX to submit form data to a PHP file. Everything in the code seems to work except for a call to the PHP file.
I setup a Java Alert() on the PHP file and it never alerts.
I am sure it is an issue with the AJAX code but I don't know it well enough to figure out what is going wrong.
The AJAX Call:
$(document).on('click','.addItem',function(){
// Add Item To Merchant
var el = this;
var id = this.id;
var splitid = id.split("_");
// Add id's
var addid = splitid[1]; // Merchant ID
var additem = splitid[2]; // Item ID
// AJAX Request
$.ajax({
url: "jquery/addItem.php",
type: "POST",
data: { mid : addid , iit : additem },
success: function(response){
// Removing row from HTML Table
$(el).closest('tr').css('background','tomato');
$(el).closest('tr').fadeOut(300, function(){
$(this).remove();
});
}
});
});
The HTML Form Call Within a Table:
<span class='addItem' id='addItem_<?php echo $m; ?>_<?php echo $list['id']; ?>' >Add Item</span>
Ok Simple PHP code that it calls to with some alerts for testing:
<?php
require_once("../includes/constants.php");
require_once("../includes/functions.php");
$iid = filter_input(INPUT_POST, 'iit', FILTER_SANITIZE_STRING); // Item ID
$mid = filter_input(INPUT_POST, 'mid', FILTER_SANITIZE_STRING); // Merchant ID
$slot = 0;
$slot = getMerchSlot($mid);
?>
<script>
alert ("Slot Value: <?php echo $slot; ?>");
</script>
<?php
$result = $pdoConn->query("INSERT INTO merchantlist (merchantid, item, slot)
VALUES
('$mid', '$iid', '$slot') ");
if ($result) {
?>
<script>
alert("Looks like it worked");
</script>
<?php
}
echo 1;
?>
I would like some help with ajax. I would like to update a php file which will update a database. I have a form which send the selected check box to a php file which then updates the data base. I would like to do this with ajax but I am struggling with this. I know how to update <div> Html elements by ajax but cannot work this out.
HTML script
<html>
<head>
<script src="jquery-3.1.0.min.js"></script>
</head>
<body>
<form name="form">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<button onclick="myFunction()">Update</button>
</form>
<script>
function myFunction() {
var boiler = document.getElementByName("boiler").value;
var niamh = document.getElementByName("niamh").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'boiler=' + boiler + 'niamh=' + niamh;
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "updateDB.php",
data: dataString,
cache: false,
success: function() {
alert("ok");
}
});
}
</script>
</body>
</html>
PHP updateDB.php
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="14Odiham"; // Mysql password
$db_name="heating"; // Database name
$tbl_name = "test";
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$boiler = (isset($_GET['boiler'])) ? 1 : 0;
$niamh = (isset($_GET['niamh'])) ? 1 : 0;
// Insert data into mysql
$sql = "UPDATE $tbl_name SET boiler=$boiler WHERE id=1";
$result = mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
}
else {
echo "ERROR";
}
?>
<?php
//close connection
mysql_close();
header ('location: /ajax.php');
?>
I would like this to update with out refreshing the page.
I just want some suggestion and first your html page code should like-
<html>
<head>
<script src="jquery-3.1.0.min.js"></script>
</head>
<body>
<form name="form" id="form_id">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<button onclick="myFunction()">Update</button>
</form>
<script>
function myFunction() {
// it's like cumbersome while form becoming larger so comment following three lines
// var boiler = document.getElementByName("boiler").value;
// var niamh = document.getElementByName("niamh").value;
// Returns successful data submission message when the entered information is stored in database.
//var dataString = 'boiler=' + boiler + 'niamh=' + niamh;
// AJAX code to submit form.
$.ajax({
// instead of type use method
method: "POST",
url: "updateDB.php",
// instead dataString i just serialize the form like below this serialize function bind all data into a string so no need to worry about url endcoding
data: $('#form_id').serialize(),
cache: false,
success: function(responseText) {
// you can see the result here
console.log(responseText)
alert("ok");
}
});
}
</script>
</body>
</html>
Now i am turning to php code:
You used two line of code right in php
$boiler = (isset($_GET['boiler'])) ? 1 : 0;
$niamh = (isset($_GET['niamh'])) ? 1 : 0;
$_GET is used in get method and $_POST for post method, thus you are using post method in ajax and above line of code should be like
$boiler = (isset($_POST['boiler'])) ? 1 : 0;
$niamh = (isset($_POST['niamh'])) ? 1 : 0;
Update:
As well as fixing the dataString, stop the form from being submitted so that your function is used:
<form name="form" onsubmit="return false;">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<button onclick="myFunction()">Update</button>
</form>
The ajax call should handle returned data from updateDb.php.
Update the php file to send data back to the server, revert to $_POST instead of $_GET and remove the header call at the bottom:
if($result){
$data['success'=>true, 'result'=>$result];
} else {
$data['success'=>false];
}
echo json_encode($data);
// die(); // nothing needed after that
Update the ajax call to handle the response and fix your dataString with '&' between params (This is why you are not getting your params properly).
var dataString = 'boiler=' + boiler + '&niamh=' + niamh;
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "updateDB.php",
data: dataString,
cache: false,
success: function(data) {
var json = $.parseJSON(data);
if(json.success){
// update the page elements and do something with data.results
var results = data.results;
} else {
// alert("some error message")'
}
}
});
}
document.getElementByName not a javascript function, try document.getElementById() instead
You can do this
<form name="form" onsubmit="myfunction()">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<input type="submit" value="Update"/>
</form>
Javascript:
function myFunction() {
var boiler = document.getElementById("boiler").value;
var niamh = document.getElementById("niamh").value;
// Returns successful data submission message when the entered information is stored in database.
// i dont practice using url string in ajax data as it can be compromised with a quote (') string, instead i am using json
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "updateDB.php",
data: {
boiler: boiler,
niamh: niamh
},
cache: false,
}).done(function() {
alert('success');
}); // i do this because some jquery versions will deprecate the use of success callback
}
And you are getting to a post so change the $_GET in you php file to $_POST
This ajax code gets called, I tested it, but the database does not get updated.
I think the code is small enough not to need any further explanation. When something from the class pdb gets clicked, it saves its source to the database.
$(function(){
$('.pdb').on('click',function(){
var sou = $(this).attr('src');
var iddo = $(this).attr('id');
var data = 'id='+iddo+'&value='+sou+'&turno='+(bia)?true:false;
$.ajax({
data: data,
type: "post",
url: "database.php",
success: function(data){
alert("Prova: " + data);
}
});
});
});
database.php
<?php
mysql_connect("localhost","pierostesting","");
mysql_select_db("my_pierostesting");
$id=$_POST['id'];
$value =$_POST['value'];
$turno=$_POST['turno'];
if(true){
$sql="UPDATE board SET $id=$value, turno=$turno WHERE partita=0";
$result=mysql_query($sql);
if($result){
echo "Nailed it";
}
}else{
}
?>
remove
var data = 'id='+iddo+'&value='+sou+'&turno='+bia;
and debug ajax calls use either console or firebug extension
replace:
var data = 'id='+iddo+'&value='+sou+'&turno='+(bia)?true:false;
with
data = { 'id':iddo,'value':sou,'turno':(bia)?true:false}
Needed to change the PHPto this:
$sql="UPDATE board SET $id='$value', turno=$turno WHERE partita=0";
Simply change $value with '$value', bloody ''. Thank you all guys.
I use the following code to output a table with FAQ.
// get faq
global $wpdb;
$faq = $wpdb->get_results("SELECT ID, q, a, cat, quality, active FROM ce_faq");
foreach ($faq as $i) {
echo
'<div>
<a id="'.$i->ID.'" class="question" href="#">'.$i->q.'</a>
</div>
<div id="a'.$i->ID.'" class="answer">
<p>'.$i->a.'</p>
<form method="POST" id="form'.$i->ID.'">
<input type="hidden" value="'.$i->ID.'" name="faq_id"></input>
<input type="hidden" name="action" value="ce_faq_quality"/>'
.wp_nonce_field( 'name_of_my_action','name_of_nonce_field' ).
'<p><b> Was this answer usefull? <input type="radio" name="quality" value="1" class="quality_radio"> yes </input><input type="radio" name="quality" value="-1" class="quality_radio"> No </input> </b></p>
</form>
</div>';
}
echo '<div id="feedback">feedback</div>';
I use jQuery().slidetoggle to toggle the answers when somebody clicks on the question. I want to enable end-users to give feedback on the questions with a simple yes or no question. The form should be submitted when one of the radio buttons is selected. the trigger jQuery('.quality_radio').click is working and also the formid is correctly fetched.
problem: The function ce_faq_quality(); is unfortunately not responding, when i use console.log(qu) i get for example 'faq_id=1&action=ce_faq_quality&name_of_nonce_field=7dd1d930af&_wp_http_referer=%2Ffaq%2F&quality=1', which seems to be correct to me. I also get the alert 'this is working'. The php handler doesn't seem to work however. the div feedback turns 0 (instead of 'success php function') and also the query isn't performed (while I know it works for 120%). I am at a loss here...
solved: the handler wasn't accessible from the page i was working on...
jQuery('.question').click(
function(){
var id = this.id;
jQuery('#a'+id).slideToggle(350);
});
jQuery('.quality_radio').click(
function(){
var formid = jQuery(this).closest('form').attr('id');
var formid = '#'+formid;
jQuery(formid).submit(ajaxSubmit(formid));
});
function ajaxSubmit(formid){
var qu = jQuery(formid).serialize();
console.log(qu);
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: qu,
success:function(data){
jQuery("#feedback").html(data);
alert('this is working');
}
});
return false;
}
This is the php function i use to process the form.
add_action('wp_ajax_ce_faq_quality', 'ce_faq_quality');
add_action('wp_ajax_nopriv_ce_faq_quality', 'ce_faq_quality');
function ce_faq_quality(){
$quality = 1; //$_POST['quality'];
$faq_id = 1; //$_POST['faq_id'];
global $wpdb;
$wpdb->query($wpdb->prepare("UPDATE `ce_faq` SET `quality`= `quality` + $quality WHERE id = $faq_id"));
echo 'succes php function ';
die();
}
Your formid variable falls out of scope in the ajaxSubmit function. You should instead try:
jQuery('.quality_radio').click(
function() {
var formid = jQuery(this).closest('form').attr('id')
var formid = '#' + formid;
jQuery(formid).submit(ajaxSubmit(formid));
});
function ajaxSubmit(formId) {
var qu = jQuery(formid).serialize();
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: qu,
success: function(data) {
jQuery("#feedback").html(data);
}
});
return false;
}
So that you pass the formid to the ajaxSubmit function.
I am building a review system with php jquery and ajax. I have written the following code already for the 'Was this review helpful?' button:
<input type='button' value='Yes' onClick = 'myCall()'
style='background-color:#556B2F;color:white;padding:2px; cursor:pointer'
name='help' />
<input type='hidden' id='randomdirectory' value='$g' name='ids'/>
$g is the variable I assigned to the id of the review which is stored in a database. The ajax script is this:
<script>
function myCall() {
var ids = $('#randomdirectory').val();
var self = this;
$.ajax({
url: 'rev.php',
type: 'POST',
data: {ids: ids},
success: function(data) {
$('#ques1').hide();
}
});
}
and the code in the "rev.php" file is this:
<?php
include 'includes/db.php';
$q = $_POST['ids'];
if ($q != ""){
$result = mysql_query("SELECT * FROM table where id='$q'");
while($row = mysql_fetch_array($result))
{
$finalproduct = $row['numberofhelpfulvotes'];
$finalproduct1 = $finalproduct + 1;
}
mysql_query("UPDATE table SET numberofhelpfulvotes='$finalproduct1' WHERE id ='$q'");
}
?>
The problem is when I have multiple reviews on the page. When you click any of the "Yes" buttons on any of the reviews, the first review displayed gets the vote added to it, not the actual review where the button was clicked. Also when the button and text is hidden after the ajax call, the first review button and text is hidden, not the review where the button was clicked. Also a black line appears on the bottom of the page.
Any solutions to these problems will be greatly appreciated.
Thanks for all reply's. I ended up doing this which works perfectly for me:
<script>
$(function() {
$(".button").click(function() {
var ids = (this.id);
$.ajax({
url: 'rev.php',
type: 'POST',
data: {ids: ids},
success: function(data) {
$('.' + ids).hide();
}
});
});
});
</script>
and this as the html:
<div class='$g'><font size='2' color='black'>Was this review helpful?</font> <input type='submit' value='Yes' onClick = 'myCall()' style='background-color:#556B2F;color:white;padding:2px; cursor:pointer' name='help' id='$g' class='button' /><input type='hidden' id='randomdirectory' value='$g' name='ids'/>
The php stayed the same, but I am going to update it to make it more secure.