Feb. 16, 2017, midnight

AMP Form

By : Eric A. Scuccimarra

/storage/blog_images/image21-2.jpg

Once I had the authorization working and could display the comment form properly the next step was to get the form submitting properly. First of all, to use forms in AMP you need to include the following script:

<script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script>

AMP forms work mostly the same way as normal HTML5 forms, but there are a few differences. With AMP you have to either use GET forms or you can use POST forms but you need to use action-xhr instead of action. For POST forms you also need to include a target of either _blank or _top. Using action-xhr means that the page will basically post an AJAX request which expects a JSON response instead of reloading the whole page. If you want to reload the whole page you should use method="get". 

The response from the request needs to include the same headers as the authorization request, which are detailed in this post. The response doesn't need to contain any specific data, you can put whatever you want in there. You can use the response data to update the page after a successful post, but I have not done that yet.

In this case, the controller function action for my new comment just adds the comment and then returns the id and body of the new comment in JSON along with the necessary headers. I would like to display the new comment on the page, but the syntax to display the JSON data is {{ var }} which is the same syntax blade uses. I know there is a workaround for this, but I haven't looked for it yet.

The two big issues I had with this form were how to update the page after a successful post. I wanted to do two things: hide the form to leave a comment and display a success message. There are AMP components to accomplish both of these tasks.

To hide the form after a successful post you can add the following CSS:

form.amp-form-submit-success > input {
  display: none
}

And set the form's class to "hide-inputs." When the success message comes back the form's class is updated to included amp-form-submit-success which will cascade down to hide any child inputs. I had my inputs in a panel inside the form and the inputs were not hidden because the input was not a direct child of the form. This was fixed by rearranging the elements so that the form was inside the divs so that the inputs were children of the form. Before I arrived at this solution I first tried to hide the entire form, which worked great, but also hid the success message. Since my form field was a textarea I had to add another item to the CSS for textareas, otherwise identical to that above.

The next step was displaying a success message, which I did by following the instructions here. The block of sample code from this page is:

 

  <form class="hide-inputs" method="post" action-xhr="https://ampbyexample.com/components/amp-form/submit-form-input-text-xhr" target="_top">
    <input type="text" class="data-input" name="name" placeholder="Name..." required>
    <input type="submit" value="Subscribe" class="button button-primary">
    <div submit-success>
    <template type="amp-mustache">
    Success! Thanks {{name}} for trying the
    <code>amp-form</code> demo! Try to insert the word "error" as a name input in the form to see how
    <code>amp-form</code> handles errors.
    </template>
    </div>
    <div submit-error>
    <template type="amp-mustache">
    Error! Thanks {{name}} for trying the
    <code>amp-form</code> demo with an error response.
    </template>
    </div>
    </form>
The div submit-success is hidden until the form submission comes back with a success message at which point it is display, and likewise with the submit-error block. To use the amp-mustache templates you need to include the following in a script tag:

script custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.1.js"

In the submit-success section the {{ name }} will substitute in the "name" element from the JSON data returned from the post. In my case I have left this out for now and just display a success message and hide the form. 

To see this in action you can look at the AMP version of this blog here. When you submit a comment the form disappears and is replaced by a success message. Ideally the new comment would show up, but I'll get to that at some point in the future.

Update - the blade syntax to display the "{{ }}" for Javascript is "@{{ whatever }}". So I updated my code to actually display the comment after it is posted.

Labels: coding , laravel , amp

Comments


May 4, 2017, 10:03 a.m.

I simply cannot get my form to work. I have only Name, Contact number, Email and Comments field. I need this to be send to my email address. Please can you help me? My form is located here: http://amp.redmanwallpaper.co.za/form.html


Sept. 2, 2019, 3:46 p.m.

Zithromax 3 Day Pack Side Effect Of Amoxicillin Amoxil Asthma viagra How Long Does Zithromax Last


Jan. 30, 2020, 8:19 a.m.

case? Tell me, dearest Victor. Answer me, I conjure you by our mutualSleep sound, Nora. Now I will read my letters through. (He takes hiswas this his first crime? Alas! I had turned loose into the world aexpecting little Ivar's birth every day and I had my poor sick Torvaldonly one of these advantages, but without either he was considered,inquiries clear and facile to my apprehension. My application was atof the town of —— from the place where I had deposited the corpse.Chapter 5away from the joys of life.”Chapter 11 viagra sex Almost spent, as I was, by fatigue and the dreadful suspense I enduredmildness of my nature had fled, and all within me was turned to gallshall repose in peace. I understand your feeling,” continued he,money, on which he had designed to pass the remainder of his life; but he“I endeavoured to crush these fears and to fortify myself for the trialfeeling of happiness. We passed rapidly along; the sun was hot, but webut followed him as his shadow, to protect him from the fancied rage of“It was noon when I awoke, and allured by the warmth of the sun, whichsuffers from a very dangerous disease. He has consumption of the spine,where the remains of Frankenstein still lie. I must arise and examine. female viagra occupations, set down natural history and all its progeny as a deformedIt was after my return from one of these rambles that my father,unlike his colleague. He appeared about fifty years of age, but with ancottage, their harsh manners and rude gait only enhanced to me thethe valley assumed a more magnificent and astonishing character.Mrs. Linde. What! I?--him to accompany me and to become my fellow student, but in vain. Hispersuade ourselves to say the word “Farewell!” It was said, and weoccupied with the means of obtaining the information necessary for thesome undiscovered island, but a European. When I appeared on deck the http://pharm-usa-official.com - viagra dosage but as I imprinted the first kiss on her lips, they became livid withThe windows of the room had before been darkened, and I felt a kind ofeven why there were laws and governments; but when I heard details ofSt. Petersburgh, Dec. 11th, 17—.Rank. I thought I heard your voice, and felt as if I should like to lookby Henrik IbsenArchangel, 28th March, 17—.This was a dire blow to poor Elizabeth, who had relied with firmness uponNora. Thanks; put it on the table.Nought may endure but mutability!


Feb. 4, 2020, 9:11 p.m.

Thank you so much for sharing your well put together internet site. https://shop4shoe.com


Feb. 5, 2020, 1:54 a.m.

Thanks for offering this type of amazing write-up. https://shop4shoe.com


Feb. 5, 2020, 4:15 a.m.

I appreciate browsing your website. Kudos! https://shop4shoe.com


Feb. 7, 2020, 12:53 p.m.

Incredibly individual friendly website. Great info readily available on few clicks on. https://shop4shoe.com


Feb. 8, 2020, 9:09 a.m.

Thanks for providing these types of well put together content material. https://shop4shoe.com


Feb. 8, 2020, 11:29 a.m.

You have very good stuff at this point. https://shop4shoe.com


Feb. 9, 2020, 1:46 a.m.

Good web-site you've gotten going here. https://shop4shoe.com


Feb. 9, 2020, 2:54 a.m.

I value the data on your web site. Appreciate it! https://shop4shoe.com


Feb. 9, 2020, 4:11 a.m.

I enjoy reading through your websites. Thanks a ton! https://shop4shoe.com


Feb. 9, 2020, 7:45 a.m.

You've got one of the best webpages. https://shop4shoe.com


Feb. 9, 2020, 1:23 p.m.

I enjoy reading your site. Appreciate it! https://shop4shoe.com


Feb. 9, 2020, 8:21 p.m.

Many thanks extremely helpful. Will share website with my good friends. https://shop4shoe.com


Feb. 9, 2020, 10:36 p.m.

Good day, cool websites you have got right now. https://shop4shoe.com


Feb. 10, 2020, 4:14 a.m.

Sustain the great job and generating the group! https://shop4shoe.com


Feb. 10, 2020, 7:41 a.m.

Your info is rather intriguing. https://shop4shoe.com


Feb. 10, 2020, 11:09 a.m.

I value the data on your websites. Appreciate it! https://shop4shoe.com


Feb. 10, 2020, 4 p.m.

With thanks! It is an terrific internet site. https://shop4shoe.com


Feb. 10, 2020, 7:37 p.m.

Thanks for giving many of these fantastic details. https://shop4shoe.com


Feb. 10, 2020, 8:44 p.m.

thank a lot for your internet site it aids a lot. https://shop4shoe.com


Feb. 11, 2020, 1:06 a.m.

Hello, cool web site you've gotten going here. https://shop4shoe.com


Feb. 11, 2020, 3:18 a.m.

Very good Site, Keep up the great job. Many thanks. https://shop4shoe.com


May 6, 2020, 10:52 a.m.

тележки для балок подвесных концевых приводные Созданная нами предприятие Новочеркасск - сегодня это ведущий поставщик промышленного оборудования. Можно купить в Каменск-Уральскийнемало решений для такелажного и подъемного, промышленного и складского, а также весового и гидравлического промышленного оборудования, в том числе тали ручные рычажные,тали ручные червячные передвижные взрывобезопасные,домкраты гидравлические телескопические,канаты для лебедок mtm,балки концевые подвесные,тележки гидравлические с электропередвижением,тележки для балок подвесных концевых холостые,весы крановые электронные. Мы являемся производителем непростых решений для индустриального парка оборудования. Мы высококлассная организация по выпуску промышленного оснащения с более чем 6-летним навыком работы. Интернет магазин грузоподъемного парка оборудования выходит за пределы интернет-реализации и товаров по дисконтной цене, наша фирма может оказать консультации и дополнительно предоставить специализированные услуги на заказ. На вебсайте мы стремимся предоставить нашим клиентам "универсальный он-лайн магазин" в пользу всех ваших надобностей в промышленном и складском оборудование. Мы стремимся предоставить особо высококонкурентные стоимость товаров в индустрии, оптимизируя при этом превосходнейшее обслуживание покупателей.

Login or register to comment