Jump to content
iwato

Return a Value Generated by the Success Function of an AJAX Call

Recommended Posts

BACKGROUND:  I have a javascript document that is dynamically loaded when a certain condition is met.  In this document there are two functions:  the first function is called submitForm(), and the second is called  resetForm().  Each of these functions is triggered separately by a different button on the same HTML webpage.  Both functions rely on the same PHP class, but each relies on data created by a different instance containing different data.  The first instance is created at run time and is ultimately read into the submitForm() function.  The second instance is created at the visitor's discretion via an AJAX call that is made when the resetForm() function is triggered. 

The success function of the AJAX call made by the resetForm()  function generates a value needed by the submitForm() function when it is run for a second time after the resetForm() function has already been called once.

QUESTION:  How do I get the resetForm() function to return a value generated by its AJAX call's success function in a manner that it can be used by the submitForm() function?

Sorry, no code, as the whole process is even a little more complicated than what has just been explained..

Please advise.

Roddy

 

Share this post


Link to post
Share on other sites

Have a global object or something where you can save properties or methods that should be usable by anything.

Share this post


Link to post
Share on other sites

That was my idea too, but I could not get it to work after two-and-one-half hours of experimentation.  I have decided to provide all of the code with the exception of the modified PHP class, and add the following comments. 

The submitForm() function works  well with each new page load.

The resetForm() function works well with each button click.

The submitForm() function fails to work after the resetForm() function has been activated.  In effect, the function cannot match the word-number phrase with the number that is entered by the visitor and the error message results.

Please skip to the dilemma for a quick technical understanding of the problem.

The CODE

//Create the first instance on page load and assign values.

require_once("./php/classes/class.imageless_captcha.php");
$captcha_s = new ImagelessCaptcha(3, false, false);
$captcha_sq = $captcha_s->formPhrase();
$captcha_sa = $captcha_s->getInt();

/*****************************************/
//Load the submitForm() and resetForm() functions.

<script src='./javascript/imageless_captcha.js'></script>

//The loaded functions.

function submitForm(confirmCode) {
	var visitorConfirmation = confirmCode;

	if (visitorConfirmation == captcha_sa) {
		alert('Send search info for further processing.');
		$('#captcha_success').css('display', 'block');
		$('#captcha_error').css('display', 'none');		
	} else {
		$('#captcha_error').css('display', 'block');		
		$('#captcha_success').css('display', 'none');
	}
}

function resetForm() {	
	$.ajax({
		type: "POST",
		url: './php/captcha_reset.php',
		data: {dataRequest: 'requestInstance'},
		statusCode: {
			404: function() {
			alert( "Page not found" );
		}},
		success: function(jsonData) {			
			jsonObj = JSON.parse(jsonData);
			$('#captcha_answer').val('');
			$('#captcha_question').html(jsonObj.captcha_rq);
			$('#captcha_success').css('display', 'none');
			$('#captcha_error').css('display', 'none');			
		}
	});
}

/*****************************************/

// Create a second instance of the ImagelessCaptcha class for the resetForm() function.
<?php
	ini_set('log_errors', 1);
	ini_set('error_log', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'error.log');
	ini_set('html_errors', 1);
	ini_set('display_errors', 0);
	if ($_SERVER['REQUEST_METHOD'] == 'POST') {
		$captcha_reset = array();
		if ($_POST['dataRequest']) {
			$dataRequest = filter_var($_POST['dataRequest'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
			if ($dataRequest == 'requestInstance') {
				require_once('./classes/class.imageless_captcha.php');
				$captcha_r = new ImagelessCaptcha(3, false, false);
				$captcha_reset['captcha_rq'] = $captcha_r->formPhrase();
				$captcha_reset['captcha_ra'] = $captcha_r->getInt();
			}		
		}
		echo json_encode($captcha_reset);
	}
?>

/******************************************/

A modified version of the ImagelessCaptcha class not included here.

/*****************************************/
//Embed the success and error messages.

<div id='captcha_error' style='display:none;'>
	<p>Error: The number that you entered was incorrect. Please try again.</p>
</div><!-- end div#captcha_error -->
<div id='captcha_success' style='display:none;'>
	<p>Congratulations! Your search request has been sent.</p>
</div><!-- end div#captcha_success -->

//Embed the captcha form

<form>
	<div id='captcha_messaging'>
		<label id='captcha_question'></label><br>
		<input id='captcha_answer' type="text" value="" >
	</div><!-- end div#captcha_messaging -->
	<div id='captcha_buttons'>
		<input id='captcha_submit' type='button'  style='width:100px;' value='submit'>
		<input id='captcha_reset' type='button'  style='width:100px;' value='reset'>
	</div>
</form>

/*****************************************/
// Assign the PHP outcomes to their Javascript counterparts.

<script>
	var captcha_sq = <?php echo "'" . $captcha_sq . "'"; ?>;
	var captcha_sa = Number(<?php echo $captcha_sa; ?>);
	$('#captcha_question').html(captcha_sq);
</script>

/*******************************************/
// Call the submitForm() and resetForm() functions

<script>
	$(document).ready(function() {
		$('#captcha_submit').on('click', function() {
			confirmCode = Number($('#captcha_answer').val());
			submitForm(confirmCode);	
		});
		$('#captcha_reset').on('click', function() {
			resetForm();
		});
	});
</script>

The DILEMMA

Replace the value of the captcha_sa variable in the submitForm() function with the value of newly generated captcha_ra variable generated by the resetForm() function.

function submitForm(confirmCode) {
  var visitorConfirmation = confirmCode;
  if (visitorConfirmation == captcha_sa) {...}
  ...
  }
}

Please advise.

Roddy

 

Edited by iwato
Better clarity.

Share this post


Link to post
Share on other sites

It looks like captcha_sa is already a global variable, so just set it with the new value.

  • Thanks 1

Share this post


Link to post
Share on other sites

It worked!

As is often the case, I am heartily embarrassed.

Sometimes I get so lost in the trees that I can no longer see the forest.

The new resetForm() function:

function resetForm() {	
	$.ajax({
		type: "POST",
		url: './php/captcha_reset.php',
		data: {dataRequest: 'requestInstance'},
		statusCode: {
			404: function() {
			alert( "Page not found" );
		}},
		success: function(jsonData) {			
			jsonObj = JSON.parse(jsonData);
			captcha_sa = jsonObj.captcha_ra;
			$('#captcha_answer').val('');
			$('#captcha_question').html(jsonObj.captcha_rq);
			$('#captcha_success').css('display', 'none');
			$('#captcha_error').css('display', 'none');			
		}
	});
}

Have a great day!

Roddy

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...