0

I have a web site that has all of the error messages displaying in a "div" at the top of the page. I need to change the code so that the errors display as alerts instead, but I can't figure out how to get the timing correct.

I've created a more simplified example of what I'm trying to do.

I want the following to happen:

  1. User types a letter into the "letter" input.
  2. User clicks a submit button.
  3. The form posts and the PHP code checks what letter was typed and sets a variable ($fruit).
  4. The HTML re-renders, and if the variable ($fruit) has a value, it is placed in the "fruit" input. (The purpose here is to put the result in a place Javascript can get to it.)
  5. The Javascript then executes and displays an alert showing the contents of the "fruit" input.

Here is the Javascript:

/* myTestScripts.js */



$(document).ready(function() {

window.onsubmit = function (e) {
  e.preventDefault();
  alert($("#fruit").val());
};

});

And here is my index.php file:

<!DOCTYPE html>

<head>
    <!-- Style for Zebra Dialog boxes -->
    <link rel="stylesheet" href="zebra/zebra_dialog.css" type="text/css"> 
</head>

<header>
    <h1>Testing My Dialogs and Alerts</h1>
</header>

<body>

    <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $user_input = trim($_POST["letter"]);

        if ($user_input == 'A') {
            $fruit = "apples";
        } elseif ($user_input == 'B') {
            $fruit = "bananas";
        } else {
            $fruit = "No fruit for you!";
        }
    }
    ?>

    <form id="form_to_submit" action="index.php" method="POST">

        <fieldset>
            <label>Type A for apples and B for bananas:</label>
            <input type="text" name="letter" id="letter"> 
            <input type="text" name="fruit" id="fruit" value="<?php if(isset($fruit)) {echo $fruit;} ?>"> 
            <button type="submit" id="click">Click Here to see your fruit selection.</button>
        </fieldset>

    </form>

<!-- Link to jQuery file so any plug-ins can work 
Including the production version here.  Can also download one for better debugging.  -->
<script type="text/javascript" src="jquery-1.12.0.min.js"></script>

<!-- Link to My Javascript code -->
<script type="text/javascript" src="myTestScripts.js"></script>

</body> 

Am I going about this the wrong way?

THREE DAYS LATER....

OK it seems like everyone is telling me to go with AJAX. So I've been watching tutorials and I get the general idea, but I'm confused about the URL I should pass.

Here is my updated Javascript: (It's a big wordy, but I'm trying to code this to get it clear in my head.)

/* myTestScripts.js */

function sendAjax() {

  // Use ajax short-hand for 'get'
  $.ajax({
      type: "POST",                                                   // Post vs Get
      url: "index.php",                                               // url
      context: $('#letter').val()                                     // data
    }).done(function() {                                              // callback function
      alert("Here is your fruit: " + $('#fruit').val());              // Show alert based on data here
    });
}

$('#theButton').bind('click', sendAjax);

This only works party. It does not update the "fruit" input, so it doesn't display it in the alert either.

If my PHP code that processes this info is inside my "index.php" file, is THAT the URL I pass in? Or do I have to take all the processing code OUT of index.php, save it as a separate file, and pass THAT NEW file in?

1

5 Answers 5

1

window.onsubmit() fires when the form is submitted, but before the data is sent to the server. If you want to generate the alert after the page has returned from the server based on the input value you're filling with php, you can do something like this:

$(document).ready(function() {
  if($('#fruit').val() != '') {
    alert($('#fruit').val());
  };
});

This isn't necessarily the best way to handle the situation (as others point out), but I believe it's the most direct answer to what you're asking.

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

3 Comments

That TOTALLY works! And I would REALLY REALLY like to run with this and just be done with it, but am I going to be sorry later that I didn't code it with Ajax instead?
Without knowing the scope and context of what you're doing, and the environment you're doing it in, it's hard to say. If you're learning, it would be good to understand the different roads you could take to reach your desired destination. Just using what you posted here, everything could be done in javascript without the need for php (Barthy's response -- you don't show any need to send the data to the server), and the removal of a round trip back to the server is better from a user experience standpoint.
Well, in my actual web site I am displaying data from the server, or information about what happened on the server side. ("Thank you for accepting this assignment! The coordinator will receive an email with your information.") That kind of thing and validation. ("No such user name was found. Please try again.") I did a tutorial last summer on Ajax and at the time it seemed overwhelming with everything else I was learning. So emotionally I'm resistant to doing it that way. On the other hand, I don't want to have to come back and code up my alerts a third time.
1

How can you get your php POST code to run BEFORE your Javascript code?

Your PHP code ever runs before as your javascript does except using ajax.

In your case you just want to display something in an alert. If I understand you you have to store the variable which contains the "error" and echo into a javascript variable.

Of course the following lines should be in the same php file.

<script type="text/javascript">
 var error = "<?php echo $error; ?>";
 alert(error);
</script>

1 Comment

I think you meant "ever run" => "never runs".
1

A more standard and flexible pattern is to separate the PHP that is to be done with an ajax request as its own file not directly inside the HTML.

So lets create an ajax endpoint

my-ajax-endpoint.php

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $user_input = trim($_POST["letter"]);

    if ($user_input == 'A') {
        $fruit = "apples";
    } elseif ($user_input == 'B') {
        $fruit = "bananas";
    } else {
        $fruit = "No fruit for you!";
    }
    echo json_encode(array("fruit" => $fruit)); // encode as json
}

Now we have an HTML form that we want to handle with an ajax request using jQuery.

The form we are acting on

<form id="form_to_submit" action="my-ajax-endpoint.php" method="POST">
    <fieldset>
        <label>Type A for apples and B for bananas:</label>
        <input type="text" name="letter" id="letter"> 
        <input type="text" name="fruit" id="fruit"> 
        <button type="submit" id="click">Click Here to see your fruit selection.</button>
    </fieldset>
</form>

We hook in into the forms onsubmit method

Ajax hook for form submit

$("#form_to_submit").submit(function (evt) {
  evt.preventDefault();
  var $form = $(this); // the form we are acting on
  // xhr is a defered object
  var xhr = $.ajax({
    url: $form.attr('action'), // the url of the action
    data: $form.serialize(), // send all the form fields
    method: $form.attr('method') // POST or GET
  });

  // handle the data
  xhr.done(function (data) {
    // find the fruit field and store the fruit value
    $form.find("[name=fruit]").val(data.fruit);
    alert("Your fruit: " + data.fruit);
  });

  // handle HTTP errors
  xhr.fail(function (jqXHR, textStatus) {
    alert("Error: " + textStatus);
  });

});

This is a flexible pattern that you can use with many different use cases. You can pass back more data with json_encode() using an associative array. Using $form.find("[name=youinput]") will easily allow you to update form elements.

1 Comment

This seems like the way to go and very helpful. But I may need a day to come to terms with the fact that I have to rework my architecture. I thought adding in the dialogs would be an afternoon of work and it's turned into a lot more. That's how these things go!
0

Well, that's not how you should approach this problem...

I believe that what you trying to achieve can simply be done with Ajax.

I like to work with jQuery to make Ajax calls, here is an example:

$.ajax({
  url: "test.html",
  context: yourFormFields
}).done(function() {
  $( this ).addClass( "done" );
});

If you want to know more: http://api.jquery.com/jquery.ajax/

Comments

0

I would suggest doing this all in jQuery/Client Side.

Note: this does not answer your question, it's just a suggestion.

This way, you don't need to reload the page.

Add an onClick listener to the submit button and use preventDefault to prevent the submission. Then do the check and insert the result into input:

$('#click').click(function(event){
    event.preventDefault();
    var letter = $('#letter').val(),
        fruit = "No fruit for you!";
    switch(letter){
        case 'A':
            fruit = 'Apple';
            break;
        case 'B':
            fruit = 'Banana';
            break;
    }
    $('#fruit').val(fruit);
});

4 Comments

If the op is not going to submit to post then they need to change the submit button to just a button with an onclick event. preventDefault is depreciated and will eventually fail over time. In a real world application Doctype HTML's way of doing it is the preferred way, Unless youre into Ajax...
event.preventDefault is deprecated. Is it? I don't see anything in the docs, and Google doesn't give me any result that points that way...
@Danimal that's ridiculous to say preventDefault() is deprecated. Cite your source
Sorry. I had a bit of programmer blur there. I read preventDefault() but in my mind was thinking getPreventDefault(). preventDefault is not depreciated.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.