Make a submit button POST and AJAX call same time? - javascript

I have this form that will POST to show_aht2.php but I also want it to make the AJAX call that you see in my code below. So, how can I do both so the user doesn't go to the other? I want the user to stay on map.php
thanks in advance
map.php
<form action="show_aht2.php" method="post">
<input type="radio" name="date_selected" value="1d" checked="checked"/>1d
<input type="radio" name="date_selected" value="1w" />1w
<input type="radio" name="date_selected" value="1m" />1m
<input type="radio" name="date_selected" value="3m" />3m
<input type="submit" id="aht_btn" name="get_aht" value="Get AHT" />
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#aht_btn').click(function(){
$.ajax({
type:"GET",
url : "show_aht2.php",
data:{ } , // do I need to pass data if im GET ting?
dataType: 'json',
success : function(data){
//doing stuff
//get the MIN value from the array
var min = data.reduce(function(prev, curr) {
return isNaN(+curr['aht_value']) || prev < +curr['aht_value'] ? prev : +curr['aht_value'];
}, 1000000);
// alert("min:" + min); //return min for debug
//get the MAX value from the array
var max = data.reduce(function(prev, curr) {
return isNaN(+curr['aht_value']) || prev > +curr['aht_value'] ? prev : +curr['aht_value'];
}, -1000000);
//alert("max:" + max); //return max number for debug
//function for calculation of background color depending on aht_value
function conv(x){
return Math.floor((x - min) / (max - min) * 255);
}
//function for background color
//if NA then show white background, either show from green to red
function colorMe(v){
return v == 'NA' ? "#FFF" : "rgb(" + conv(v) + "," + (255-conv(v)) + ",0)";
}
//going through all DIVs only once with this loop
for(var i = 0; i < data.length; i++) { // loop over results
var divForResult = $('#desk_' + data[i]['station']); // look for div for this object
if(divForResult.length) { // if a div was found
divForResult.html(data[i]['aht_value']).css("background-color", colorMe(data[i]['aht_value']));
// alert("station " + data[i]['station'] + " <br>aht value" + data[i]['aht_value'] + "<br>timestamp:"+data[i]['ts_generated']);
}//end if
}//end for
}//end success
});//end ajax
});//end click
});//end rdy
</script>
show_aht2.php
if (isset($_POST['get_aht'])) {
if($_POST['date_selected'] == "1d" )//yesterdays result and using past 10 minute
{
$start_date = $one_day;
//$interval_value = "10 MINUTE";
//echo $start_date;
}
elseif($_POST['date_selected'] == "1w" )//1 week results
{
$start_date = $one_week;
//$interval_value = "7 DAY";
//echo $start_date;
}
elseif($_POST['date_selected'] == "1m" )//1 month results
{
$start_date = $one_month;
//$interval_value = "30 DAY";
//echo $start_date;
}
elseif($_POST['date_selected'] == "3m" )//3 month results
{
$start_date = $three_month;
//$interval_value = "90 DAY";
//echo $start_date;
}
}
/* what I expect from ther call back*/
$result = array();
foreach ($memo as $username => $memodata) {
if (in_array($username, array_keys($user))) {
// Match username against the keys of $user (the usernames)
$userdata = $user[$username];
//if AHT is null give N/A as value
if (is_null($memodata['aht_value'])) {
$result[] = array( 'username' => $userdata['username'],
'aht_value' => 'NA',
'station' => $userdata['station']//,
// "ts_generated" => $userdata['ts_generated']
);
}//end inner if
//else give the actual value of AHT without the decimals
else {
$result[] = array( 'username' => $userdata['username'],
'aht_value' => substr($memodata['aht_value'],0,-3),
'station' => $userdata['station']//,
// "ts_generated" => $userdata['ts_generated']
);
}//end else
}//end outer if
}//end for
echo json_encode($result);

do ajax call first, then submit form with .submit() later with callback of ajax.
<form action="show_aht2.php" method="post" id="formtopost">
<script type="text/javascript">
$(document).ready(function() {
$('#aht_btn').click(function() {
$.ajax({
type: "GET",
url: "show_aht2.php",
data: {}, // do I need to pass data if im GET ting?
dataType: 'json',
success: function(data) {
//doing stuff
//end success
},
always: function() {
//submit form !!!
$("#formtopost").submit();
}
}); //end ajax
}); //end click
}); //end rdy
</script>

Try :
<script type="text/javascript">
$(document).ready(function() {
$('#aht_btn').click(function(event){
event.preventDefault();
$.ajax({
type:"GET",
url : "show_aht2.php",
data:{ } , // do I need to pass data if im GET ting?
dataType: 'json',
success : function(data){
//doing stuff
}//end success
});//end ajax
});//end click
});//end rdy
</script>
Use method preventDefault : http://api.jquery.com/event.preventdefault/

You could submit the form with ajax rather than trying to do both at the same time
Something like this maybe?
<script type="text/javascript">
$(document).ready(function() {
$('#aht_btn').click(function(){
// This prevents the form from submitting
event.preventDefault();
// Capture form input
var $form = $(this);
var serializedData = $form.serialize();
// Run the ajax post
$.ajax({
url : "show_aht2.php",
type:"POST",
data: serializedData
success: function(response) {
// Do something
}
});
});//end click
});//end rdy
</script>

Related

Ajax passing value to PHP

I would like to pass multiple values to php via ajax (on same page), here's my code:
HTML (user_list.php):
<button type="submit" class="button button-block savebutton" name="save_changes"/>
Save changes</button>
Javascript (user_list.php):
$(".savebutton").on("click", function (event) {
event.preventDefault();
var js = [];
var i = 0;
$('select').each(function () {
var a = {"id": "", "permission": ""}
a.id = $(this).val();
a.permission = $(this).children(":selected").text();
js.push(a);
alert(js[i].permission + " - "+js[i].id);
i++;
});
$.ajax({
type: "POST",
url: "user_list.php",
data: {result: JSON.stringify(js)}
});
return false;
});
PHP (user_list.php):
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['delete_selected'])) { // Button to delete selected user(s)
if (!empty($_POST['check_list'])) {
foreach ($_POST['check_list'] as $id) {
$sql = "DELETE FROM users WHERE id=$id";
$mysqli->query($sql);
header("Refresh:0"); //Refresh page
}
}
}
// Other if above works fine
elseif (isset($_POST['result'])){
// I want to get the js array with the values here after ajax
}
else {
// But I get here, and I don't get the js array
}
}
So I have 2 problems, the first is that I pass the elseif, and the second is that I dont get the array. I think the problem is with ajax, since filling the array works properly
EDIT: I moved the php to a different page, now it's working.
Though your Ajax request is initiated, a "normal" submit request is also started, when you press the button. To prevent the second request (thus keeping only the Ajax request), you have to return false; at the end of your onclick callback.
Solution #1:
$(".savebutton").on("click", function () {
var js = [];
var i = 0;
$('select').each(function () {
var a = {"id": "", "permission": ""}
a.id = $(this).val();
a.permission = $(this).children(":selected").text();
js.push(a);
alert(js[i].permission + " - "+js[i].id);
i++;
});
$.ajax({
type: "POST",
url: "user_list.php",
data: {result: JSON.stringify(js)}
});
return false;
});
Solution #2 (as also suggested by #charlietfl):
$(".savebutton").on("click", function (event) {
event.preventDefault();
var js = [];
var i = 0;
$('select').each(function () {
var a = {"id": "", "permission": ""}
a.id = $(this).val();
a.permission = $(this).children(":selected").text();
js.push(a);
alert(js[i].permission + " - "+js[i].id);
i++;
});
$.ajax({
type: "POST",
url: "user_list.php",
data: {result: JSON.stringify(js)}
});
});
It seems that when you're submitting the POST request, the data is coming as their own POST fields. Simply check for the values of what you submitted. For example, if you had done the same, but put foo as bar and hello as world, you could check for foo and hello with something like this:
elseif (isset($_POST['foo'], $_POST['hello']) {
# your code
}
$('.savebutton').click(function (e) {
e.preventDefault()
var js = []
var i = 0
$('select').each(function (i) {
var a = {}
a.id = $(this).val()
a.permission = $(this).children(':selected').text()
js.push(a)
alert(js[i].permission + ' - ' + js[i].id)
})
js = JSON.stringify(js)
$.post('user_list.php', {result: js}
})
Try with this
<button type="submit" class="button button-block savebutton" name="save_changes[]"/>Save changes</button>

Form/button stop work after ajax partly reload page after form success

(If my english is bad I'm from pewdiepieland)
I have a problem that itch the hell out of me.
I have a page with a picture gallery. When logged in every picture gets a form where you can change the description or delete the picture. I also have a form where you can add a new picture to the gallery.
If I add a picture or delete/edit an existing one the part of the page where all of the pictures are shown reloads so that the new content is loaded. (since I don't want the whole page to reload and also wants to show a message about what happened, eg. "The picture was successfully uploaded/changed/deleted").
The problem is that the forms inside of the part which were reloaded stops working. I need to reload the whole page if I want to delete or edit another image. (The form for submitting a new picture still works, since it's outside of the "reloaded part of the page")
Do I have to reload the javascriptfile or anything else, or what do I need to do?
Do you guys need some parts of the code to check? It feels like I need to add something to my code to prevent this instead of changing the existing.. but hey what do I know...
Best Wishes and Merry Christmas!
UPDATE << with Simplyfied code:
HTML/PHP
<form id="addimg" role="form" method="POST" enctype="multipart/form-data">
<input type="file" name="img">
<input type="text" name="imgtxt">
<input type="submit" name="gallery-submit" value="Add Image">
</form>
<div id="gallery_content">
<?php
$result = mysqli_query($link, "SELECT * FROM gallery");
$count = 1;
while($row = mysqli_fetch_array($result)) {
$filename = $row['filename'];
$imgtxt = $row['imgtxt'];
$id = $row['id'];
echo '<div>';
echo '<img src="gallery/' . $filename . '">';
echo '<form id="editimg' . $count . '" role="form" method="POST">';
echo '<input type="text" name="imgtxt">';
echo '<input type="hidden" name="id">';
echo '<input type="submit" name="changeimgtxt" data-number="' . $count . '" value="Update" class="edit_img">';
echo '</form>';
echo '<button class="delete_img" value="' . $id . '">Delete</button>';
echo '</div>;
}
?>
</div>
JAVASCRIPT/JQUERY
$(document).ready(function() {
$('#addimg').submit(function(e) {
e.preventDefault();
gallery('add', '');
});
$('.edit_img').click(function(e) {
e.precentDefault();
var formNr = $(this).data('number');
var dataString = $('#editimg' + formNr).serialize();
gallery('edit', dataString)
});
$('.delete_img').click(function(e) {
e.preventDefault();
var imgid = $('this').value();
gallery('delete', imgid);
});
function gallery(a, b) {
if (a == 'add') {
var dataString = new FormData($('#addimg')[0]);
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'add_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
},
cache: false,
contentType: false,
processData: false
});
} else if (a == 'edit') {
var dataString = b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'edit_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
}
});
} else if (a == 'delete') {
var dataString = 'imgid=' + b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'delete_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content');
} else {
- Show fail message -
}
}
});
}
}
});
I don't think you need to see my process-file. Any clues?
Your problem is probably the .click function on add and delete image so change it to $('body').on('click', 'delete_img', function() {// do something});
See Here
Your problem is that you only hook up the .click() listeners once on "document ready".
When the $(document).ready() callback is executed the gallery has already been filled and you hook up click listeners on the elements that are currently in the DOM. When you reload the gallery it is no longer the same DOM elements and no click listeners are being set up on these ones. There are a multitude of ways you correct this, for example, jQuery .load() takes a complete callback in which you can set up the event listeners. Your sample adapted with this:
$(document).ready(function() {
var setupGalleryEventListeners = function () {
$('.edit_img').click(function(e) {
e.preventDefault();
var formNr = $(this).data('number');
var dataString = $('#editimg' + formNr).serialize();
gallery('edit', dataString)
});
$('.delete_img').click(function(e) {
e.preventDefault();
var imgid = $('this').value();
gallery('delete', imgid);
});
};
$('#addimg').submit(function(e) {
e.preventDefault();
gallery('add', '');
});
setupGalleryEventListeners(); // Setup initial event listeners on page load
function gallery(a, b) {
if (a == 'add') {
var dataString = new FormData($('#addimg')[0]);
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'add_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
},
cache: false,
contentType: false,
processData: false
});
} else if (a == 'edit') {
var dataString = b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'edit_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
}
});
} else if (a == 'delete') {
var dataString = 'imgid=' + b;
$.ajax({
type: "POST",
url: "gallery_process.php",
data: dataString,
success: function(text){
if(text == 'delete_success') {
- Show success message -
$('#gallery_content').load(document.URL + ' #gallery_content', setupGalleryEventListeners); // setupGalleryEventListeners called when load is done
} else {
- Show fail message -
}
}
});
}
}
});

Change text box value after deleting phpgrid row

I need to refresh the Sub Total div/text box value after deleting the row of phpgrid (phpgrid.org).
Before Delete:
After deleting the second row:
<div id="sub_total_div">
<input name="txtSubTotal" type="text" id="txtSubTotal" size="15" value="<?php
$sql=mysqli_query($connection,'select sum(amount) from sales_temp');
$row = mysqli_fetch_array($sql);
echo $row[0];
?>"/>
</div>
Please help me.
Edited code:
function submitdata() {
var listItemName = document.getElementById("listItemName").value;
var listStock = document.getElementById("listStock").value;
var txtUnitPrice = document.getElementById("txtUnitPrice").value;
var txtQuantity = document.getElementById("txtQuantity").value;
var listCustomer = document.getElementById("listCustomer").value;
var txtReceiptNo = document.getElementById("txtReceiptNo").value;
var TheDate = document.getElementById("TheDate").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = {listItemName:listItemName, listStock: listStock, txtUnitPrice: txtUnitPrice, txtQuantity: txtQuantity, listCustomer: listCustomer, txtReceiptNo: txtReceiptNo};
if (listItemName == '' || listStock == ''|| txtUnitPrice == ''|| txtQuantity == ''|| listCustomer == ''|| txtReceiptNo == ''|| TheDate == '') {
salesitemsAddFail();
}
else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "/pms/includes/functions/sales_temp_functions.php",
data: dataString,
cache: false,
success: function(html) {
//reload the sales datagrid once add the item details to temporary table (sales_temp)
$('#list').trigger("reloadGrid",[{page:1}]);
//window.location.reload();
//refresh/update the sub total value when adding
$("#sub_total_div").load(location.href + " #sub_total_div");
}
});
}
}
Create a new php file:
Gettotal.php
$sql=mysqli_query($connection,'select sum(amount) from sales_temp');
$row = mysqli_fetch_array($sql);
echo $row[0];
your js code will be:
submitdata() {
var listItemName = document.getElementById("listItemName").value;
var listStock = document.getElementById("listStock").value;
var txtUnitPrice = document.getElementById("txtUnitPrice").value;
var txtQuantity = document.getElementById("txtQuantity").value;
var listCustomer = document.getElementById("listCustomer").value;
var txtReceiptNo = document.getElementById("txtReceiptNo").value;
var TheDate = document.getElementById("TheDate").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = {listItemName:listItemName, listStock: listStock, txtUnitPrice: txtUnitPrice, txtQuantity: txtQuantity, listCustomer: listCustomer, txtReceiptNo: txtReceiptNo};
if (listItemName == '' || listStock == ''|| txtUnitPrice == ''|| txtQuantity == ''|| listCustomer == ''|| txtReceiptNo == ''|| TheDate == '') {
salesitemsAddFail();
}
else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "/pms/includes/functions/sales_temp_functions.php",
data: dataString,
cache: false,
success: function(html) {
//reload the sales datagrid once add the item details to temporary table (sales_temp)
$('#list').trigger("reloadGrid",[{page:1}]);
//Ajax call to get the sub
$("#sub_total_div").load("gettotal.php");
}
});
}
}
Note : This is not proper method to go with but in your case this will work
I found the solution, added the do_onload(id) to calculate the total on loadComplete event which is triggered after each refresh (also after delete)
function do_onload(id)
{
//alert('Simulating, data on load event')
var s = $("#list").jqGrid('getCol', 'amount', false, 'sum');
jQuery("#txtSubTotal").val(s);
}
And changed the phpgrid code accordingly.
$opt["loadComplete"] = "function(ids) { do_onload(ids); }";
$grid->set_options($opt);
I found the solution, added the do_onload(id) to calculate the total on loadComplete event which is triggered after each refresh (also after delete)
function do_onload(id)
{
//alert('Simulating, data on load event')
var s = $("#list").jqGrid('getCol', 'amount', false, 'sum');
jQuery("#txtSubTotal").val(s);
}
And changed the phpgrid code accordingly.
$opt["loadComplete"] = "function(ids) { do_onload(ids); }";
$grid->set_options($opt);

AJAX inside $.when giving fist character of the return string

I'm calling an AJAX using a $.when to wait till that ajax completes and return to process the next ajax inside.
This is where $.when calling happens:
function loadAllData(){
$.when(getCreditorID()).done(function(a1){
console.log("cx id is : " + parseFloat(a1[0])); //this is in the attached screen shot
var urlx = "functions/getCustomerData.php";
$.post(
urlx,
{
selectedValue: a1[0],
},
function(data) {
$("#payduedate").val(data[0].duedate);
document.getElementById('portcode').value = data[0].portcode;
document.getElementById('currencycode').value = data[0].currencycode;
document.getElementById('convertion').value = data[0].conversion;
},
"json"
);
});
}
Above code is calling below ajax method function:
function getCreditorID(){
id = "";
var creditorcodex = document.getElementById('creditorcode').value;
// console.log("getCreditorID input: " + creditorcodex);
var urlx = "functions/getCreditorID.php";
return $.ajax({
type: 'POST',
url: urlx,
data: {
creditorcode: creditorcodex,
},
success: function(data) {
console.log("Result : "+data); //this is in the attached screen
}
});
}
Above function calling getCreditorID.php to get data:
getCreditorID.php:
<?php
include '../config/dbConn.php';
$creditorcode = $_POST["creditorcode"];
// $creditorcode = $_GET["creditorcode"];
$result="";
$sql = "SELECT intCustomerID FROM lms.tblcustomers WHERE varCustomerName='".$creditorcode."';";
mysql_select_db('$dbname');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
$result=-999;
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$result=$row["intCustomerID"];
}
echo $result;
mysql_close($conn);
?>
Problem is:
If return from getCreditorID.php is '44' then console.log("Result : "+data); inside getCreditorID() function will output in console as 'Result : 44' and this is working fine. But the same function is getting returned in loadAllData() function and using the value returned for next ajax. Here if we print the return value using console.log("cx id is : " + parseFloat(a1[0])); output is '4' which should be '44'. Which means it's only giving the first character as output and ignoring the rest.
Screenshot of running console:
Please find a way out.
In your function loadAllData(), use a1 instead of a1[0] and update your code accordingly
function loadAllData(){
$.when(getCreditorID()).done(function(a1){
console.log("cx id is : " + parseFloat(a1)); // did correction here
var urlx = "functions/getCustomerData.php";
$.post(
urlx,
{
selectedValue: a1[0],
},
function(data) {
$("#payduedate").val(data[0].duedate);
document.getElementById('portcode').value = data[0].portcode;
document.getElementById('currencycode').value = data[0].currencycode;
document.getElementById('convertion').value = data[0].conversion;
},
"json"
);
});
}

javascript alert in an if else statement not triggering

If the first part of the statement fails I am trying to send an alert. But I cannot figure out why the alert is not triggering. Yes, I have forced the statement to fail.
$("#btnSubmit").click(function (e)
{
if (<?php echo $browser; ?> >= 1)
{
var user = $("#ownerPost input").val();
var oid = <?php echo $Owner; ?>;
$.ajax(
{
type: 'POST',
url: 'follow.php',
data: "oid="+oid,
dataType: 'json',
success: function(data)
{
var id = data[0];
var name = data[1];
$('#output2').html("<b>id: </b>"+id+"<b> name: </b>"+name);
}
}
);
$("#output").html("<b>You are now following: </b>" + user);
e.preventDefault();
}
else
{
alert("You must log in to follow");
}
}
);
Here is the output from view source:
The actual number is 56 and makes the statement true and that is correct. It is when the statement is false that it will not trigger the else and hence the alert.
If I place an alert right before the else it will show the alert because first part is true.
$("#btnSubmit").click(function (e)
{if (56 >= 1){
var user = $("#ownerPost input").val();
var oid = 56;
$.ajax({
type: 'POST',
url: 'follow.php',
data: "oid="+oid,
dataType: 'json',
success: function(data){
var id = data[0];
var name = data[1];
$('#output2').html("<b>id: </b>"+id+"<b> name: </b>"+name);} });
$("#output").html("<b>You are now following: </b>" + user);
e.preventDefault();
}else{alert("You must log in to follow");}});
I think you have a syntax error. I was going to suggest a try/catch, but that will not help with a syntax error. Please edit your question and put in the "view > page source" as the others have suggested. Also, can you use Firebug, or equivalent to view the console?
EDIT:
I do get the alert with this code. Note that I set browser to 0.
blah = function(e) {
if (0 >= 1) {
var user = $("#ownerPost input").val();
var oid = 56;
$.ajax({
type : 'POST',
url : 'follow.php',
data : "oid=" + oid,
dataType : 'json',
success : function(data) {
var id = data[0];
var name = data[1];
$('#output2')
.html("<b>id: </b>" + id + "<b> name: </b>" + name);
}
});
$("#output").html("<b>You are now following: </b>" + user);
e.preventDefault();
} else {
alert("You must log in to follow");
}
};
blah.call();

Categories

Resources