How to prevent execution of event handler? - php

I wish to authenticate a user each time they click a button. If the user is logged out, and they attempt to click on a button, they are redirected home.
However the code after validate() is executes before the user is redirected home. In this example the popup always displays before the user is directed back home. How do I wait for the execution of validate() to complete before the rest of the event handler attempts to execute?
$("#main-display").on('click', 'button', function (event){
validate();
hello = window.open( '', '', "height = 100, width = 100");
hello.document.write('hello');
});
function validate(){
$.ajax({
url: 'validate_user.php',
dataType: "json",
success: function(response) {
if(response.status == 'false') {
location.href = 'home.php';
}
}
});
}
validate_user.php
<?php
session_start();
if(!isset($_SESSION['userId'])){
session_destroy();
$response['status'] = 'false';
}
else {
$response['status'] = 'true';
}
echo json_encode($response);
?>
EDIT
Thanks for the answers, however the popup still displays before the user is directed back even with the code bits of the most upvoted answers.

You could run your code in the ajax callback instead of directly after you start the request. What the below does is set up your validate function to take a single function parameter. This function is called after the AJAX has been run.
You could even use else on line 14 to only run the code if they are valid users.
$("#main-display").on('click', 'button', function (event){
validate(function(){
//some code here
});
});
function validate(callback){
$.ajax({
url: 'validate_user.php',
dataType: "json",
success: function(response) {
if(response.status == 'false') {
location.href = 'home.php';
}
callback();
}
});
}
This is flexible as it allows validate to be used in different contexts.

Use jQuery's Deferred objects, which are encapsulated in each jqXHR. Looks like
function validate(){
return $.ajax({ // <-- new return statement
url: 'validate_user.php',
dataType: "json",
success: function(response) {
if(response.status == 'false') {
location.href = 'home.php';
}
}
});
}
..and after you returning that jqXHR, continue like:
$("#main-display").on('click', 'button', function (event){
validate().done(function() {
// this code gets executed after the request successfully finished
});
});
This is a very nice and convinient technique to work with asyncronous processes. You can also catch more cases, like .fail() for any error case.
Have a further read:
http://api.jquery.com/category/deferred-object/

Use a callback function at the end of your success handler:
$("#main-display").on('click', 'button', function (event){
validate(function() {
//code to execute after validate AJAX is complete
});
});
function validate(cb){
$.ajax({
url: 'validate_user.php',
dataType: "json",
success: function(response) {
if(response.status == 'false') {
location.href = 'home.php';
}
cb();
}
});
}
This will execute the callback function after the AJAX request is complete, without locking up the UI in the meantime.

What about that:
$("#main-display").on('click', 'button', function (event){
validate();
});
function validate(){
$.ajax({
url: 'validate_user.php',
dataType: "json",
success: function(response) {
if(response.status == 'false') {
location.href = 'home.php';
}else{
//some code here
}
}
});
}

You can use preventDefault:
$("#main-display").click(function(event) {
event.preventDefault();
// do the rest of the code
});

Use Synchronous AJAX request dude. By default it will be Asynchronous.
you can do this by adding one parameter..
async : false,

Related

Ajax function issue on return true and false in wordpress

I am validating a form with ajax and jquery in WordPress post comments textarea for regex. But there is an issue when i want to alert a error message with return false. Its working fine with invalid data and showing alert and is not submitting. But when i put valid data then form is not submit. May be issue with return false.
I tried making variable and store true & false and apply condition out the ajax success block but did not work for me.
Its working fine when i do it with core php, ajax, jquery but not working in WordPress .
Here is my ajax, jquery code.
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And i'm using wordpress wp_ajax hook.
And here is my php code.
<?php
function nmp_process_func (){
$comment = $_REQUEST['comment'];
preg_match_all("/(->|;|=|<|>|{|})/", $comment, $matches, PREG_SET_ORDER);
$count = 0;
foreach ($matches as $val) {
$count++;
}
echo $count;
wp_die();
}
?>
Thanks in advance.
Finally, I just figured it out by myself.
Just put async: false in ajax call. And now it is working fine. Plus create an empty variable and store Boolean values in it and then after ajax call return that variable.
Here is my previous code:
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And the issue that i resolved is,
New code
var returnval = false;
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
async: false, // Add this
data: 'action=nmp_process_ajax&comment=' + comment,
Why i use it
Async:False will hold the execution of rest code. Once you get response of ajax, only then, rest of the code will execute.
And Then simply store Boolean in variable like this ,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
returnval = false;
} else {
returnval = true;
}
}
});
// Prevent Default Submission Form
return returnval; });
That's it.
Thanks for the answers by the way.
Try doing a ajax call with a click event and if the fields are valid you submit the form:
jQuery(document).ready(function () {
jQuery("input[type=submit]").click(function (e) {
var form = $(this).closest('form');
e.preventDefault();
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: {'action':'nmp_process_ajax','comment':comment},
success: function (res) {
var count = parseInt(res);
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
} else {
form.submit();
}
}
});
});
});
note : you call need to call that function in php and return only the count!
Instead of submitting the form bind the submit button to a click event.
jQuery("input[type=submit]").on("click",function(){
//ajax call here
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}else{
jQuery("form").submit();
}
}
});
return false;
})
Plus also its a good idea to put return type to you ajax request.
Let me know if this works.

Send data from Javascript to PHP and use PHP's response as variable in JS

I have checked around, but can't seem to figure out how this is done.
I would like to send form data to PHP to have it processed and inserted into a database (this is working).
Then I would like to send a variable ($selected_moid) back from PHP to a JavaScript function (the same one if possible) so that it can be used again.
function submit_data() {
"use strict";
$.post('insert.php', $('#formName').formSerialize());
$.get('add_host.cgi?moid='.$selected_moid.');
}
Here is my latest attempt, but still getting errors:
PHP:
$get_moid = "
SELECT ID FROM nagios.view_all_monitored_objects
WHERE CoID='$company'
AND MoTypeID='$type'
AND MoName='$name'
AND DNS='$name.$selected_shortname.mon'
AND IP='$ip'
";
while($MonitoredObjectID = mysql_fetch_row($get_moid)){
//Sets MonitoredObjectID for added/edited device.
$Response = $MonitoredObjectID;
if ($logon_choice = '1') {
$Response = $Response'&'$logon_id;
$Response = $Response'&'$logon_pwd;
}
}
echo json_encode($response);
JS:
function submit_data(action, formName) {
"use strict";
$.ajax({
cache: false,
type: 'POST',
url: 'library/plugins/' + action + '.php',
data: $('#' + formName).serialize(),
success: function (response) {
// PROCESS DATA HERE
var resp = $.parseJSON(response);
$.get('/nagios/cgi-bin/add_host.cgi', {moid: resp });
alert('success!');
},
error: function (response) {
//PROCESS HERE FOR FAILURE
alert('failure 'response);
}
});
}
I am going out on a limb on this since your question is not 100% clear. First of all, Javascript AJAX calls are asynchronous, meaning both the $.get and $.post will be call almost simultaneously.
If you are trying to get the response from one and using it in a second call, then you need to nest them in the success function. Since you are using jQuery, take a look at their API to see the arguments your AJAX call can handle (http://api.jquery.com/jQuery.post/)
$.post('insert.php', $('#formName').formSerialize(),function(data){
$.get('add_host.cgi?moid='+data);
});
In your PHP script, after you have updated the database and everything, just echo the data want. Javascript will take the text and put it in the data variable in the success function.
You need to use a callback function to get the returned value.
function submit_data(action, formName) {
"use strict";
$.post('insert.php', $('#' + formName).formSerialize(), function (selected_moid) {
$.get('add_host.cgi', {moid: selected_moid });
});
}
$("ID OF THE SUBMIT BUTTON").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data: $("ID HERE OF THE FORM").serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
return false; //This stops the Button from Actually Preforming
});
Now for the Php
<?php
start_session(); <-- This will make it share the same Session Princables
//error check and soforth use $_POST[] to get everything
$Response = array('success'=>true, 'VAR'=>'DATA'); <--- Success
$Response = array('success'=>false, 'VAR'=>'DATA'); <--- fails
echo json_encode($Response);
?>
I forgot to Mention, this is using JavaScript/jQuery, and ajax to do this.
Example of this as a Function
Var Form_Data = THIS IS THE DATA OF THE FORM;
function YOUR FUNCTION HERE(VARS HERE) {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data:Form_Data.serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
}
Now you could use this as the Button Click which would also function :3

how to stop ajax request?

I have multiple ajax requests and when one of them can't get data I want , I re-send it until it can get data .
the problem that I can't stop it after it gets data . Is there's a break or something equivalent to it in ajax ?
I tried clearinterval but it didn't work
here's my functions :
function ajaxGetServerDatabase(Div,val,interval){
console.log(val);
dbs[val]=new Array();
$('#bck_action').val('get_DB');
$('#server_ip').val(val);
post_data = $('#'+Div+' *').serialize();
$.ajax({
type: "POST",
url: document.URL,
data: post_data,
dataType: "text",
success: function(response) {
if (response!='no_connection'){
dbs[val]=JSON.parse(response)
clearInterval(this.interval); // ????
}
}
});
return false;
}
function ajaxGetDatabase(Div,ips,interval){
$.each(ips,function(i,val){
dbs[val]=new Array();
$('#bck_action').val('get_DB');
$('#server_ip').val(val);
post_data = $('#'+Div+' *').serialize();
// console.log(post_data);
$.ajax({
type: "POST",
url: document.URL,
data: post_data,
dataType: "text",
success: function(response) {
if (response!='no_connection'){
dbs[val]=JSON.parse(response)
}
else
{
setInterval("ajaxGetServerDatabase('"+Div+"','"+val+"','"+interval+"')", interval);
}
}
});
});
return false;
}
I call it :
ajaxGetDatabase('tab_backup',ips,3000);
var timer = null;
function ajaxGetServerDatabase(Div,val,interval){
//...
if (response!='no_connection'){
dbs[val]=JSON.parse(response)
clearInterval(timer); // ????
}
//....
else
{
timer = setInterval("ajaxGetServerDatabase('"+Div+"','"+val+"','"+interval+"')", interval);
}
clearInterval has nothing to do with ajax. It's only a timer function which scope is to clear the timer set earlier with setInterval. If you really want to use a timer function you need either to attach a variable to the setInterval function, which you can clear with clearInterval setting as a parameter the id defined earlier in the setInterval.
var id = " ";
success: function(response) {
if (response!='no_connection'){
dbs[val]=JSON.parse(response)
clearInterval(id);
}
else
id= setInterval("ajaxGetServerDatabase('"+Div+"','"+val+"','"+interval+"')", interval);
}
Or you can abort the code with ajax abort.
Maybe something close to this?
...
var stopAjax = 0; //switch is on
if(stopAjax == 0){
$.ajax({
...
success: function(response) {
if (response!='no_connection'){
dbs[val]=JSON.parse(response);
stopAjax = 1; //switch is off
}
else{
setInterval("ajaxGetServerDatabase('"+Div+"','"+val+"','"+interval+"')", interval);
}
}
});
}
Are you looking for the timeout setting perhaps? eg
$.ajax({
timeout: 10000,
...
});
http://api.jquery.com/jQuery.ajax/
here's the answer :
in ajaxGetDatabase :
success: function(response) {
if (response!='no_connection'){
dbs[val]=JSON.parse(response)
}
else
{
id=setInterval("ajaxGetServerDatabase('"+Div+"','"+val+"')", interval);
}
in ajaxGetServerDatabase :
success: function(response) {
if (response!='no_connection'){
dbs[val]=JSON.parse(response)
clearInterval(id);
}
}
with out scope parameter
var id;
to make it general and work for more than one server had stopped (more than one ajax request is failed) I used an array to save ids like this :
var ids=new Array();
ids[val]=setInterval("ajaxGetServerDatabase('"+Div+"','"+val+"')", interval);
clearInterval(ids[val]);

Validate if website exists with AJAX

I'm trying to check if a website exists with an ajax call, but I'm not sure I am getting it right. On my page I grab a URL on click
$("#go").click(function() {
var url = $("#url").val();
$.ajax({
type: "POST",
url: "/ajax.php",
data: "url="+url,
success: function(){
$("#start").remove();
},
error: function(){
alert("Bad URL");
}
});
});
a=And then check on ajax.php
$url = $_POST['url'];
ini_set("default_socket_timeout","05");
set_time_limit(5);
$f=fopen($url,"r");
$r=fread($f,1000);
fclose($f);
if(strlen($r)>1) {
return true;
} else {
return false;
}
It seems I am getting SUCCESS no matter what... What am I missing?
It seems I am getting SUCCESS no matter what... What am I missing?
This is extremely pretty straightforward.
Because of this reasons:
// You have no idea what server respond is.
// that is you can't parse that respond
success: function(){
$("#start").remove();
}
Which should be
success: function(respond){
//you don't have to return TRUE in your php
//you have to echo this one instead
if ( respond == '1'){
$("#start").remove();
} else {
//handle non-true if you need so
}
}
In php replace this:
if(strlen($r)>1) {
return true;
} else {
return false;
}
to
if(strlen($r)>1) {
print true; //by the way, TRUE is a constant and it equals to == 1 (not ===)
}
Oh yeah, also don't forget to fix this as well:
data: "url="+url,
to data : {"url" : url}
As Nemoden said, you get a success message even if it returns false.
You need to check the data returned and then remove the element.
for example
$("#go").click(function() {
var url = $("#url").val();
$.ajax({
type: "POST",
url: "/ajax.php",
data: "url="+url,
success: function(response){
if (response == 'whatever you are returning') {
$("#start").remove();
}
},
error: function(){
alert("Bad URL");
}
});
});
Success callback is called whenever server-side script returned an answer (there were no connectivity errors or server-side errors). Is this answering your question?
See the difference:
$("#go").click(function() {
var url = $("#url").val(),
ajax_data = {url: url};
$.post({
"/ajax.php?cb=?",
ajax_data,
function(response){
if (response.status) {
// URL exists
}
else {
// URL not exists
}
$("#start").remove();
},
'json'
});
});
php back-end:
printf('%s(%s)', $_GET['cb'], json_encode(array('status' => (bool)$url_exists)));

jQuery function to check if an email address exists

I have a very limited jQuery experience and I was wondering if you can help me with a function that has to check, with an AJAX request, if an email address exists or not.
Until now I have this piece of code for email checking:
$('input#email').bind('blur', function () {
$.ajax({
url: 'ajax/email.php',
type: 'GET',
data: 'email=' + $('input#email').val(),
cache: false,
success: function (html) {
if (html == 1) alert('Email exists!');
}
});
});
How can I make a function out of this and use it like this:
if (!email_exists($('input#email').val())) {
$('#error_email').text('Email exists').show();
return false;
}
My PHP code looks like this:
$email = ($_GET['email']) ? $_GET['email'] : $_POST['email'];
$query = "SELECT `id` FROM `users` \n"."WHERE `users`.`email` = '".mysql_real_escape_string($email)."'";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
echo '1';
} else {
echo '0';
}
Thank you.
If you really must have an answer returned from the function synchronously, you can use a synchronous XMLHttpRequest instead of the normal asynchronous one (the ‘A’ in AJAX):
function email_exists(email) {
var result= null;
$.ajax({
url: 'ajax/email.php',
data: {email: email},
cache: false,
async: false, // boo!
success: function(data) {
result= data;
}
});
return result=='1';
}
However this is strongly discouraged as it will make the browser hang up whilst it is waiting for the answer, which is quite user-unfriendly.
(nb: also, pass an object to data to let jQuery cope with the formatting for you. Otherwise, you would need to do 'email='+encodeURIComponent(email) explicitly.)
You can't have a function that synchronously returns a value from an asynchronous action, or vice versa (you would need threads or co-routines to do that, and JavaScript has neither). Instead, embrace asynchronous programming and have the result returned to a passed-in callback:
$('#email').bind('change', function() {
check_email($('#email').val(), function(exists) {
if (exists)
$('#error_email').text('Email exists').show();
});
});
function check_email(email, callback) {
$.ajax({
url: 'ajax/email.php',
data: {email: email},
cache: false,
success: function(data) {
callback(data=='1');
}
});
}
You've already made it a "function" by attaching it to the blur event of your input. I would just
success: function(html) {
if (html == 1)
$('#error_email').text('Email exists').show();
else
$('#error_email').hide();
}

Categories