4

I'm sure the title will get my scoulded by the SO naz. . moderators. But I wasn't sure what to name it.

I have a form that I have saved in it's own php file. I include this form on the bottom of each page on the website. This is the form file.

This should be the minimum needed code to show my issue.

<?php
error_reporting(E_ALL);
//Declare variables, strip html, and php tags and then assign value from POST
if(isset($_POST['submit'])){

  $name  = strip_tags($_POST['name']);
  $phone = strip_tags($_POST['phone']);
  $email = strip_tags($_POST['email']);

  $errors = array();

//Validate input
  //Name
  if(!empty($name)) {
     //Check to see that $name only contains valid characters
     if(!preg_match("/^[a-zA-Z'-]+$/", $name)) { $errors[] = "Names may only contain letters and spaces."; } 
  }else{
     $errors[] = "Name field must be filled out.";
  }
  //End Name

  //Phone
  if(!empty($phone)) {

  }else{
     $errors[] = "Phone field must be filled out.";
  }
  //End Phone

  //Email
  if(!empty($email)) {
     if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Invalid email format."; }
  }else{
     $errors[] = "Email field must be filled out.";
  }
  //End Email       

    echo json_encode($errors);

}
 ?>

<!-- Action Form -->
<section id="sectActionForm">
<div class="row">

    <div class="col1 col-md-6">
        <img class="noPad" src="/images/banners/karateka.jpg">
    </div>

    <div id="col2" class="col-md-6 col-xs-12">

            <form id="actionForm" class="" role="form" action="index.php" method="POST">
                <h3>Get your FREE class today!</h3>

                <input id="name" class="form-control" type="text" placeholder="Name" /><br/>

                <input id="phone" class="form-control" type="text" placeholder="Phone" /><br/>

                <input id="email" class="form-control" type="text" placeholder="Email" />

                <input class="btn btn-lg btn-block" type="submit" value="Send" />
            </form>

    </div>

</div>
</section>

<script type="text/javascript">
$(document).ready(function(){
    $.ajax({
        type: "POST",
        url: "action.include.php",
        dataType: "json",
        success: function(data){
            alert(data);
        }
    })
});
</script>

<!-- END Action Form -->

My problem is that since this form could be being accessed from any page, I don't know what to put in the AJAX url section.

My DESIRED BEHAVIOR: I would like for the php errors array to be passed to the ajax so it can be displayed in a modal error box.

5
  • I think $_SERVER['PHP_SELF'] could do it Commented Aug 23, 2015 at 1:22
  • Just jam that into the url section? Commented Aug 23, 2015 at 1:25
  • Look at my answer and check if it works Commented Aug 23, 2015 at 1:38
  • If all you need is to display the $errors array in a modal error box, how does ajax come in? The $errors array is available at load time on whatever page this script is included in. ... Or else I am missing something major. Commented Aug 23, 2015 at 2:06
  • I'm trying for as seamless as possible. If I can get an error up without having to refresh and have the page end up back at the top it looks better. Commented Aug 23, 2015 at 2:32

3 Answers 3

1

not sure if i'm missing something, but you would literally just put the path of the file as the url. So if the name of the form php file is myForm.php, the ajax url would be myForm.php

Sign up to request clarification or add additional context in comments.

1 Comment

I wondered that too. But since I'm so out of my league here, I couldnt properly test cause I dont even know if I'm passing the array correctly. I press the submit button and nothing happens
1

Try with this...

<?php
error_reporting(E_ALL);
//Declare variables, strip html, and php tags and then assign value from POST
if(isset($_POST['submit'])){

  $name  = strip_tags($_POST['name']);
  $phone = strip_tags($_POST['phone']);
  $email = strip_tags($_POST['email']);

  $errors = array();

//Validate input
  //Name
  if(!empty($name)) {
     //Check to see that $name only contains valid characters
     if(!preg_match("/^[a-zA-Z'-]+$/", $name)) { $errors[] = "Names may only contain letters and spaces."; } 
  }else{
     $errors[] = "Name field must be filled out.";
  }
  //End Name

  //Phone
  if(!empty($phone)) {

  }else{
     $errors[] = "Phone field must be filled out.";
  }
  //End Phone

  //Email
  if(!empty($email)) {
     if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "Invalid email format."; }
  }else{
     $errors[] = "Email field must be filled out.";
  }
  //End Email       

    exit(json_encode($errors)); // exit so it doesn't send the form below

}
 ?>

<!-- Action Form -->
<section id="sectActionForm">
<div class="row">

    <div class="col1 col-md-6">
        <img class="noPad" src="/images/banners/karateka.jpg">
    </div>

    <div id="col2" class="col-md-6 col-xs-12">

            <form id="actionForm" class="" role="form" action="index.php" method="POST">
                <h3>Get your FREE class today!</h3>

                <input id="name" class="form-control" type="text" placeholder="Name" /><br/>

                <input id="phone" class="form-control" type="text" placeholder="Phone" /><br/>

                <input id="email" class="form-control" type="text" placeholder="Email" />

                <input class="btn btn-lg btn-block" type="submit" value="Send" />
            </form>

    </div>

</div>
</section>

<script type="text/javascript">
$("#actionForm").on('submit', function(event){
    event.preventDefault(); // so it doesnt reload the page
    $.ajax({
        type: "POST",
        url: "<?php echo $_SERVER['PHP_SELF'] ?>",
        dataType: "json",
        success: function(data){
            alert(data);
        }
    });
});
</script>

<!-- END Action Form -->

4 Comments

Sweet. I'll give it a test shortly and report my findings. :)
Nope. The page reloads and nothing comes up. Gonna add an error function to the ajax to see if its getting that far. . No luck. Nothing from the error function
@Zerquix18 the event variable is missing in the callback parameters: $("#actionForm").on('submit', function(event){. I think you could also use the window.location.pathname value instead of "<?php echo $_SERVER['PHP_SELF'] ?>" for the url :)
@Brunt I just fixed the event error, thanks you ! And I think PHP SELF is better. It points the exactly file url, no matter where they load the file, even if it's re-wrtitten with RewriteRule.
0

Where are the 'name' attributes? All I see is 'id' and $_POST submits the name and value. Did this code ever work? What am I missing?

EDIT: Place this line of code right above your <form>: <h4 id="errors" class="error"><?php if(isset($errors) && count($errors)) echo($errors);?></h4>. Add a class called 'error' and style it the way you want. You might want to add a <br> tag to the end of each error message. Or use the explode command instead of adding the <br> tag and the echo command.

4 Comments

You are correct, its missing the name tags. But that should be irrelivant to the issue I'm working on since it would simply cause the errors to always be present and I'm working on displaying the errors.
Are you trying to display the PHP $errors[] array? Or are you trying to display some other errors?
OK, check out my edited answer above. Let me know what happens.
Oh yes, the $errors is an array so you will have to use the explode command and not the echo command.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.