stop ajax from running n number of times - php

I don't know what happens there. [
Here you see the Edit buttonedit(pencil) in actions when i uopdate the record modal will open.
When you click on edit(pencil) button modal will be open.
When i update the record first time its working fine and ajax runs one time. when i again update the record ajax runs twice and again update the record ajax run thrice. every time when i update the record the ajax run incremented
Here is my code:-
Html code of Button
enter code here
<button type="button" class="btn btn-info btn-edit editService"><i class="fa fa-pencil" aria-hidden="true"></i></button>// this button in foreach loop
My Modal:-
enter code here
<div class="modal fade" id="myModal-edit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form id="subservicedata" role="form" method="POST" action="Javascript:;">
{{ csrf_field() }}
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="add-cat">Edit Service</h4>
</div>
<div class="modal-body">
<div class="form-group row">
<span class="col-xs-3 add-cate-model">Service</span>
<div class="col-xs-8">
<input name="name" id="sname" class="form-control txtfield m-tb-10" type="text" placeholder="Service" value="">
<input type="hidden" name="id" id="id" value="">
<input type="hidden" name="serviceid" id="service_id" value="">
<input type="hidden" name="listid" id="list_id" value="">
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary editSubService">Submit</button>
</div>
</form>
</div>
</div>
My Jquery Code:-
enter code here
$(document).on ('click','.editService',function(){
var tdid = $(this).parents().parents().attr('id');
var service = tdid.split('-');
var subserviceid = service[1];
alert(subserviceid);
$.ajax({
type : "POST",
url : "get-service",
data : { id: subserviceid },
dataType: 'json',
success:function(resp){
if($.trim(resp)){
$('#myModal-edit').modal('show');
$('#sname').val(resp.name);
$('#id').val(resp.id);
$('#service_id').val(resp.service_id);
$('#list_id').val(resp.list_id);
$(document).on('click','.editSubService',function(){
$.ajax({
type : "post",
url : "edit-sub-service",
data : $("#subservicedata").serialize(),
success:function(resp){
if($.trim(resp)){
alert(resp);
alert(subserviceid);
$('#tr-'+subserviceid+' #tdid-'+subserviceid).html(resp);
$('#myModal-edit').modal('hide');
}else{
alert("Error"); return false;
}
},
error:function(){
alert("Something Went Wrong!");
}
});
});
} else{
alert("Failed"); return false;
}
}
});
});
And My laravel 5.2 function
enter code here
public function getCategoryService(Request $request){
if($request->ajax()){
$data = $request->all();
$servicedata= DB::table("session_subservices")->where('id',$data['id'])->first();
echo json_encode($servicedata);die;
}
}
public function editCategoryService(Request $request){
if($request->ajax()){
$data = $request->all();
//echo "<pre>"; print_r($data); die;
SessionSubservice::where('id', $data['id'])->update(array('name' =>$data['name']));
echo $data['name']; die;
}
}

The problem is that you append a new event every time the button is clicked.
You need to remove the first event if you want to retain your approach.
Change this $(document).on ('click','.editSubService',function(){
to this:
$(document).off('click').on('click','.editSubService',function(){
Other aproach is to create a function in your js and set it to be called in the html.

The problem is the .editSubSerice click handler:
$(document).on('click','.editSubService',function(){
...
}
You are adding this click handler in the success function of your ajax call which is part of another click handler, so every time that ajax call / click handler executes, you add an additional click handler and that causes the code to execute multiple times.
You should move that click handler to after (or before...) your other click handler so that it only gets called / binds once.

Related

Bootstrap Modal won't POST all data with datepicker field using PHP

I have two elements of members data such as id and some other info in a modal which are hidden input elements inside my modal, I bind data from a anchor tag using javascript, example of data element in the anchor tag:
data-column="'.htmlspecialchars($column, ENT_QUOTES, 'utf-8').'"
Javascript example to bind into the modal:
$('#EnterExpiryModal').on('show.bs.modal', function (e) {
var memberID = $(e.relatedTarget).data('id');
$('#memID232').val(memberID);
var cola3 = $(e.relatedTarget).data('column');
$('#column3').val(cola3);
});
Having the relevant data for the members in question in my modal (modal code snippet below):
<div class="modal" id="EnterExpiryModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<div id="ExpiryError"></div>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Please enter document expiry date</h4>
<br>
<form class="form-horizontal" method="post" id="ExpiryDateForm">
<div class="form-group">
<input id ="memID232" name="memID232" class="form-control" type="hidden">
</div>
<div class="form-group">
<input id ="column3" name="column3" class="form-control" type="hidden">
</div>
<div class="form-group">
<label class="col-md-4 control-label">Date</label>
<div class="col-md-6 inputGroupContainer">
<div class="input-group">
<div class="clearfix">
<div id="date" data-placement="left" data-align="top" data-autoclose="true">
<input name="date" type="text" class="form-control hasDatepicker" placeholder="Choose Date">
</div>
</div>
</div>
</div>
</div>
<div class="middleme"><p><i class="fa fa-info-circle iwarner" aria-hidden="true"></i><small> These documents can be uploaded again at any time...</small></p></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" id="expirySubmit" name="expirySubmit" class="btn clocumsbtn">Confirm</button>
</div>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
The above code produces the below modal:
As you can see user is prompted to enter a expiry date in the form field and click confirm.
However the issue I am having is when I hit submit the form does submit, my jQuery validation does all the necessary checks before submitting using ajax, but my hidden input elements don't submit with the values as they should, they appear to be empty, but the datepicker (date) field is populated - I know the values populate with the required data I need.
Here's what the modal looks like without the elements being hidden:
Here is the validation:
$("#ExpiryDateForm").validate({
rules:
{
memID232: {
required: true,
minlength: 0
},
column3: {
required: true,
minlength: 0
},
date: {
required: true,
minlength: 3
}
},
messages:
{
memID232: "There's an error",
column3: "There's an error",
date: "Please enter the expiry date",
},
submitHandler: submitExpiryDate
});
here's the submit handler:
function submitExpiryDate() {
var data = $("#ExpiryDateForm").serialize();
$.ajax({
type : 'POST',
url : 'enterdocexpiry.php',
data : data,
beforeSend: function() {
$("#expirySubmit").html('<span class="fa fa-spinner"></span> please wait...');
},
success : function(responses) {
if(responses=="1"){
$('#ExpiryError').removeClass('animated shake');
$("#ExpiryError").fadeIn(1000, function(){
$('#ExpiryError').addClass('animated shake');
$("#ExpiryError").html('<div class="alert alert-danger"> <span class="fa fa-exclamation"></span> Sorry there was an error!</div>');
});
}
else if(responses=="updated"){
$("#ExpiryError").fadeIn(2000, function(){
$("#expirySubmit").html('<span class="fa fa-spinner"></span> updating...');
$("#ExpiryError").html("<div class='alert alert-success'><span class='fa fa-check-square-o'></span> Added Expiry Date!</div>");
setTimeout(function(){
window.location.href="manage_docs.php";
},2000);
});
}
else {
$("#ExpiryError").fadeIn(1000, function(){
$("#ExpiryError").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> '+data+' !</div>');
$("#expirySubmit").html('<span class="glyphicon glyphicon-log-in"></span> Some other error');
});
}
}
});
return false;
}
here the php:
require "database.php";
$memberID = $_POST['memID232'];
$column = $_POST['column3'];
$date = DateTime::createFromFormat('d/m/Y',$_POST['dates']);
$expiryDate = $date->format("Y-m-d");
$docploaded = "Yes";
if (isset($_POST['expirySubmit'])) {
if ($column == "passport") {
$statement = $conn->prepare('UPDATE memberdocs SET pexpiry=:expiryDate,puploaded=:docploaded WHERE m_id=:memberID');
$statement->bindParam(':expiryDate', $expiryDate);
$statement->bindParam(':docploaded', $docploaded);
$statement->bindParam(':memberID', $memberID);
$statement->execute();
if($statement->execute() ):
echo 'updated';
else:
echo "1";
endif;
}else if ($column == "crb") {
$statement = $conn->prepare('UPDATE memberdocs SET cvexpiry=:expiryDate WHERE m_id=:memberID');
$statement->bindParam(':expiryDate', $expiryDate);
$statement->bindParam(':memberID', $memberID);
$statement->execute();
if($statement->execute() ):
echo 'updated';
else:
echo "1";
endif;
}
}
Now I have done some troubleshooting and it seems the datepicker is the issue here. If I remove the datepicker (date) form field and replace it with a standard free text input field my form submits successfully with the memID232 input field and column3 input field populated, executing my php script, I've tried to be as clear as possible I hope the screenshots and snippets help, any advice?

Save button on profile picture module not working or module is getting stuck at "Uploading..." PHP

I have a module where a user can upload a profile picture. I want to do several things when a user uploads a picture to there profile, but I am trying to take it in steps, the first step being getting the picture saved and uploaded to the server. Right now, the user can select there picture just fine, after the user has chosen there picture, it gives a little notice that the picture is uploading. I don't know if something is supposed to show after uploading or if it is just supposed to go away (I joined a friend in getting this site done, the module was already here; I'm trying to get the functionality finished up and working).
This is what it looks like:
I have noticed though, that if you click save nothing seems to happen. Like the save button is not set up correctly or something.
I suspect that the the issue of the pictures not being uploaded is either because of the "Uploading..." text or the save button not working. I have tried to debug by echoing out if $_FILES is getting the picture that I am trying to upload, but the module does not reload to allow me to see if $_FILES is getting anything (it's not making it to the if loop of what happens after the save button has been clicked.
Here is the code for the module itself:
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
</div>
<div class="modal-body">
<center>
<h3>Edit Profile Picture</h3>
<img src="images/default.png" name="aboutme" width="140" height="140" border="0" class="img-circle"></a></br></br></br></br></br></br></br>
</center>
<div class="modal-body">
<form id="cropimage" method="post" enctype="multipart/form-data" action="upload_pic/change_pic.php">
<strong>Upload Image:</strong> <br><br>
<input type="file" name="profile-pic" id="profile-pic" />
<input type="hidden" name="hdn-profile-id" id="hdn-profile-id" value="1" />
<input type="hidden" name="hdn-x1-axis" id="hdn-x1-axis" value="" />
<input type="hidden" name="hdn-y1-axis" id="hdn-y1-axis" value="" />
<input type="hidden" name="hdn-x2-axis" value="" id="hdn-x2-axis" />
<input type="hidden" name="hdn-y2-axis" value="" id="hdn-y2-axis" />
<input type="hidden" name="hdn-thumb-width" id="hdn-thumb-width" value="" />
<input type="hidden" name="hdn-thumb-height" id="hdn-thumb-height" value="" />
<input type="hidden" name="action" value="" id="action" />
<input type="hidden" name="image_name" value="" id="image_name" />
<div id='preview-profile-pic'></div>
<div id="thumbs" style="padding:5px; width:600p"></div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="save_crop" class="btn btn-primary">Save</button>
</div>
</div></br>
<div class="container">
<div id="profile_pic_modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Upload Profile Picture</h3>
</div>
<div class="modal-body">
<form id="cropimage" method="post" enctype="multipart/form-data" action="upload_and_change.php">
<strong>Upload Image:</strong> <br><br>
<input type="file" name="profile-pic" id="profile-pic" />
<input type="hidden" name="hdn-profile-id" id="hdn-profile-id" value="1" />
<input type="hidden" name="hdn-x1-axis" id="hdn-x1-axis" value="" />
<input type="hidden" name="hdn-y1-axis" id="hdn-y1-axis" value="" />
<input type="hidden" name="hdn-x2-axis" value="" id="hdn-y2-axis" />
<input type="hidden" name="hdn-thumb-width" id="hdn-thumb-width" value="" />
<input type="hidden" name="hdn-thumb-height" id="hdn-thumb-height" value="" />
<input type="hidden" name="action" value="" id="action" />
<input type="hidden" name="image_name" value="" id="image_name" />
<div id='preview-profile-pic'></div>
<div id="thumbs" style="padding:5px; width:600p"></div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="save_crop" class="btn btn-primary" name="save">Save</button>
</div>
</div>
</div>
</div>
</div>
</br></br></br></br></br>
</div>
</div>
</div>
This is the function.js where I think the "Uploading..." is coming from:
jQuery(document).ready(function(){
/* When click on change profile pic */
jQuery('#change-profile-pic').on('click', function(e){
jQuery('#profile_pic_modal').modal({show:true});
});
jQuery('#profile-pic').on('change', function() {
jQuery("#preview-profile-pic").html('');
jQuery("#preview-profile-pic").html('Uploading....');
jQuery("#cropimage").ajaxForm(
{
target: '#preview-profile-pic',
success: function() {
jQuery('img#photo').imgAreaSelect({
aspectRatio: '1:1',
onSelectEnd: getSizes,
});
jQuery('#image_name').val(jQuery('#photo').attr('file-name'));
}
}).submit();
});
/* handle functionality when click crop button */
jQuery('#save_crop').on('click', function(e){
e.preventDefault();
params = {
targetUrl: '/upload_pic/change_pic.php?action=save',
action: 'save',
x_axis: jQuery('#hdn-x1-axis').val(),
y_axis : jQuery('#hdn-y1-axis').val(),
x2_axis: jQuery('#hdn-x2-axis').val(),
y2_axis : jQuery('#hdn-y2-axis').val(),
thumb_width : jQuery('#hdn-thumb-width').val(),
thumb_height:jQuery('#hdn-thumb-height').val()
};
saveCropImage(params);
});
/* Function to get images size */
function getSizes(img, obj){
var x_axis = obj.x1;
var x2_axis = obj.x2;
var y_axis = obj.y1;
var y2_axis = obj.y2;
var thumb_width = obj.width;
var thumb_height = obj.height;
if(thumb_width > 0) {
jQuery('#hdn-x1-axis').val(x_axis);
jQuery('#hdn-y1-axis').val(y_axis);
jQuery('#hdn-x2-axis').val(x2_axis);
jQuery('#hdn-y2-axis').val(y2_axis);
jQuery('#hdn-thumb-width').val(thumb_width);
jQuery('#hdn-thumb-height').val(thumb_height);
} else {
alert("Please select portion..!");
}
}
/* Function to save crop images */
function saveCropImage(params) {
jQuery.ajax({
url: params['targetUrl'],
cache: false,
dataType: "html",
data: {
action: params['action'],
id: jQuery('#hdn-profile-id').val(),
t: 'ajax',
w1:params['thumb_width'],
x1:params['x_axis'],
h1:params['thumb_height'],
y1:params['y_axis'],
x2:params['x2_axis'],
y2:params['y2_axis'],
image_name :jQuery('#image_name').val()
},
type: 'Post',
success: function (response) {
jQuery('#profile_pic_modal').modal('hide');
jQuery(".imgareaselect-border1,.imgareaselect-border2,.imgareaselect-border3,.imgareaselect-border4,.imgareaselect-border2,.imgareaselect-outer").css('display', 'none');
jQuery("#profile_picture").attr('src', response);
jQuery("#preview-profile-pic").html('');
jQuery("#profile-pic").val();
},
error: function (xhr, ajaxOptions, thrownError) {
alert('status Code:' + xhr.status + 'Error Message :' + thrownError);
}
});
}
});
I have attempted to comment out the line jQuery("#preview-profile-pic").html('Uploading....'); but that does not seem to remove the "Uploading..." text and the picture still does not upload.
If someone could help me figure out why the module is not working correctly, I would greatly appreciate it. If there is an easier way to get the functionality I am looking for, please let me know.
From my analysis, I did ran the code and found lots of more errors but the following are the key issues to address first.
Your code uses an assigned header file, as seen here ,that carries all the snippets for CDN jquery files. if you would have opened your console while its 'Uploading...' you would have noticed an error like one in this pic
First impression is that no jQuery.form.js file was found which is responsible for this function. If you go further and confirm that it is correctly loaded, Use this function here to check its loading:
(function() {
var startingTime = new Date().getTime();
// Load the script
var script = document.createElement("SCRIPT");
script.src = 'dist_files/jquery.form.js';
script.type = 'text/javascript';
document.getElementsByTagName("head")[0].appendChild(script);
// Poll for jQuery to come into existance
var checkReady = function(callback) {
if (window.jQuery) {
callback(jQuery);
}
else {
window.setTimeout(function() { checkReady(callback); }, 20);
}
};
// Start polling...
checkReady(function($) {
$(function() {
var endingTime = new Date().getTime();
var tookTime = endingTime - startingTime;
window.alert("jQuery.form is loaded, after " + tookTime + " milliseconds!");
});
});
})();
if you would use this function to check if its correctly loaded, after then, if it loads, your next victim is your jQuery, this is because of compatibility issues, the jQuery.form.js version used requires a jQuery of 1.5.x or higher.
Secondly,you have to check that you don't have any conflict with your imports, if in your project you used a version like
Assuming you had used jQuery in your other functions before the profile thing came in, which in this case came with its imports.
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
then definitely you'll not have jQuery functioning, meaning, jQuery will no work, and also, the same guy needs to call jQuery.form.js, now you see you'll come back to the same error. so harmonize your imports and delete any duplicates in .js imports and also .css files(although there is no css conflict currently but just for your info)
Once you clean the imports(I advise you use CDN if you are developing with good network connection) clear your browser caches and redo the upload with 'inspect element option in your browser' Do this:
Right click an empty space on browser
select 'inspect element'
switch in the inspector to 'Console' and you'll be able to see the errors if any.
your end result should work and get something of this sort:

Loading detail from database with ajax

I'm trying something very simple yet can't make it work and I have no idea why. I'm trying to load details on bootstrap modal windows from database so I can edit them. My button looks like
<button onclick="GetUserDetails('.$row['row_id'].')" class="btn btn-warning">Update</button>
Then this is the php part which should load the data
include("../../misc/database.inc.php");
error_reporting(E_ALL);
ini_set('display_errors', 1);
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['row_id']) && isset($_POST['row_id']) != "") {
$row_id = $_POST['row_id'];
$value = $pdo->prepare('SELECT row_id, row_content, row_email FROM excel_table WHERE row_id = ?');
$value->bindParam(1, $id, PDO::PARAM_INT);
$value->execute();
$response = array();
if($value->rowCount() > 0){
while ($rs = $value->fetch(PDO::FETCH_ASSOC)) {
$response = $row;
}
}
else
{
$response['status'] = 200;
$response['message'] = "Data not found!";
}
echo json_encode($response);
//var_dump($_POST['row_id']); // return correct id
}
On the console->Network I see correct response
{"row_id":"1","row_content":"asd","row_email":"sad"}
Here is js part which should load data
function GetUserDetails(row_id) {
$("#row_id").val(row_id);
$.post("ajax/readUserDetails.php", {
row_id: row_id
},
function (data, status) {
// PARSE json data
var excel_table = JSON.parse(data);
// Assing existing values to the modal popup fields
$("#row_content").val(excel_table.row_content);
$("#row_email").val(excel_table.row_email);
}
);
// Open modal popup
$("#update_user_modal").modal("show");
}
And this is my modal
<div class="modal fade" id="update_user_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Update</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="row_content">Desc</label>
<input type="text" id="row_content" placeholder="Описание" class="form-control"/>
</div>
<div class="form-group">
<label for="row_email">Email</label>
<input type="text" id="row_email" placeholder="Email" class="form-control"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" onclick="UpdateUserDetails()" >Save Changes</button>
<input type="hidden" id="row_id">
</div>
</div>
</div>
</div>
Can anyone tell me why modal isn't populated with data?
well my guess is you need to show the modal after the ajax asynchronous call end.
function GetUserDetails(row_id) {
$("#row_id").val(row_id);
$.post("ajax/readUserDetails.php", {
row_id: row_id
},
function (data, status) {
// PARSE json data
var excel_table = JSON.parse(data);
// Assing existing values to the modal popup fields
//add console.log to make sure you have some value
console.log('row_content: ' + excel_table.row_content);
$("#row_content").val(excel_table.row_content);
$("#row_email").val(excel_table.row_email);
// then add another to make sure you update it correctly.
console.log('#row_content: ' + $("#row_content").val());
// Open modal popup AFTER YOU UPDATE
$("#update_user_modal").modal("show");
}
);
}

Click executes the function only once

I have a form with a button whose id is calbtn. The form has two input fields whose ids are input1 and input2.
I want to check if the inputs are empty after I click callbtn. If the inputs are empty, then display the alert box (whose id is failurebox) else submit the form.
But this function is executed only once during its first time. When I click again callbtn does not execute the check function. If I leave either of my input1 or input2 empty for second time.
Please help me solve this problem. I am new to using jQuery. Please correct my below jquery code.
$(document).ready(function() {
$("#calbtn").on('click', function() {
if ($("#tempsp").val() == "" || $("#temppv").val() == "")
$("#failurebox").show();
});// end of click function
});
My HTML code is
<form id="newlayerform" role="form" method="post" class="form-horizontal" >
<div class="form-group">
<label for="tempsp" class="col-sm-4 control-label" style="color:red">Temp Set Point</label>
<div class="col-sm-8">
<div class="input-group">
<input type="number" class="form-control" name="tempsp" id="tempsp" placeholder="Enter Temp Set Point">
<div class="input-group-addon"><b>deg.Celcius</b></div>
</div><!--end of input group-->
</div>
</div>
<div class="form-group">
<label for="temppv" class="col-sm-4 control-label" style="color:red">Temp Process</label>
<div class="col-sm-8">
<div class="input-group">
<input type="number" class="form-control" name="temppv" id="temppv" placeholder="Enter Temp Process">
<div class="input-group-addon"><b>deg.Celcius</b></div>
</div><!--end of input group-->
</div>
</div>
<button type="button" class="btn btn-success btn-lg btn-block" id="calbtn" name="calbtn">Calculate</button>
</form>
<div id="failurebox" class="alert alert-warning" style="display:none">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
Failure
</div>
The form should not be submitted. Use return false; to stop form from submitting.
$(document).ready(function() {
$("#calbtn").on('click', function() {
if (!$.trim($("#input1").val()) || !$.trim($("#input2").val())) {
$("#failurebox").show();
} else {
$("#failurebox").hide();
}
}); // end of click function
});
Try this: jquery way of checking if an input is empty:
$(document).ready(function() {
$("#calbtn").on('click', function() {
if (!$("#input1").val() || !$("#input2").val()) {
$("#failurebox").show();
}
}); // end of click function
});
I think I've gotten it to work using this sqlfiddle
I did it like this:
$(document).ready(function() {
$("#calbtn").click(function() {
if (!$("#tempsp").val() || !$("#temppv").val())
{
$("#failurebox").show();
}
else{
$("#failurebox").hide();
}
});// end of click function
});
EDIT: my bad I made a slight mistake but fixed it now, should work now
I have got the problem solved.
The problem was in my alert box. I have used dismissible alert box with a close button. When I get the error for first time I was just closing my alert box which is preventing from getting the alert again when I do it for the second time.
The click function was working fine but the problem was due to the alert box.

Submitting form via POST with jQuery and Ajax

I am trying to POST data from a form using jQuery & Ajax. However, when I check on my PHP to see if the form has been "submitted", it shows it has not because the MySQL code does not run. I am guessing my HTML is not setup correctly and therefore the Ajax request is not sending the data to my post-update.php script. Here is my code:
<script type="text/javascript">
$(document).ready(function() {
$('#ajax-remove-completion-date').click(function() {
$.ajax({
type:'POST',
url:'post-update.php',
data: dataString,
success: function(response) {
$('#success-remove-completion-date').removeClass('hidden');
}
});
});
});
HTML:
<form action="">
<div id="myModal1" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel1" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h3 id="myModalLabel3">Remove Completion Date</h3>
</div>
<div class="modal-body">
<p>Are you sure you want to remove the students Completion Date?</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn blue" data-dismiss="modal" id="ajax-remove-completion-date">Yes</button>
<input type="hidden" name="submitted" value="remove-completion-date" />
</div>
</div>
</form>
PHP:
<?
session_id();
session_start();
require_once('assets/includes/mysql-connect.php');
/*Check to see if the completion date is being removed*/
if ($_POST['submitted'] == 'remove-completion-date') {
$query = "UPDATE students SET completion_date = NULL, completed = NULL WHERE student_id = {$_SESSION['student_id']} LIMIT 1";
$result = mysqli_query($dbc, $query);
}
?>
Where does dataString come from?
It's better if you define the data you want to send as an object. It's more readable and it's automatically converted to a query String.
$(document).ready(function() {
$('#ajax-remove-completion-date').click(function() {
$.ajax({
type:'POST',
url:'post-update.php',
data: {
submitted: 'remove-completion-date'
},
success: function(response) {
$('#success-remove-completion-date').removeClass('hidden');
}
});
});
});
If you want to take the value from the field, set submitted as:
$('input[name="submitted"]').val()

Categories