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();
}
Related
I'm tryng to set up a panel, this one
The menu on the top calls different ajax functions in order to display a thumb. Clicking on the thumb you can see the details in the last box of the panel.
I have this php functions
function GetPostPartner(){
$catPartner = "loop_pb_partner";
get_template_part($catPartner);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostPartner', 'GetPostPartner');
function GetPostEnte(){
$catEnte = "loop_pb_ente";
get_template_part($catEnte);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostEnte', 'GetPostEnte');
function GetPostColl(){
$catColl = "loop_pb_coll";
get_template_part($catColl);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostColl', 'GetPostColl');
function GetPostMedia(){
$catMedia = "loop_pb_media";
get_template_part($catMedia);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostMedia', 'GetPostMedia');
function GetPostDetails(){
$pb_details = $_POST['postURL'];
get_template_part($pb_details);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostDetails', 'GetPostDetails');
And those are called by these ajax functions
$(document).delegate('h4.homus-partners-global-ajax[data-pb- cat*=pb_partner]', 'click', function(event) {
event.preventDefault();
var pb_cat = "pb_partner";
var data = {
'action': 'GetPostPartner',
catURL : "loop_"+ pb_cat,
};
$.post(ajaxURL, data, function(response) {
$( 'ul.homus-partners-section-slide' ).html(response);
});
});
$(document).delegate('h4.homus-partners-global-ajax[data-pb-cat*=pb_ente]', 'click', function(event) {
event.preventDefault();
var pb_cat = "pb_ente";
var data = {
'action': 'GetPostEnte',
catURL : "loop_"+ pb_cat,
};
$.post(ajaxURL, data, function(response) {
$( 'ul.homus-partners-section-slide' ).html(response);
});
});
$(document).delegate('h4.homus-partners-global-ajax[data-pb-cat*=pb_coll]', 'click', function(event) {
event.preventDefault();
var pb_cat = "pb_coll";
var data = {
'action': 'GetPostColl',
catURL : "loop_"+ pb_cat,
};
$.post(ajaxURL, data, function(response) {
$( 'ul.homus-partners-section-slide' ).html(response);
});
});
$(document).delegate('h4.homus-partners-global-ajax[data-pb-cat*=pb_media]', 'click', function(event) {
event.preventDefault();
var pb_cat = "pb_media";
var data = {
'action': 'GetPostMedia',
catURL : "loop_"+ pb_cat,
};
$.post(ajaxURL, data, function(response) {
$( 'ul.homus-partners-section-slide' ).html(response);
});
});
$(document).delegate('li.homus-partners-section-single', 'click', function(event) {
event.preventDefault();
var pb_post_id = $(this).data('post-id');
var data = {
'action': 'GetPostDetails',
postURL : "single_pb_post_details",
post_id: pb_post_id
};
$.post(ajaxURL, data, function(response) {
$( '.homus-partners-detalis' ).html(response);
console.log(pb_post_id);
console.log(data.postURL);
console.log(response);
});
});
the response that I have is always 0 even if the console of the last ajax call here above return the right postid. You can find the whole project in this repo
https://github.com/wanbinkimoon/homus-web.git
in the code
function GetPostPartner(){
$catPartner = "loop_pb_partner";
get_template_part($catPartner);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostPartner', 'GetPostPartner');
instead of including the file by get_template_part paste the code here and then try
I have an issue in a Wordpress installation with a plugin. There is a calendar which you can click on a day (or a range of days) and from ajax calls through admin-ajax.php it calculates product costs.
The problem is that, when I click on a calendar cell, the admin-ajax.php is called twice. The first time for a few milliseconds and canceled immediately. Then automatically, it calls it once again and get the ajax response. When I click for a second time on a calendar cell, the admin-ajax.php is called 3 times. The first two are canceled and only the last one get a response.
I found that the code that is used for this part is the following. However, I cannot find any issue on it, even if I can see those cancelled calls on Developer console.
$('.wc-bookings-booking-form')
.on('change', 'input, select', function() {
var index = $('.wc-bookings-booking-form').index(this);
if ( xhr[index] ) {
xhr[index].abort();
}
$form = $(this).closest('form');
var required_fields = $form.find('input.required_for_calculation');
var filled = true;
$.each( required_fields, function( index, field ) {
var value = $(field).val();
if ( ! value ) {
filled = false;
}
});
if ( ! filled ) {
$form.find('.wc-bookings-booking-cost').hide();
return;
}
$form.find('.wc-bookings-booking-cost').block({message: null, overlayCSS: {background: '#fff', backgroundSize: '16px 16px', opacity: 0.6}}).show();
xhr[index] = $.ajax({
type: 'POST',
url: booking_form_params.ajax_url,
data: {
action: 'wc_bookings_calculate_costs',
form: $form.serialize()
},
success: function( code ) {
if ( code.charAt(0) !== '{' ) {
console.log( code );
code = '{' + code.split(/\{(.+)?/)[1];
}
result = $.parseJSON( code );
if ( result.result == 'ERROR' ) {
$form.find('.wc-bookings-booking-cost').html( result.html );
$form.find('.wc-bookings-booking-cost').unblock();
$form.find('.single_add_to_cart_button').addClass('disabled');
} else if ( result.result == 'SUCCESS' ) {
$form.find('.wc-bookings-booking-cost').html( result.html );
$form.find('.wc-bookings-booking-cost').unblock();
$form.find('.single_add_to_cart_button').removeClass('disabled');
} else {
$form.find('.wc-bookings-booking-cost').hide();
$form.find('.single_add_to_cart_button').addClass('disabled');
console.log( code );
}
},
error: function() {
$form.find('.wc-bookings-booking-cost').hide();
$form.find('.single_add_to_cart_button').addClass('disabled');
},
dataType: "html"
});
})
.each(function(){
var button = $(this).closest('form').find('.single_add_to_cart_button');
button.addClass('disabled');
});
And here is a screenshot from the Dev Console:
EDIT: I think I found the problem, but I am not sure. There is also this part of code which was supposed to not used at all. There is a feature for time on calendar, but it isn't activated. So, this code should not be run.
$('.wc-bookings-booking-form').on( 'date-selected', function() {
show_available_time_blocks( this );
});
var xhr;
function show_available_time_blocks( element ) {
var $form = $(element).closest('form');
var block_picker = $form.find('.block-picker');
var fieldset = $form.find('.wc_bookings_field_start_date');
var year = parseInt( fieldset.find( 'input.booking_date_year' ).val(), 10 );
var month = parseInt( fieldset.find( 'input.booking_date_month' ).val(), 10 );
var day = parseInt( fieldset.find( 'input.booking_date_day' ).val(), 10 );
if ( ! year || ! month || ! day ) {
return;
}
// clear blocks
block_picker.closest('div').find('input').val( '' ).change();
block_picker.closest('div').block({message: null, overlayCSS: {background: '#fff', backgroundSize: '16px 16px', opacity: 0.6}}).show();
// Get blocks via ajax
if ( xhr ) xhr.abort();
xhr = $.ajax({
type: 'POST',
url: booking_form_params.ajax_url,
data: {
action: 'wc_bookings_get_blocks',
form: $form.serialize()
},
success: function( code ) {
block_picker.html( code );
resize_blocks();
block_picker.closest('div').unblock();
},
dataType: "html"
});
}
I have the following function to commit the values to a mysql database. The php ajax call works fine. But after the insert function, it does not execute the code related to window.open where it should go to index.html page.
function sendval(){
var tosubmit = validateForm();
if(tosubmit){
showprog();
// now create the json string to insert in the database
var myData = {};
myData.EmpName=localStorage.getItem("username");
myData.LeaveType = $( "#leavetype option:selected" ).text();
myData.LeaveStart = $('#txtFromDate').val();
myData.LeaveEnd = $('#txtToDate').val();
myData.ContactNum = $('#contactnum').val();
myData.Comments = $('#Comments').val();
myData.UsrMail = localStorage.getItem("usermail");
myData.SupMail = localStorage.getItem("supmail");
myData.Status = 'Submit';
var myjson = JSON.stringify(myData);
$.ajaxSetup( { "async": false } );
$.ajax({
method: "POST",
url: "submitleave.php",
data: {"points": myjson}
})
.done(function( msg ) {
if(msg == 'Success') {
alert("Submission successful");
} else {
alert("Could not sumbit - try again");
}
$.ajaxSetup( { "async": true } );
window.open("index.html","_self");
});
} else {
alert("Please enter valid values before submitting the form");
}
}
I tried a few iterations but do not seem to get the error.
Some of the other functions do not work as well.
<header>XXXXX<br>
<br><input type="button" value="Logoff" id="logoff">
</header>
$('#logoff').click(function(){
localStorage.clear();
window.open("index.html","_self");
});
Regards,
I am using setInterval and then unable to clearInterval in my code. Please see the code
I am getting the value of complete and it is true and also entering the if statement but clearInterval still not working. I am tired and trying for last 10 hours but not find the bug. I checking the console.log and it is not stopping the interval.
jQuery(document).ready(function() {
var complete = false;
var Interval;
jQuery( "#form" ).submit(function() {
Interval = setInterval(get, 100);
post();
return false;
});
function post(){
var url = "my/url/here";
var data = {
'action': 'action/here',
'name': 'value'
};
jQuery.post(url, data, function(response) {
jQuery("#emails").html(response);
}).done(function() {
//alert( "second success" );
})
.fail(function() {
//alert( "error" );
})
.always(function() {
complete = true;
//alert( "finished" );
});
} // End post()
function get(){
var url = "url/goes/here";
if(complete == true){
clearInterval(Interval);
}
var data = {
'action': 'action/here',
};
jQuery.get(url, data, function(response) {
console.log(response);
jQuery("#progress").html(response);
});
} // End get()
});
here is the original code below. ajax call is working fine but clearInterval() not working
<script type="text/javascript" >
jQuery(document).ready(function() {
jQuery(".juee_emails_row").hide();
var juee_complete = false;
var juee_Interval;
jQuery( "#juee_form" ).submit(function() {
jQuery(".juee_emails_row").show();
juee_Interval = setInterval(juee_get, 100);
juee_post();
return false;
});
function juee_post(){
var data = {
'action': 'juee_get_emails',
'juee_data_option': jQuery('input[name=juee_data_option]:checked', '#juee_form').val()
};
jQuery.post(ajaxurl, data, function(response) {
jQuery("#juee_emails_td").html(response);
}).done(function() {
//alert( "second success" );
})
.fail(function() {
//alert( "error" );
})
.always(function() {
juee_complete = true;
//alert( "finished" );
});
} // End juee_post()
function juee_get(){
if(juee_complete == true){
clearInterval(juee_Interval);
}
var data = {
'action': 'juee_progress',
};
jQuery.get(ajaxurl, data, function(response) {
console.log(response + " email found");
jQuery("#juee_progress_td").html("");
jQuery("#juee_progress_td").html(response);
});
} // End juee_get()
});
</script>
i am new to cakephp and trying to send data from ajax to my controller action..
i have a popup model in which there is a input box ..i want to grab that value and send to controller without page refresh
here is my code ..
<a class="button anthracite-gradient" onclick="openPrompt()">submit </a>
my javascript
function openPrompt()
{
var cancelled = true;
$.modal.prompt('Please enter a value:', function(value)
{
$.ajax({
type:"POST",
url:"/cakephp/controller/action/",
success : function(data) {
alert(value); //value right now is in this variable ... i want to send this variable value to the controller
},
error : function() {
alert("false");
}
});
}, function()
{
});
};
</script>
myController
public function action(){
if( $this->request->is('ajax') ) {
$new = $this->request->data;
echo "ok"
return;
}
}
i want to first get the value here and then send the response to may ajax request
Its simple post the value to the controller and do what you want , in ajax request bind the value in data:{value_to_send:value} and get in controller
function openPrompt()
{
var cancelled = true;
$.modal.prompt('Please enter a value:', function(value)
{
$.ajax({
type:"POST",
data:{value_to_send:value},
url:"/cakephp/controller/action/",
success : function(data) {
alert(data);// will alert "ok"
},
error : function() {
alert("false");
}
});
}, function()
{
});
};
</script>
public function action(){
if( $this->request->is('ajax') ) {
// echo $_POST['value_to_send'];
echo $value = $this->request->data('value_to_send');
//or debug($this->request->data);
echo "ok"
die();
}
}
For more see accessing-post-data
I will give you some example. In my case, list out book list as a smart search while typing on text box.
$( ".selectBook" ).each(function(){
$(this).keyup(function( event ) {
var tri = $(this).val();
var oPrnt = $(this).parents('.smartsearch');
var str = '';
if(tri.length > 2){
$.ajax({
type: "POST",
url: "/utility/getbooks/",
data: JSON.stringify({string: tri, activeonly:false}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function(key, val) {
str += '<li id="a'+key+'" term="'+val+'" data-did="'+key+'">'+val+'</li>';
});
oPrnt.find("ul.result").html(str);
},
error: function (errormessage) {
oPrnt.find("ul.result").html('<li><b>No Results</b></li>');
}
});
oPrnt.find("ul.result").slideDown(100);
}
});
});
And in the controller, action (getbooks Action in UtilityController in my case)
public function getbooks($string = '', $activeonly = true){
$this->autoRender = false;
if( $this->request->is('ajax') ) {
$data = $this->request->input('json_decode');
$string = $data->string;
$activeonly = $data->activeonly;
}
$aReturn = array();
// ... fetch books data from DB goes here...
$aResult = $this->Book->fetch('list');
foreach($aResult as $r){
if(isset($r['bookname'])){
$aReturn[$r['id']] = $r['bookname'];
}
}
return json_encode($aReturn);
}