I am trying to debug a problem I have with submitHandler: function. What is happening, in firebug it is displaying the correct error message based on the true handle in the submitHandler. But, it is firing the success dialog and not the error dialog. I am fairly new to jquery and ajax so I have proably got some brackets or commas in the wrong place.
I would be grateful if someone could point out my error. Thanks
submitHandler: function() {
if ($("#USRboxint").valid() === true) {
var data = $("#USRboxint").serialize() + '&submit=true';
$.post('/domain/users/box.php', data, function(msgs) {
if (msgs.boxerror === true) {
var $dialog = $('<div id="dialog"></div>').html('<br /><b>Your New entry was NOT SUBMITTED.<br /><br />Thank you.</b>');
$dialog.dialog({
autoOpen: true,
modal: true,
title: 'New entry Unsuccessfull',
width: 400,
height: 200,
draggable: false,
resizable: false,
buttons: {
Close: function() {
$( this ).dialog( "close" );
}
}
});
}
else
var messageOutputs = '';
for (var i = 0; i<msgs.length; i++){
messageOutputs += msgs[i].box+' ';
}
$("#USRboxint").get(0).reset();
var $dialog = $('<div id="dialog"></div>').html('<br /><b>Your New entry was successfully submitted.<br /><br />Thank you.</b>');
$dialog.dialog({
autoOpen: true,
modal: true,
title: 'New entry successfull',
width: 400,
height: 200,
draggable: false,
resizable: false,
buttons: {
Close: function() {
$( this ).dialog( "close" );
}
}
});
//$("#frmreport").get(0).reset();
}, 'json');
}
},
success: function(msgs) {
}
PHP Code
<?php
$boxerrortext = 'No duplicates';
$array = split('[,]', $_POST['box_add']);
if (isset($_POST['submit'])) {
if ($box == 'DEMO111')
{
$error = array('boxerror'=>$boxerrortext);
$output = json_encode($error);
echo $output;
return;
}
else
$form = array();
foreach ($array as $box) {
// if (empty($box)) {
// $error = array('boxerrortext'=>$boxerrortext);
// $output = json_encode($error);
// echo $output;
// }
// else
// {
$form[] = array('dept'=>$dept,
'company'=>$company,
'address'=>$address,
'service'=>$service,
'box'=>$box,
'destroydate'=>$destroydate,
'authorised'=>$authorised,
'submit'=>$submit);
}
}
$result=json_encode($form);
echo $result;
?>
Creating dialogs each time is not efficient, better to initialize the dialogs on document ready:
$(function(){
$('<div id="dialog_error"></div>').html('<br /><b>Your New entry was NOT SUBMITTED.<br /><br />Thank you.</b>').dialog({
autoOpen: false,
modal: true,
title: 'New entry Unsuccessfull',
width: 400,
height: 200,
draggable: false,
resizable: false,
buttons: {
Close: function () {
$(this).dialog("close");
}
}
});
$('<div id="dialog_success"></div>').html('<br /><b>Your New entry was successfully submitted.<br /><br />Thank you.</b>').dialog({
autoOpen: false,
modal: true,
title: 'New entry successfull',
width: 400,
height: 200,
draggable: false,
resizable: false,
buttons: {
Close: function () {
$(this).dialog("close");
}
}
});
});
Then open them when you need them:
submitHandler: function () {
if ($("#USRboxint").valid() === true) {
var data = $("#USRboxint").serialize() + '&submit=true';
$.post('/domain/users/box.php', data, function (msgs) {
if (msgs.boxerror === true) {
$("#dialog_error").dialog("open");//Open error dialog
} else var messageOutputs = '';
for (var i = 0; i < msgs.length; i++) {
messageOutputs += msgs[i].box + ' ';
}
$("#USRboxint").get(0).reset();
$("#dialog_success").dialog("open");//Open success dialog
//$("#frmreport").get(0).reset();
}, 'json');
}
}
You should add braces around the code for the else-statement, or else only the first line is is part of the else block, and all the lines after it are executed no matter what.
Change this:
else
var messageOutputs = '';
To this:
else {
var messageOutputs = '';
// Other lines that belong in the else block.
}
I disagree with Wilmer, but you should properly clean up the dialog when it is closed. Since you create the div just to display the dialog once, you should remove it when the dialog is closed. You can do this by adding the following dialog option:
close: function() { $(this).dialog('destroy').remove(); },
Related
So I am making a checkbox for each row in my table so I can delete multiple rows at once.
I am trying to do this for each row inside my table:
<td><input id="checkItem" name="delete[]" type="checkbox" value="<?=$product->id;?>"></td>
Then delete[] is holding the array.
My issue is, I am using json (ajax) to parse my data.
It is only recognizing the last delete[] checkbox I have on my page.
If I check the last checkbox and hit delete all (my button to execute multi-selected rows), it shows the product id, this is good.
If I try any other checkbox, it returns nothing.
Here is the checkbox line that creates checkbox array for each row:
enter image description here
Here is the post function:
enter image description here
Here is my delete function:
enter image description here
Here is my json ajax code to process the requests:
$("body").on("submit", ".ajax-form", function (e) {
e.preventDefault();
form = $(this);
url = form.attr("action");
method = form.attr("method");
data = {};
form.find("[name]").each(function (key, value) {
type = $(this).attr("type");
name = $(this).attr("name");
if (type == "radio" || type == "checkbox") {
value = "";
if ($(this).prop("checked")) value = $(this).val();
} else value = $(this).val();
data[name] = value;
});
button_lang = $("[type=submit]", form).html();
var saveData = $.ajax({
type: method,
crossDomain: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
url: url,
data: data,
dataType: "json",
success: function(response) {
messages = "";
if(response.success === true)
{
if(response.redirect)
{
$('.ajax-form').trigger("reset");
window.location.href = response.redirect;
}
else if(response.success)
{
for (var message in response.messages) {
messages += response.messages[message] + "<br>";
}
if(response.timer) {
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
onOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
});
Toast.fire({
icon: 'success',
title: "<h6 style='text-align: left!important;'>" + messages + "</h6>"
});
$('.ajax-form').trigger("reset");
window.setTimeout(function(){window.location.href = response.sendTo;},response.timer);
} else {
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
onOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
});
Toast.fire({
icon: 'success',
title: "<h6 style='text-align: left!important;'>" + messages + "</h6>"
});
$('.ajax-form').trigger("reset");
}
}
else
{
location.reload();
}
}
else
{
for (var message in response.messages) {
messages += response.messages[message] + "<br>";
}
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
onOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
});
Toast.fire({
icon: 'error',
title: "<h6 style='text-align: left!important;'>" + messages + "</h6>"
});
}
}
});
saveData.fail(function() {
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
onOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
});
Toast.fire({
icon: 'error',
title: "<h6 style='text-align: left!important;'>A system error occured</h6>"
});
});
});
Try this. But #El_Vanja is right. Your code is highly room for improvement
form.find('input:checkbox').each(function (key, value) {
type = $(this).attr("type");
name = $(this).attr("name");
if (type == "radio" || type == "checkbox") {
value = "";
if ($(this).prop("checked")) value = $(this).val();
} else value = $(this).val();
data.push({name:value});
});
I am trying to validate part of a form, I am stuck on checking the database to see if a company name exists before submitting the form. This is a stripped down demo from the jquery ui modal from with the addition of checking if the company already exists. I am aware of SQL injection and am not doing anything about it just yet. At the moment the form won't submit as I'm missing something, I just don't know what yet.
Any help would be much appreciated.
This is what I have so far
The JS code:
$(function() {
var dialog, form,
company_name = $( "#company_name" ),
tips = $( ".validateTips" );
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkCompany( o, n ) {
$.ajax({
type: "POST",
url: "crud.php?act=check",
data: "&company_name=" + o.val(),
success: function(response){
if(response > 0){
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
})
}
function addUser() {
var valid = true;
valid = valid && checkCompany( company_name, "Company Name already exists." );
if ( valid ) {
$.ajax({
type: "POST",
url: "crud.php?act=create",
data: "&company_name=" + company_name.val(),
success: function(data){
}
});
dialog.dialog( "close" );
}
return valid;
}
dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 350,
width: 350,
modal: true,
buttons: {
"Create an account": addUser,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
allFields.removeClass( "ui-state-error" );
}
});
form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addUser();
});
$( "#create-user" ).button().on( "click", function() {
dialog.dialog( "open" );
});
});
The php side (crud.php):
include 'connection.php';
$action = $_GET['act'];
if(isset($_POST['company_name'])){
$company_name = $_POST['company_name'];
}
switch($action){
case 'create':
$q = "INSERT INTO company_info (company_name) VALUES
('".$company_name."')";
mysql_query($q);
break;
case 'check':
$result = mysql_query('SELECT company_name FROM company_info WHERE company_name = "'.$company_name.'"');
$num = mysql_num_rows($result);
echo $num;
break;
}
CheckCompany returns nothing. You are returning true or false from success but that goes nowhere.
You need an outer deferred so you can return something from your ajax success, back through checkcompany out to your call.
Basically, checkcompany is called and exits/returns normally. SOme time later, the success function runs but that is independent because it's async. It's not part of your checkcompanmy function.
Ideally, you should trigger an event on ajax success that your element subscribes to.
Examples from comment below:
checkCompany(o,n) {
var retval = false;
$.ajax({
sync : true,
success: function(data) {
retval = true;
}
});
return retval;
}
OR asynch:
checkCompany(o,n) {
$.ajax({
success: function(data) {
$("#ID").trigger('ajsuccess.company');
}
});
}
OR using returned promise:
if (valid) {
checkCompany().done(function() {
do the secondary ajax call in here
}
}
checkCompany(o,n) {
return $.ajax();
}
index.php
$(document).ready(function(){
$('a.bruker').click(function() {
var idx = $(this).attr('id');
$.ajax({
url:'bruker.php',
type:'POST',
data: 'id='+idx,
cache: false,
success:function(data) {
$('#bruker').html(data);
}
});
});
});
echo "<div id='bruker'></div>";
<a class='bruker' id='1'>name1</a>
<a class='bruker' id='2'>name2</a>
bruker.php
if(isset($_POST['id'])) {
echo "<script> $(function() {
$('.bruker-box').dialog({
autoOpen:true,
resizable: false,
closeOnEscape: true,
width:600,
height:500,
show: 'fade',
modal: true,
open: function(event, ui) { },
position: { my: 'center', at: 'center' }
})
$('#ui-id-2').css('border', 'none');
$('.ui-widget-overlay').click (function () {
$('.bruker-box').dialog( 'close' );
});
});</script>";
echo "<div class='bruker-box' title='(".$_POST['id'].")'>";
echo "example";
echo "</div>";
When i click out of the first box (name1) and click on name2 i want to get only the name 2 to come up, but the first box (name1) comming up first and than name2.
How can i get this right? Is there a way to reset somthing when i click on a new one?
This is happening because, every time an anchor is clicked, you are injecting a new div containing a dialog set to autoOpen. (Turn on Developer Tools F12 in Chrome and watch what happens.)
The autoOpen divs accumulate, redisplaying themselves with each change to the DOM.
To solve this, you can remove() the div after it displays. Change your bruker.php file to look like this:
Note the addition of a close: function in the dialog definition:
PHP:
if(isset($_POST['id'])) {
$out = "
<script>
$(function() {
$('.bruker-box').dialog({
autoOpen:true,
resizable: false,
closeOnEscape: true,
width:600,
height:500,
show: 'fade',
modal: true,
open: function(event, ui) { },
position: { my: 'center', at: 'center' },
close: function() {
$('div.ui-dialog').remove();
}
}); //END .dialog()
$('#ui-id-2').css('border', 'none');
$('.ui-widget-overlay').click (function () {
$('.bruker-box').dialog( 'close' );
});
}); //END document.ready
</script>";
$out .= "<div class='bruker-box' title='Name: (" .$_POST['id']. ")'>";
$out .= "example";
$out .= "</div>";
echo $out;
}
I created a div for preview with PHP and now I need to display it in Dialog Jquery,is it possible to pass directly php variable in Jquery?I tried but I have as results a blank dialog!!
Jquery side :
$(function() {
$( "#previewDiv" ).dialog({
autoOpen: false,
height: 200,
width: 700,
modal: true,
buttons: {
"Submit": function() {
$( this ).dialog( "close" );
$("#submit").click();
},
"Cancel": function() {
$( this ).dialog( "close" );
}
},
close: function() {
$('#').val("");
}
});
$( "#previewButton" ).click(function() { $( "#previewDiv" ).dialog( "open" ); });
});
And PHP :
$table=$_SESSION['data'];
if (isset($_POST['preview'])) {
if ($table) {
foreach($table as $keys=>$values) {
$pieces = explode(" , ",$values);
echo "<div id='previewDiv'>"
echo "$pieces[0]";
echo "$pieces[1]";
echo "</div>";
}
}
Thank you for your help!!!
I have created a calendar that saves to MySQL.
I have the allDay value set as false for time frame events but the calendar displays it as all day.
This gets the events..
$sql = mysql_query('SELECT * FROM `companies`.`calendar`');
${'Events'} = array();
while(${'Event'} = mysql_fetch_assoc($sql)){
${'Events'}[] = ${'Event'};
}
Snapshot of my table:
Here is my jQuery
$(document).ready(function() {
$('#eventToAdd').dialog({
autoOpen: false,
height: '300',
width: '550',
modal: true,
resizable: false,
position: 'center',
});
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
theme: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
loading: function(bool) {
if (bool) $('#loading').show();
else $('#loading').hide();
},
eventClick: function(calEvent, jsEvent, view) {
$('#eventTitle').val(calEvent.title);
$('#textColor').val(calEvent.textColor);
$('#backgroundColor').val(calEvent.color);
$("#eventToAdd").dialog({
autoOpen: true,
title: "Update Event",
modal: true,
buttons: [
{
text:"Update Event",
click: function () {
if($('#eventTitle').val()){
calEvent.title = $('#eventTitle').val();
calEvent.color = $('#backgroundColor').val();
calEvent.textColor = $('#textColor').val();
calendar.fullCalendar('updateEvent',calEvent);
$.post('post.api.php', { 'api': 'updateEvent', 'id': calEvent.id, 'title': calEvent.title, 'start': $.fullCalendar.formatDate(calEvent.start, 'yyyy-MM-dd h:mm:ss tt'), 'end': $.fullCalendar.formatDate(calEvent.end, 'yyyy-MM-dd h:mm:ss tt'), 'allDay': calEvent.allDay, 'bgColor': calEvent.color, 'textColor': calEvent.textColor }, function(resp) {
if(resp == 'SUCCESS') {
jAlert('The event has been updated','Updated');
} else {
jAlert('There was an error updating the event<br />Please try again later.<br />ERROR CODE: 728375', 'Process Error');
}
$('#eventToAdd').dialog('close');
});
}
}
},
{
text: "Cancel",
click: function() { $(this).dialog('close'); }
}]
});
},
selectable: true,
selectHelper: true,
select: function (start, end, allDay, jsEvent, view) {
$("#eventToAdd").dialog(
{
autoOpen: true,
title: "Create Event",
modal: true,
buttons: [
{
text:"Create Event",
click: function () {
if($('#eventTitle').val()){
calendar.fullCalendar('renderEvent',
{
title: $('#eventTitle').val(),
start: $.fullCalendar.formatDate(start, 'yyyy-MM-dd h:mm:ss tt'),
end: $.fullCalendar.formatDate(end, 'yyyy-MM-dd h:mm:ss tt'),
allDay: allDay,
textColor: $('#textColor').val(),
color: $('#backgroundColor').val()
},
true
);
var startDate = $.fullCalendar.formatDate(start, 'yyyy-MM-dd h:mm:ss tt');
var endDate = $.fullCalendar.formatDate(end, 'yyyy-MM-dd h:mm:ss tt');
$.post('post.api.php', { 'api': 'createEvent', 'title': $('#eventTitle').val(), 'start': startDate, 'end': endDate, 'allDay': allDay, 'textColor': $('#textColor').val(), 'bgColor': $('#backgroundColor').val() }, function(response) {
if(response == 'SUCCESS'){
jAlert('The event has been saved!','Event Created');
} else {
jAlert('There was an error saving your event<br />Please try again later or let JD know<br />ERROR CODE: 882293','Process Error');
}
});
}
$(this).dialog('close');
}
},
{
text: "Cancel",
click: function() { $(this).dialog('close'); }
}
],
close: function(){
$('#eventTitle').val('');
$('#textColor').val('');
$('#backgroundColor').val('');
}
});
},
editable: true,
events: <?= ${'Events'}; ?>
});
});
The record value should be returned as false (without quotes); not "false". I had the same problem and applied this simple solution:
// -----------------------
while ($row = mysql_fetch_assoc($sql)) {
// -----------------------
if ($row['event_allday'] = 'false') {
$allDayStatus = false;
}
// -----------------------
$eventsArray['id'] = $row['event_id'];
$eventsArray['title'] = $row['event_title'];
$eventsArray['start'] = $row['event_start'];
$eventsArray['end'] = $row['event_end'];
$eventsArray['url'] = $row['event_url'];
$eventsArray['allDay'] = $allDayStatus;
$eventsArray['className'] = $row['event_class'];
$eventsArray['admNotes'] = $row['event_adm_notes'];
// -----------------------