Jump to content
hellomoto

Help with frontend ajax form submission on same page

Recommended Posts

I have a single-page website with a contact form:

        <div id="wrap_form">
          <form id="inquire" action="" class="uk-form">
            <div class="uk-grid uk-grid-collapse">
              <input type="text" id="i_name" name="name" class="uk-width" placeholder="Your Name" maxlength="250" required />
              <input type="text" id="i_phone" name="phone" class="uk-width" placeholder="###-###-####" pattern="^[2-9]\d{2}-\d{3}-\d{4}$" required />
              <input type="text" id="i_email" name="email" class="uk-width" placeholder="Email" pattern="/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/" maxlength="250" />
              <input type="text" id="i_zipcode" name="zipcode" class="uk-width" placeholder="Zip Code" pattern="\d{5}-?(\d{4})?" />
              <select name="scope" id="i_scope" class="uk-width" multiple required>
                <option value="" disabled>Representing...</option>
                <option value="residential">Residence</option>
                <option value="commercial">Business</option>
              </select>
              <textarea name="message" id="i_message" class="uk-width" placeholder="Message" rows="4" required></textarea>
              <input type="submit" name="submit" id="submit" class="uk-button uk-width" value="Send" />
              <!--button type="submit" name="submit" id="submit" class="uk-button uk-width">Send <i class="fa fa-send"></i></button-->
            </div>
          </form>
        </div>

Above is from contact.php template partial included in my _main.php output, which includes this script in the body closing:

$(function() {
    $('.error').hide();
    $("#inquire").submit(function(e) {
      e.preventDefault();
      // validate and process form here
      $('.error').hide();
  	  //var name = $("input[name='name']").val();
  	  var name = $("input#i_name").val();
  		if (name == "") {
        $("label#name_error").show();
        $("input[name='name']").focus();
        return false;
      }
  		//var phone = $("input[name='phone']").val();
  		var phone = $("input#i_phone").val();
  		if (phone == "") {
        $("label#phone_error").show();
        $("input[name='phone']").focus();
        //return false;
      }
  		//var email = $("input[name='email']").val();
  		var email = $("input#i_email").val();
  		//var zipcode = $("input[name='zipcode']").val();
  		var zipcode = $("input#i_zipcode").val();
  		//var scope = $("select[name='scope']").val();
  		var scope = $("select#i_scope").val();
  		if (scope == "") {
        $("label#scope_error").show();
        $("select[name='scope']").focus();
        //return false;
      }
  		//var message = $("textarea[name='message']").val();
  		var message = $("textarea#i_message").val();
  		if (phone == "") {
        $("label#message_error").show();
        $("textarea[name='message']").focus();
        //return false;
      }

      var dataString = 'name=' + name + '&phone=' + phone + '&email=' + email + 'zipcode=' + zipcode + 'scope=' + scope + 'message=' + message;

      //alert (dataString); return false;
      $.ajax({
        type: "POST",
        url: "./inquiries/",
        data: dataString,
        success: function() {
          $('#wrap_form').html("<div id='inquired'></div>");
          $('#inquired').html("<h3>Inquiry submitted!</h3>")
          .append("<p>Thanks, " + name + "! We will be in touch soon.</p>")
          .hide()
          .fadeIn(1500, function() {
            $('#inquired p').append(" <i class='fa fa-check' style='color:green'></i>");
          });
        }
      });
      //return false;

    });
  });

I tried submitting directly to a php file in templates which is forbidden so I saw that this worked for someone and no longer get an error; the form seems to submit from the frontend, however nothing results from it in the admin.

Here's my inquiries.php template file:

<?php

$mailTo = $pages->get('/contact/')->contact_email;

// sanitize form values or create empty
$data = array(
    'name' => $sanitizer->text($input->post->name),
    'phone' => $sanitizer->text($input->post->phone),
    'email' => $sanitizer->email($input->post->email),
    'zipcode' => $sanitizer->text($input->post->zipcode),
    'scope' => $sanitizer->text($input->post->scope),
    'message' => $sanitizer->textarea($input->post->message),
);

$error = '';

if($input->post->submit) {
  $up = $pages->get('/inquiries/');
  $up->title .= "+";
  $up->save();

  $msg = "Name: $data[name]\n" .
         "Phone: $data[phone]\n" .
         "Email: $data[email]\n" .
         "Zip Code: $data[zipcode]\n" .
         "Job Type: $data[scope]\n" .
         "Message: $data[message]";

  $p = new Page();
  $p->title = date('Y/m/d H:i:s');
  $p->parent = $pages->get('/inquiries/');
  $p->template = 'inquiry';
  $p->message = $msg;
  $p->save();

}

I added the inquiries title appendage bit just for testing, but it just doesn't happen. How can I make this work/better test? 

Share this post


Link to post
Share on other sites
1 hour ago, hellomoto said:

bump

Give us chance :)

We will need some more info.

  1. Is ./inquiries/ really pointing to a PW page that has the inquiries.php template assigned to it?
  2. Is that page definitely being loaded?
  3. If that page is being loaded, what do you get when you dump $_POST?

 

  • Like 2

Share this post


Link to post
Share on other sites

Hi Adrian, I know sorry I'm just eager to overcome this and get it online. Yes to your first Q, I don't know about the others. It doesn't appear to be loading as I just added this 

  $up = $pages->get('/inquiries/');
  $up->title .= "-";
  $up->save();

before if($input->post->submit) {} so no matter what when I send the form Inquiries page in the admin should become "Inquiries-" and it did not. 

Share this post


Link to post
Share on other sites

Here are a few things you could check:

$("#inquire").submit(function(e) {

Do you fire a submit event right on start? Is this by purpose? If not, it should be rather

$("#inquire").on('submit', function(e) {

Maybe you should change it to full url instead:

$.ajax({
        type: "POST",
        url: "./inquiries/",

Here you might save the page first, set msg and save again:

$p->save();
$p->message = $msg;
$p->save();

 

Share this post


Link to post
Share on other sites

What are you doing with the $error var?

$error = '';

if($input->post->submit) {

try adding an else statement at the bottom of your PHP.

Also, in your 

$.ajax

call you only have a success scenario, but none for failure... which is not a good idea.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By ICF Church
      Hi 👋
      Anyone else having this problem?
      Requirements:
      - Repeater (matrix & normal) with mutlilanguage fields (text, textarea…) 
      - Backend language set to something other than default (ie. German) 
      Reproduce:
      - Add a new repeater Item (ajax, I found no way to possible to disable it with matrix)

      (Notice how the default language tab is active instead of the backend language…)
      - Write something into the (default language) field
      - Try to save, if field is required, this will not work. If not required, then when reloading, the content will be inside the backend language field, instead of the default language field who was (presumably) active
      Analysis:
      When  loading  a new repeater element with ajax, the default langue tab is active, but the backend language inputfield is visible (with no visual indication). When writing into the field, it will populate the backend language. When manually clicking on the default language tab (which is already active), the field will switch to the actual default language field (which is [now] empty) (that can now be populated…)
      Also Notice, the labels of the elements to be added are in default language as well instead of the translated label (images instead of Bilder)…
      ProcessWire 3.0.148, Profields 0.0.5…
      Is it my system configuration, or does anyone else have the same issue? This is a screen recording of the problem:
      Issue: https://github.com/processwire/processwire-issues/issues/1179

      Screen Recording 2020-02-25 at 14.18.31.mov
    • By benbyf
      I have a a form in my site footer that can be accessed anywhere on site, I've added the form in the _inc.php file and added the render in the pages footer.php. However, this works well on the homepage e.g. you can submit said form and get a thank you on reload, doesnt work at all on other pages... Just lots like a fresh reload. Any thing im doing wrong here or ways to diagnose as there isn't an error log for formbuilder etc...?
    • By Peter Knight
      I have a few web forms which require testing on a weekly basis and I don't want the recipients (administrators) to receive these test emails.
      What would be a good way to test approx 15 forms from the front end and have the test delivered a list of secondary administrator recipients?
      I'm thinking that I could have some kind of config file which watches for a trigger word or email and then understands that it's a test and to bypass the normal admins?
      All of the forms ask for an email address so I could setup an email such as 'testform@email.not' etc which my config file (hook?) would watch for.
      Or is there a better way to do this?
      Additionally, I have a few extra requirements...
      Forms should goto an alternative success page. This is because I don't want my test to skew my Google Analytics conversion tracking Forms would need to be tested from the front-end and not the PW admin area Any advice appreciated.
      BTW I realise this should be posted in the proper FormBuilder support forum. I am in the process of renewing my license for access to that support forum.
       
    • By michelangelo
      Hello there,
      I am building my website, which has a dozen projects with 10 images each. Basically, I need a filtering system but built in the most efficient and user-friendly way. You can see below that the images flow sideways so being hidden, JS lazy loading was a good tool, but I just wanted to try AJAX. Is it fit for this purpose or it's more for dynamic content?
       

    • By louisstephens
      I have been messing around with creating pages from ajax requests, and it has gone swimmingly thus far. However, I am really struggling with creating a page and saving an image via ajax. 
      The form:
      <form action="./" role="form" method="post" enctype="multipart/form-data"> <div> <input type="text" id="preview" name="preview" placeholder="Image Title"> </div> <div> <input type="file" id="preview-name" name="preview-name"> </div> <div> <select id="select-tags" name="select-tags"> <?php $tags = $pages->find("template=tag"); ?> <option value="">Select Your Tags</option> <?php foreach ($tags as $tag) : ?> <option value="<?= $tag->name; ?>"><?= $tag->name; ?></option> <?php endforeach; ?> </select> </div> <div> <button type="button" id="submit-preview" name="submit" class="">Upload Images</button> </div> </form>  
      The ajax in my home template:
      $('#submit-preview').click(function(e) { e.preventDefault(); title = $("#preview").val(); image = $("input[name=preview-name]"); console.log(title); console.log(image); data = { title: title, image: image //not sure if this is actually needed }; $.ajax({ type: 'POST', data: data, url: '/development/upload-preview/', success: function(data) { console.log("Woo"); }, error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); } }); }); And finally in my ajax template:
      $imagePath = $config->paths->assets . "files/pdfs/"; //was from an older iteration $title = $sanitizer->text($_POST['title']); $image = $sanitizer->text($_POST['image']); $p = new Page(); $p->template = "preview"; $p->parent = $pages->get("/previews/"); $p->name = $title; $p->title = $title; $p->save(); $p->setOutputFormatting(false); $u = new WireUpload('preview_image'); $u->setMaxFiles(1); $u->setOverwrite(false); $u->setDestinationPath($p->preview_image->path()); $u->setValidExtensions(array('jpg', 'jpeg', 'gif', 'png', 'pdf')); foreach($u->execute() as $filename) { $p->preview_image->add($filename); } $p->save(); I can complete the file upload but just using a simple post to the same page and it it works well, but I was really trying to work out the ajax on this so I could utilize some modals for success on creation (and to keep my templates a little cleaner). When I do run the code I have, a new/blank folder is created under assets, and a new page is created with the correct title entered. However, no image is being processed. I do get a 200 status in my console. I have searched google for help, but everything seems to be slightly off from my needs. If anyone could help point me in the right direction I would greatly appreciate it. 
×
×
  • Create New...