Help with validating web Form from ajax

  • (2 Pages)
  • +
  • 1
  • 2

28 Replies - 1526 Views - Last Post: 01 May 2020 - 12:44 PM Rate Topic: -----

#1 chrisjchrisj   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 141
  • Joined: 04-February 19

Help with validating web Form from ajax

Posted 21 April 2020 - 05:21 PM

I have this code and I am trying have validate the input from the web Form and corresponding .js

<?php
/* Makes it so we don't have to decode the json coming from javascript */
header('Content-type: application/json');

/* Grab decoded incomming data from Ajax */ 
$incomming  = $_POST['data'];

$data['outgoing'] = 'stop';

if ( $incomming === 'proceed') {

	$data['outgoing'] = "send"; 
}

if ( $data['outgoing'] === 'send') {
   output($data);
} else { 
   errorOutput('error');
}

/* Something went wrong, send error back to Ajax / Javascript */
function errorOutput($output, $code = 500) {
    http_response_code($code);
    echo json_encode($output);
}

/*
 * If everything validates OK then send success message to Ajax / Javascript
 */
function output($output) {
    http_response_code(200);
    echo json_encode($output);
}
if($_POST){
	$to = '[email protected]';
	$subject = 'Thank you for your info';
	$name = $_POST['name'];
	$email = $_POST['email'];
	$message = $_POST['message'];
	$message1 = $_POST['message'];
	$headers = $name;
	$headers = 'from: [email protected]';
	$message1 .= "\r\n\r\nName: ".$_POST['name']." \r\n Email: ".$_POST['email']." ";
	$message = "Hello {$_POST['name']}, ~ Thank you for your input\r\n\r\n";
   		mail( $to, $subject, $message1, $headers );
   		mail( $email, $subject, $message, $headers );
		header('Location: https://....');
   exit;
}
?>



The corresponding .js code (using jBox) is:

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) {
      alert('Success');
    } else {
      alert('Error');
    }
  }
});



Any guidance with validating the input and then sending some response back, will be appreciated.

Is This A Good Question/Topic? 0
  • +

Replies To: Help with validating web Form from ajax

#2 Splashsky   User is offline

  • D.I.C Addict
  • member icon

Reputation: 9
  • View blog
  • Posts: 565
  • Joined: 25-August 13

Re: Help with validating web Form from ajax

Posted 21 April 2020 - 05:25 PM

First, why wouldn't you decode the JSON upon receipt? I don't believe manually changing your header is best practice.

Aside, all you need to do is attach the success flag to your header when you return and that should do the trick.

I recommend giving Laravel a try, as all requests are wrapped up into neat objects, and sending responses is very intuitive.
Was This Post Helpful? 0
  • +
  • -

#3 chrisjchrisj   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 141
  • Joined: 04-February 19

Re: Help with validating web Form from ajax

Posted 21 April 2020 - 05:35 PM

Many thanks for your kind reply.

Regarding "why wouldn't you decode the JSON upon receipt", someone suggested that to me.
Do you recommend that I remove the header line?

In regard to "attach the success flag to your header when you return ... should do the trick",
thank you but I don't know how, could you please provide an example of what you've suggested?
I look forward to any additional assistance.
Was This Post Helpful? 0
  • +
  • -

#4 Splashsky   User is offline

  • D.I.C Addict
  • member icon

Reputation: 9
  • View blog
  • Posts: 565
  • Joined: 25-August 13

Re: Help with validating web Form from ajax

Posted 21 April 2020 - 05:37 PM

Upon rereading your code, it looks like you're already returning data there... switched from mobile, now it's much more clear. What does your console.log(response) show?
Was This Post Helpful? 0
  • +
  • -

#5 chrisjchrisj   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 141
  • Joined: 04-February 19

Re: Help with validating web Form from ajax

Posted 21 April 2020 - 09:29 PM

Thanks for your reply.

If by Console.log you mean dev tools > Console, then when I select 'Continue' I see this:

"Access to XMLHttpRequest https://www....../submit.php from origin https://www....../upload.html has been blocked by CORS Policy: No 'Access-Control-Allow-Origin' header is present on the resource".

And it also shows:

"POST https://www....../submit.php net:: ERR_FAILED"

Any assistance/remedy with theses errors is appreciated.

This post has been edited by chrisjchrisj: 21 April 2020 - 09:31 PM

Was This Post Helpful? 0
  • +
  • -

#6 Ornstein   User is offline

  • D.I.C Head

Reputation: 105
  • View blog
  • Posts: 216
  • Joined: 13-May 15

Re: Help with validating web Form from ajax

Posted 22 April 2020 - 02:22 AM

Sending a Content-Type header with the appropriate MIME type is legit. It might all be neater if you used a framework, but here we are. :P

jQuery's ajax method will itself decode the response as JSON if 1) you tell it to do so (using the dataType option) or 2) it detects a JSON MIME type.

I feel like the error message you posted has already told you everything you need to know. Looks like you're being stung by CORS - so you'll want to read up on what that is and what headers you need to send in your response.

That aside, I'm a bit unsure about the logic in your PHP. In the conditional at the end there, you... do a HTTP redirect? I can't imagine why you'd want to do this from an endpoint that has already output a response.
Was This Post Helpful? 0
  • +
  • -

#7 chrisjchrisj   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 141
  • Joined: 04-February 19

Re: Help with validating web Form from ajax

Posted 22 April 2020 - 05:17 PM

Thanks for your replies.
After resolving those erros I now only see this error in the Console:


jquery.min.js:6 POST https://web-site-name/submit.php 500



Any additional assistance with resolving this error is appreciated
Was This Post Helpful? 0
  • +
  • -

#8 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2760
  • View blog
  • Posts: 8,066
  • Joined: 15-January 14

Re: Help with validating web Form from ajax

Posted 22 April 2020 - 05:32 PM

A 500 response means there's a PHP error. If PHP is printing error message in the browser, use your browser's developer tools to look at that ajax request and look at the response for the error message. If PHP is using an error log, check there.
Was This Post Helpful? 0
  • +
  • -

#9 chrisjchrisj   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 141
  • Joined: 04-February 19

Re: Help with validating web Form from ajax

Posted 22 April 2020 - 10:05 PM

Thanks for your reply.

I don't know how to "look at the response for the error message",
but, I have gone to dev tools > Network > XHR and I see
Name: submit.php
Type: XHR
Initiator:jquery.min.js:4

And when I hover over jquery.min.js:4 I see:

send @ jquery.min.js:4
ajax @ jquery.min.js:4
(anonymous) @ upload.html:122
(anonymous) @ jBox.all.min.js:1
dispatch @ jquery-3.5.0.js:5429

elemData.handle @ jquery-3.5.0.js:5233

Does any of this help you to help me resolve the 500 error?
Any guidance is appreciated.

This post has been edited by chrisjchrisj: 23 April 2020 - 07:15 AM

Was This Post Helpful? 0
  • +
  • -

#10 chrisjchrisj   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 141
  • Joined: 04-February 19

Re: Help with validating web Form from ajax

Posted 23 April 2020 - 10:02 AM

I have removed the code that I believe was causing the error and am now asking for help code for validating the input from the web Form and then sending some response back, here's the current php:

<?php
if($_POST){
	$to = '[email protected]';
	$subject = 'Thank you for your info';
	$name = $_POST['name'];
	$email = $_POST['email'];
	$message = $_POST['message'];
	$message1 = $_POST['message'];
	$headers = $name;
	$headers = 'from: [email protected]';
	$message1 .= "\r\n\r\nName: ".$_POST['name']." \r\n Email: ".$_POST['email']." ";
	$message = "Hello {$_POST['name']}, ~ Thank you for your input\r\n\r\n";
   		mail( $to, $subject, $message1, $headers );
   		mail( $email, $subject, $message, $headers );
		header('Location: https://....');
   exit;
}
?>


and here is the corresponding js:


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) {
      alert('Success');
    } else {
      alert('Error');
    }
  }
});


Any assistance/guidance is appreciated
Was This Post Helpful? 0
  • +
  • -

#11 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2760
  • View blog
  • Posts: 8,066
  • Joined: 15-January 14

Re: Help with validating web Form from ajax

Posted 23 April 2020 - 10:44 AM

If you click on the request on the network tab you'll be able to see the response. If you don't know how to use the developer tools for your browser, look up documentation about them.

I don't know what you need help with in that code. You don't know how to validate data? One issue is your header format. Headers should be capitalized, and for some reason you set $headers on line 9 and then overwrite it on line 10. You also don't need to save the same message in more than one variable.
Was This Post Helpful? 0
  • +
  • -

#12 chrisjchrisj   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 141
  • Joined: 04-February 19

Re: Help with validating web Form from ajax

Posted 24 April 2020 - 09:47 PM

Thanks for your replies.
The goal it to close the jBox upon success and not close it upon Error. Which I believe needs validation from the submit.php to successfully close the Form/Jbox.
I attempted adding this call back validation code ( everything above if($_POST) ) in the submit.php file, without success:

<?php
$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($_POST){
	$to = '[email protected]';
	$subject = 'Thank You';
	$name = $_POST['name'];
	$email = $_POST['email'];
	$message = $_POST['message'];
	$message1 = $_POST['message'];
	$headers = $name;
	$headers = 'from: [email protected]';

	$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 );

		//header('Location: https://web-site-name.com');
   exit;
}?>


After excuting the Form, still get a dialog box, on the Form page, that shows “web-site-name.com says Error”, yet the Form’s field info gets sent successfully.

And after Form submit, in the dev tools > Console it only shows one line,

[ ] upload.html:78

And, of course, the Form (jBox) doesn’t close.
Any additional help with call back and validation, is appreciated.

This post has been edited by chrisjchrisj: 24 April 2020 - 09:48 PM

Was This Post Helpful? 0
  • +
  • -

#13 Ornstein   User is offline

  • D.I.C Head

Reputation: 105
  • View blog
  • Posts: 216
  • Joined: 13-May 15

Re: Help with validating web Form from ajax

Posted 25 April 2020 - 02:55 AM

Given the options you're passing through to jBox, I guess when you want it to close you'll need to do something like:

myConfirm.close();


I notice you removed the Content-Type header, but you also don't decode the response as JSON or pass the relevant option for jQuery to do it for you - so I'd imagine your success conditional is failing because of that. Personally, I'd put the header back in.
Was This Post Helpful? 0
  • +
  • -

#14 ArtificialSoldier   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2760
  • View blog
  • Posts: 8,066
  • Joined: 15-January 14

Re: Help with validating web Form from ajax

Posted 25 April 2020 - 02:01 PM

Quote

After excuting the Form, still get a dialog box, on the Form page, that shows “web-site-name.com says Error”, yet the Form’s field info gets sent successfully.

Sure it does, look at your code. You check the values in $_POST and set up $data and $errors, and maybe print it. Then you check if $_POST has values in it and send the email. One thing is not connected to the other.
Was This Post Helpful? 0
  • +
  • -

#15 chrisjchrisj   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 141
  • Joined: 04-February 19

Re: Help with validating web Form from ajax

Posted 25 April 2020 - 05:00 PM

Thanks for your reply.

I added code that now prevents the Form from submitting and the email from sending, if, for example, the Name is left empty...Error! Now, upon submit/continue, the Form(jBox) should close to allow access to the page it is blocking. Yet, it doesn't. Maybe this .js is not getting a call back to proceed? 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) {
      myConfirm.close();
     // alert('Success');
    } else {
      alert('Error');
    }
  }
});



And the submit.php code:



<?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 = '[email protected]';
	$subject = 'Thank You';
	$name = $_POST['name'];
	$email = $_POST['email'];
	$message = $_POST['message'];
	$message1 = $_POST['message'];
	$headers = $name;
	$headers = 'from: [email protected]';

	$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 $name;
echo $email;

   exit;
}?>


any additional guidance is appreciated

This post has been edited by chrisjchrisj: 26 April 2020 - 02:48 PM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2