Donnerstag 16 Februar 2017 um 08:07

AMP Form

Von Eric Antoine Scuccimarra

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.

Etiketten: coding, laravel, amp


Bemerkungen

Anmeldung oder Registrieren einen Kommentar hinterlassen..


Maryke

May 04, 2017 at 10:03 am

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

Lesroni

Sep 02, 2019 at 03:46 pm

Zithromax 3 Day Pack Side Effect Of Amoxicillin Amoxil Asthma <a href=http://curerxfor.com>viagra</a> How Long Does Zithromax Last

usgrmbnut

Jan 30, 2020 at 08:19 am

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 <a href="http://pharm-usa-official.com">viagra sex</a> 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. <a href=http://pharm-usa-official.com>female viagra</a> 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!

tixbwfnut

Feb 04, 2020 at 09:11 pm

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

dxxdivnut

Feb 05, 2020 at 01:54 am

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

fjspytnut

Feb 05, 2020 at 04:15 am

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

utlltanut

Feb 07, 2020 at 12:53 pm

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

ljvgtbnut

Feb 08, 2020 at 09:09 am

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

dgjrmonut

Feb 08, 2020 at 11:29 am

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

twtxiinut

Feb 09, 2020 at 01:46 am

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

lfwroanut

Feb 09, 2020 at 02:54 am

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

siatrwnut

Feb 09, 2020 at 04:11 am

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

wzoeubnut

Feb 09, 2020 at 07:45 am

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

cnmgiinut

Feb 09, 2020 at 01:23 pm

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

uxvevcnut

Feb 09, 2020 at 08:21 pm

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

eimedbnut

Feb 09, 2020 at 10:36 pm

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

sewqounut

Feb 10, 2020 at 04:14 am

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

awfjoonut

Feb 10, 2020 at 07:41 am

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

vttsicnut

Feb 10, 2020 at 11:09 am

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

mijpgqnut

Feb 10, 2020 at 04:00 pm

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

ckgoynnut

Feb 10, 2020 at 07:37 pm

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

efnrggnut

Feb 10, 2020 at 08:44 pm

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

lcrpycnut

Feb 11, 2020 at 01:06 am

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

opautunut

Feb 11, 2020 at 03:18 am

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

3aplus63Cam

May 06, 2020 at 10:52 am

<b><a href=https://3aplus63.ru/product-category/telezhki-dlja-balok-podvesnyh-koncevyh-privodnye/>тележки для балок подвесных концевых приводные</a></b> Созданная нами предприятие Новочеркасск - сегодня это ведущий поставщик промышленного оборудования. Можно купить в Каменск-Уральскийнемало решений для такелажного и подъемного, промышленного и складского, а также весового и гидравлического промышленного оборудования, в том числе тали ручные рычажные,тали ручные червячные передвижные взрывобезопасные,домкраты гидравлические телескопические,канаты для лебедок mtm,балки концевые подвесные,тележки гидравлические с электропередвижением,тележки для балок подвесных концевых холостые,весы крановые электронные. Мы являемся производителем непростых решений для индустриального парка оборудования. Мы высококлассная организация по выпуску промышленного оснащения с более чем 6-летним навыком работы. Интернет магазин грузоподъемного парка оборудования выходит за пределы интернет-реализации и товаров по дисконтной цене, наша фирма может оказать консультации и дополнительно предоставить специализированные услуги на заказ. На вебсайте мы стремимся предоставить нашим клиентам "универсальный он-лайн магазин" в пользу всех ваших надобностей в промышленном и складском оборудование. Мы стремимся предоставить особо высококонкурентные стоимость товаров в индустрии, оптимизируя при этом превосходнейшее обслуживание покупателей.

Archiv