Help with modal window

Presumably where you are now alert()ing “Success”.

Well in your PHP script, you’re never setting $data['success'] = true, so in your JS the response.success check will always fail. Furthermore, you’re attempting to send the email even if the validation fails – so you should

  • echo the data at the very end of the script
  • set data['success'] = true after the mail got sent successfully
  • skip sending the mail if there were validation errors (the $_POST check won’t do here)

Thanks again for your replies.
I added your suggested changes and added this:

	if(empty($errors)) {
	//if($_POST) 
	//{

which prevents the Form from submitting and the email from sending, if, for example, the Name is left empty…Error! Much thanks. Now, upon submit/continue, the Form(jBox) should close to allow access to the page it is blocking.Yet, it doesn’t.

I was provided this feedback: “How does your response object look like in console.log(response);? It needs to be an object. And when the ajax call was successful it should contain {success: true}”. I don’t see anything in dev tools > Console when the Form shows an error on the web page, nor anything when the Form succeeds.

Any help with getting the jBox to close and show ‘success’ is greatly appreciated. Here’s the current code:

var myConfirm;

$(document).ready(function() {

  myConfirm = new jBox('Confirm', {
    content: $('.my-jbox-form'),
    width: 830,
    height: 205,
    cancelButton: 'Return Home',
    confirmButton: 'Continue',
    closeOnConfirm: false,
    closeOnEsc: false,
    confirm: function() {
      $.ajax({
      	url: 'https://..../submit.php',
        method: 'post',
        data: {
        	name: $('#name').val(),
        	email: $('#email').val()
        },
        success: function (response) {
		console.log(response);
    	if (response.success)
    	{
    	//close()
    	closeOnConfirm: true
       alert('Success')
        } else {
	alert('You have an Error');
	}
	}
      });
      return false;
    }.bind(this),
    cancel: function() {
      //disable(),
      window.location.href = "/index.html";
    }
  }).open();
});

and the php:

<?php
header('Content-type: application/json');
$errors         = array();  
$data           = array();  

    if (empty($_POST['name']))
        $errors['name'] = 'Name is required.';

    if (empty($_POST['email']))
        $errors['email'] = 'Email is required.';

    if ( ! empty($errors)) {

        $data['success'] = false;
        $data['errors']  = $errors;
    }
    echo json_encode($data);

	if(empty($errors)) {
	//if($_POST) 
	//{
	$to = 'chrisj....@hotmail.com';
	$subject = 'Thank You';
	$name = $_POST['name'];
	$email = $_POST['email'];
	$message = $_POST['message'];
	$message1 = $_POST['message'];
	$headers = $name;
	$headers = 'from: support@.....com';

	$message1 .= "\r\n\r\nName: ".$_POST['name']." \r\n Email: ".$_POST['email']." ";

	$message = "Hello {$_POST['name']}, ~ Thank you\r\n\r\n";

   		mail( $to, $subject, $message1, $headers );
   		mail( $email, $subject, $message, $headers );
$data[‘success’] = true;
echo json_encode($data);

   exit;
}
?>

Well may I ask again where exactly you got this feedback? It’s getting a bit confusing if you’re seeking advice on multiple boards or channels, and each time you post some code it has yet a couple of further modifications…

This is again not valid syntax, I already pointed that out earlier – you have to call myConfirm.close() here.

Thanks for your reply. Sorry for any confusion, the feedback was from the jBox author/developer (who doesn’t reply very often). Regarding postings, I find that in seeking help, you never know when or even if anyone will ever reply, so seeking help, googling/researching, etc. is an on-going process.

In regard to your reply about syntax, thank you. Being that the box didn’t close on the first try when I added it, I had tried something else. Now, I have it like so:

success: function (response) {
		console.log(response);
    	if (response.success)
    	{
    	myConfirm.close()
		alert('Success')
        } else {
	alert('You have an Error');
	}
	}

yet, everything remains the same, nothing shows in the Console, so I still am in search of the remedy of having the JBox/Form close upon submit/continue.

Any additional ideas are welcomed.

Okay, thanks for the information. I was just asking for the sake of transparency really – no offence!

As for your code, the JS looks right to me; the modal should close now, given that response.success is true. However in your PHP script you are now echoing the JSON twice, which will result in an invalid response… probably something like

[]{"success":true}

So just echo it once at the very end of the script, and remove the exit statement.

BTW the reason why you’ll sometimes get an array as JSON response and sometimes an object is that PHP gloriously doesn’t distinguish between lists and dictionaries; so json_decode() will treat $data as an array until you add a non-numeric key. Consider:

echo json_encode([]);            // []
echo json_encode(['foo' => 42]); // {"foo":42}

In order to avoid that confusion, either pass the JSON_FORCE_OBJECT flag…

echo json_encode([], JSON_FORCE_OBJECT); // {}

… or initialise $data with a key like so:

$data = ['success' => false];

Thanks for your reply and assistance.
It now successfully sends the Form info, shows ‘success’ and then closes the box. Much appreciated. Here’s what I have:

...
 //echo json_encode($data);
....
	$response['success'] = true;
	echo json_encode($response);
	$data = ['success' => false];
}
?>

However, now, anything entered and submitted(Continue) closes the Form, so, I’d like to add some additional validation of proper email entry. Not sure if I should start a new posting, but I tried adding this code, and it had no effect on the existing code:

		   if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
		      echo("$email is a valid email address");
		   }
		   else{
		      echo("$email is not a valid email address");
		   }

right after this existing line:

   if (empty($_POST['email']))
        $errors['email'] = 'Email is required.';

In fact, upon further testing, this existing code never displays these errors, when the Form is incomplete (or empty) upon Submit/Continue being selected:


if (empty($_POST['name']))
$errors['name'] = 'Name is required.'; 

if (empty($_POST['email']))
$errors['email'] = 'Email is required.';

The only message that appears is "Success!!', but that comes from the js ajax:

 confirm: function() {
      $.ajax({
      url: 'https://.../submit.php',
        method: 'post',
        data: {
        	name: $('#name').val(),
        	email: $('#email').val()
        },
        success: function (response) {
	console.log(response);
    	if (response.success)
    	{
    	myConfirm.close()
	alert('Success!!')

Any additional guidance with validating proper email is welcomed.
Thanks again

What’s the point in setting $data = ['success' => false] right after you echoed the JSON response though (and where is that $response variable coming from in the first place)?

Note that anything that you echo in addition to the JSON will invalidate the data, as for example

foo@bar.com is a valid email address{"success":true}

is not valid JSON, obviously; you should put those error messages in the JSON data, e.g. as a dedicated "errors" field.

I’m not sure what exactly is happening here, from the snippets you posted I can only tell that you’re not always responding with valid JSON, or setting some fields after you already wrote the JSON to the response body. But yes please start a new thread over in the PHP category for that, this is not really related to the modal logic any more but a more fundamental question about JSON responses and PHP form validation.

Thanks for your reply.
I added $data = [‘success’ => false], to the code upon your suggestion. I didn’t really understand your reply. Where would be a better place for it?

Regarding " put those error messages in the JSON data, e.g. as a dedicated "errors" field". Can you please share an example of what you’re describing?

Regarding “where is that $response variable coming from in the first place”, I believe it’s coming from the jBox js code, isn’t it?
Thanks again.

I suggested to initialise it like that, not reassign it afterwards (which would again defeat the whole purpose). You’re currently initialising $data with an empty array() in line 4 of your code from post #24; that’s where you’d initialise it with ['success' => false] instead. In case this is confusing you, note that the square brackets notation is just a shorthand for array(), so it would be the same as array('success' => false).

I was just trying to explain why you’ll sometimes get an array, sometimes an object as response. It’s a flaw in the language IMO.

Just like you already did in post #24

$data['errors'] = $errors;

// ... and eventually:
echo json_encode($data);

No. JS and PHP are different languages running at different times in different environments, and they don’t share any variables. In your JS, the response parameter will hold the data you’re echoing in your PHP script – it’s basically what you get when you just open your submit.php in the browser. jQuery will however try to parse the response appropriately, so if it’s valid JSON, you’ll get passed an object rather than just a JSON string. It doesn’t matter what the variable was called in the PHP script before you eventually json_encode() and echo it.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.