Stuck on the posting part of a form



  • So, I'm using knockout javascript to build a dynamic form, and I wanted to post it, and it never occurred to me that posting could allow me to grab the result and throw it onto the page. I just assumed that it would load another page. (Please forgive me, the last time I did anything PHP was 2007). Yet, jQuery post doesn't do that, at least that I see. So, I can easily post to the next page, pull some container back, and display it on the page. Not bad at all really.

    So, now I'm at this decision making point, and I'm a little unsure of how to proceed.

    The goal is to take the result of the form and generate 3 emails. They don't care to store off the form data in their database, just email it to them.

    So, should I replace the contents of the page I'm on? I mean, the form is still just floating there, with all the data intact, willing to accept changes. Willing to let the user post all the same data again. Do I replace that entire section? Would KO flip out?

    I'm thinking of replacing it with a landing that shows them their selections and some display that confirms the email was sent?

    Should I do a confirm 2-step submit?

    Here's the form as I have it now (with proprietary data removed)

    0_1459741256996_upload-310b17d1-bd90-42aa-b5fa-d2e46dd141ee



  • uhm, this is not a PHP problem, it's a web one :P

    so, your form has no action or an action set to the same page it?
    and you need to somehow post it with jquery? do you really need ajax?

    maybe with something in the lines of:

    $('#theForm').submit();
    

    it will reload the page and let you present the same form with a "Emails sent!" in the top or something.
    i mean, that's the standard way to do something simple like that 10 or so years ago...


    WAIT i didn't read the KO part. yo can replace the entire page, it won't hurt KO, read about templates, you can make two templates, one for the form, and another one for the landing you're planning, both based on the same viewmodel.

    the easiest option is to disable all the inputs and add a "Emails sent!" somewhere

    also, i'll drop a mention because this was meant to be a reply @xaade



  • @Jarry said in Stuck on the posting part of a form:

    do you really need ajax?

    I don't know what I need.

    @Jarry said in Stuck on the posting part of a form:

    WAIT i didn't read the KO part.
    yo can replace the entire page, it won't hurt KO, read about templates, you can make two templates, one for the form, and another one for the landing you're planning, both based on the same viewmodel.

    Great.... I'll look into that.

    The idea I had in mind would be to have it show pretty much what they selected, and then a "congrats you did it" :P

    The reason I need to post at all is because I need to perform some calculations on the second page to send out the emails, but using pricing data that the client doesn't want showing up in javascript.

    I might have to use a second page, because I need the two pages to behave differently, with one giving the inputs, and a second one calculating and sending emails. I don't know how complicated that would be to do in one page.

    I really miss MVC/ASP.NET... not a fan of PHP at all.



  • @xaade said in Stuck on the posting part of a form:

    The idea I had in mind would be to have it show pretty much what they selected, and then a "congrats you did it"

    Disable all inputs, show a spinner with "sending". On submit complete : change spinner to success message.
    Takes 10 minutes to do.
    Imo no reason to create a new viewmodel for something that simple



  • @swayde I'm totally cool with that...

    Hopefully they'll like it too.

    Obviously they find the input form really compelling, because they had been doing this by hand, and by conversation, phone calls that took hours.

    That definitely fits the jQuery post concept very well.

    I wonder if I can post to the same page....? (I know I can, I mean.... do it without making things too complicated)


  • I survived the hour long Uno hand

    @xaade I suspect you're not conceiving the model the same way jQuery is.

    In most AJAX frameworks (disclaimer: I don't know KO), you don't post to pages, you post to endpoints. They assume some kind of REST api, but it can be anything: you submit forms to submitform.php, or you make a new widget by posting to /widget, or to /widget/new. But the API layer has its own set of endpoints for doing things, separate and apart from the page structure presented to the user (/index.php, /about.php, /form.php).

    Every time you need specific types of information or are submitting specific types of information, you whip up an endpoint to get it.



  • @xaade said in Stuck on the posting part of a form:

    second page

    The second page doesn't necessarily need to be visible, it just needs to communicate its success or failure back to the first page somehow.

    You could go the AJAX submit route (kind of hacky in my opinion, since there's no built-in method to AJAX submit a form yet... you're forced to serialize the form data by hand instead of letting the browser do it), or you could submit it to a hidden <iframe> and then pass the response from that back to the page (still a bit hacky to get the results back, but at least this lets the browser natively handle the form submission). Or... you could style the iframe as a modal overlay and have it contain the human-readable response message. Then you'd just need to toggle visibility and build some chrome to hide it afterward.

    If you also want to support non-Javascript, you can set the form's default target to "_blank" to give it a graceful fallback, then change it to the ID of the iframe if the script runs. Then ensure that your second page does also produce some meaningful, human-readable output.

    @xaade said in Stuck on the posting part of a form:

    I wonder if I can post to the same page....? (I know I can, I mean.... do it without making things too complicated)

    Assuming you use a POST method, you can just wrap your entire page with a PHP conditional:

    <?php
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
      // handle the form submission
    } else {
    ?>
    
    <!-- rest of your page goes here -->
    
    <?php
    }
    ?>
    

    Otherwise, you can check isset($_GET['some_id']) to see if the form was submitted.


  • Winner of the 2016 Presidential Election

    @anotherusername said in Stuck on the posting part of a form:

    <?php
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
      // handle the form submission
    } else {
    ?>
    
    <!-- rest of your page goes here -->
    
    <?php
    }
    ?>
    

    Inline PHP :mask:


  • sockdevs

    @anotherusername said in Stuck on the posting part of a form:

    you're forced to serialize the form data by hand instead of letting the browser do it

    Or you use $(form).serialize();


  • โ™ฟ

    @anotherusername said in Stuck on the posting part of a form:

    ?>

    Don't end your PHP scripts with that. You'll thank me later.

    Also, no BOM.



  • @asdf don't you mean

    Inline PHP :mask:


  • Winner of the 2016 Presidential Election

    @anotherusername Yeah, but especially PHP mixed with HTML. And if you do that, at least have the decency to use else: and endif; instead of just leaving a closing brace somewhere in the middle of a sea of HTML.



  • @RaceProUK said in Stuck on the posting part of a form:

    @anotherusername said in Stuck on the posting part of a form:

    you're forced to serialize the form data by hand instead of letting the browser do it

    Or you use $(form).serialize();

    jQuery doesn't have a magical native form.serialize method that Javascript doesn't. It just serializes the form by hand.

    It's slightly better than rolling your own (okay, a lot better), but it's still doing the work by hand (i.e. in Javascript) instead of having the browser do it natively.

    @asdf said in Stuck on the posting part of a form:

    especially PHP mixed with HTML

    ...well, that's kind of how PHP works.

    @asdf said in Stuck on the posting part of a form:

    if you do that, at least have the decency to use else: and endif; instead of just leaving a closing brace somewhere in the middle of a sea of HTML.

    Fair point. I'm more familiar with the C-style syntax, but okay.



  • @anotherusername said in Stuck on the posting part of a form:

    ...well, that's kind of how PHP works.

    yeah, no. that was back in PHP 4. right now it let's you do something like that, but it's not how you're supposed to work.



  • @Jarry Last time I actually did much of anything with PHP was around the 4-5 transition, so feel free to explain how you'd do it now.



  • @anotherusername
    oh, we don't talk about the dark times anymore. nowadays we are in the "almost but not entire dark days"



  • @Jarry

    Last I knew, there were two ways to get a bunch of HTML inside PHP.

    ?><!-- a bunch of html --><?php
    

    and

    echo "<!-- a bunch of html -->";
    

    and one of those is definitely :doing_it_wrong: if <!-- a bunch of html --> isn't really short.

    Like I said, if there's a new way that's better, I'm all ears.



  • @anotherusername
    the thing is, i don't really do bare PHP anymore, to avoid doing that what i usually do is work with templates and maybe, if it's really needed, a templating library.



  • @anotherusername

    @anotherusername said in Stuck on the posting part of a form:

    @Jarry

    Last I knew, there were two ways to get a bunch of HTML inside PHP.

    ?><!-- a bunch of html --><?php
    

    This is (generally accepted) best practice, printing out a fuckton of HTML via echo/print_r/whatever is not recommended (stick to echoing out variables, not HTML).

    See @Yamikuronue's post about Ajax frameworks, same is true for PHP forms - post it to an endpoint, not self. This prevents issues with the back button/refresh button.



  • @anotherusername said in Stuck on the posting part of a form:

    Like I said, if there's a new way that's better, I'm all ears.

    Oh, I hate the whole

    The Right WayTM

    It's fucking opinions the whole way down.

    I'll just pick one of the above arbitrarily because.... noise.



  • @ben_lubar Can you please explain?

    @ben_lubar said in Stuck on the posting part of a form:

    @anotherusername said in Stuck on the posting part of a form:

    ?>

    Don't end your PHP scripts with that. You'll thank me later.

    Also, no BOM.


  • sockdevs

    @xaade A lot of tools (especially OSS ones) don't correctly recognise a BOM at the start of a UTF-8 file; this can lead to issues ranging from unexpected whitespace to fatal crashes



  • @Yamikuronue said in Stuck on the posting part of a form:

    In most AJAX frameworks (disclaimer: I don't know KO), you don't post to pages, you post to endpoints

    That's my problem.

    If I make something to post to, and I give it php extension. Anyone can just navigate to it, right?

    If I don't give it .php, will the php engine kick in?

    I'm not exactly sure how to make an endpoint.


  • โ™ฟ



  • @xaade yup, anyone can navigate to it. but unless they post the right parameters, it won't tell them anything.
    you could use some kind of authentication schema to block non logged in users.
    the site has authentication ?



  • @ben_lubar That's a lot of noise...

    Surely there's a "do this, not that" in there somewhere....

    No, I'm just seeing a bunch of "this can cause the problem"....

    What's the alternative to ending php in ?>


  • โ™ฟ

    @xaade just skip the last ?> in the file if there's nothing after it.



  • @xaade

    @ben_lubar said in Stuck on the posting part of a form:

    @xaade just skip the last ?> in the file if there's nothing after it.

    Can confirm this - common as well in frameworks (Mini2, Cake and Laravel all do this to my knowledge)



  • @thegoryone said in Stuck on the posting part of a form:

    This is (generally accepted) best practice, printing out a fuckton of HTML via echo/print_r/whatever is not recommended (stick to echoing out variables, not HTML).

    Yes, exactly. I was strongly hinting to that:

    one of those is definitely :doing_it_wrong: if <!-- a bunch of html --> isn't really short.

    @xaade said in Stuck on the posting part of a form:

    Oh, I hate the whole
    The Right WayTM
    It's fucking opinions the whole way down.
    I'll just pick one of the above arbitrarily because.... noise.

    Yeah, agreed. Trying to template the code is great if you're producing a page framework that needs to be flexible, but for a one-off like this it's not always helpful. And you're still intermixing PHP and HTML; you're just confining that to the template, which you still have to write at some point.

    @xaade said in Stuck on the posting part of a form:

    @ben_lubar Can you please explain?

    Ending your PHP script in ?> can bite you because any whitespace after the ?> will be echoed to the browser. If your script needed to not echo anything, it mysteriously breaks, and it's not obvious why because the whitespace you're echoing is invisible. If you just omit the final ?>, everything works fine... and any whitespace is just ignored since it's parsed as part of the PHP.

    I mostly included both the starting and closing PHP tags because completeness... there might need to be other PHP wrapping around that. You can always just leave off the ?> if it's at the very end of the script.

    The BOM (if it's present) will be several bytes that occur before the <?php at the very beginning of your script. Your editor will probably hide them, but they'll be sent to the browser, and they'll prevent you from setting any headers in your script (unless output buffering is enabled).

    Basically, he pointed out two different cases to watch out for, where something that's invisible can break a script mysteriously.



  • Yeah, agreed. Trying to template the code is great if you're producing a page framework that needs to be flexible, but for a one-off like this it's not always helpful. And you're still intermixing PHP and HTML; you're just confining that to the template, which you still have to write at some point.

    This, absolutely. A valid approach for a small system without a doubt.

    Just remember however while there may not be a "right way", there are definitely some wrong ways. Fortunately this isn't one of them, neither was what @ben_lubar mentioned (though it's a well documented issue I've also bumped into before)


  • โ™ฟ

    @anotherusername said in Stuck on the posting part of a form:

    The BOM (if it's present) will be several Unicode characters

    Actually it's just one: zero-width non-breaking space.

    Unfortunately, it generally gets mojibake'd to รฏยปยฟ.



  • @ben_lubar :facepalm: yeah, I meant several bytes.

    Anyway, if you're using UTF-8, you shouldn't include a BOM.



  • @Jarry I'm glad that page linked to some external pages on templating, because that section was totally useless other than to halfass white paper templating.

    I'm reading a couple of the links now.

    This is helpful, because my code is a mess.

    Here is basically what I did.

    <doctyp...
    <html>
    <header>
    <!--- css and javascript links --->
    
    <script javascript>
    ViewModel = function()
    {
    var self = this;
    self.{all my observables, subscriptions, and computed observables}
    }
    ViewModel.prototype.{all my methods}
    
    var ViewModel = new ViewModel();
    <?php
    // code to connect to sql server
    // perform select queries
    
    foreach (thing in result)
    {
      //things is an observableArray
      echo "viewModel.things.push(new Thing(" . result["column"] . ");"
    }
    ?>
    </script>
    
    </head>
    <body>
    <!-- html and all the bindings -->
    <script javascript>
    // me being lazy and not creating a on document load method
    
    $("someSelect").select2() // because I'm lazy
    </script>
    </body>
    </html>
    

    Ok, so templating doesn't really help me in this case. A one off form won't benefit all that much.

    I'd use templating if I was designing the whole site, but this is going into WordPress site.... so.... yeah....



  • @xaade looks good.
    i'd use json_encode instead of that foreach, to avoid writing js with php, but your solution should work in a quick'n dirty way



  • @xaade said in Stuck on the posting part of a form:

    If I make something to post to, and I give it php extension. Anyone can just navigate to it, right?

    Yeah; you have to check authentication on it just like any other endpoint/templated php file.

    @xaade said in Stuck on the posting part of a form:

    I'm not exactly sure how to make an endpoint.

    You're already making endpoints that happen to return text/HTML which the browser chooses to display to the user. Normal PHP pages are endpoints.

    In this case, you'd be making an endpoint that instead returns application/json (or XML, or whatever) that returns the value "emails = success" or something similar. Then the front-end would take that value and display its success behavior as a result.

    So basically, the "consumer" of your existing endpoints is the user; they're the ones who you intend to see the results of the request. What you'll be making now is an endpoint whose "consumer" is a JavaScript method. For convenience, you'll send data to this "consumer" in a more machine-readable format. (JSON or XML.)

    Congratulations, you've just created a REST API.



  • @blakeyrat

    So instead of the endpoint having a webpage in it, the php I'm posting to just returns JSON?



  • @xaade exactly. just be careful and set the correct headers



  • @Jarry

    Ok, I'll go look for a resource on these "headers".



  • @xaade

    header('Content-Type: application/json');
    

    Put it before any output is sent. Then, yeah, instead of HTML you just output JSON.



  • @xaade said in Stuck on the posting part of a form:

    So instead of the endpoint having a webpage in it, the php I'm posting to just returns JSON?

    That's what I'd recommend.

    If you do need a version that returns a webpage (say, for people with JavaScript disabled), that would just involve splitting the business logic of sending the emails from the presentation of sending the response back to the consumer, which you're probably already doing anyway.

    @xaade said in Stuck on the posting part of a form:

    Ok, I'll go look for a resource on these "headers".

    Just ensure the Content-Type header matches the type of content you're sending. JSON is "application/json".



  • @blakeyrat said in Stuck on the posting part of a form:

    for people with JavaScript disabled

    I'd have bigger problems.... like the form not working at all.



  • @xaade Then don't worry about it, and direct anybody who complains right back to the Slashdot they came from.



  • This post is deleted!

  • Discourse touched me in a no-no place

    @ben_lubar said in Stuck on the posting part of a form:

    @xaade just skip the last ?> in the file if there's nothing after it.

    Why?

    ETA: Never mind, further posts explained the :wtf:



  • @blakeyrat wow slashdot is still alive?! I stopped going there in something like 2005.



  • @thegoryone :thatsthejoke.png:



  • @Jarry I got that part, I actually checked though and it's still alive


  • sockdevs

    @thegoryone said in Stuck on the posting part of a form:

    I stopped going there in something like 2005.

    Ah, you missed the whole Slashdot Beta debacle; the reactions of some commenters make a Blakeyrant look like the mewling of a kitten



  • @RaceProUK

    Kitten blakey amuses me.

    0_1459900041656_upload-56112010-2411-4ae5-a9d2-7c2141d12a1f



  • @ben_lubar said in Stuck on the posting part of a form:

    ?>

    Don't end your PHP scripts with that. You'll thank me later.

    It's been 8 years since I last worked with PHP, but I still remember that the PEAR standard was to never end a PHP script with ?>

    I just treated the PEAR coding standards as general guidelines even for code that wouldn't ever become a PEAR module.


Log in to reply
 

Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.