skip to Main Content

Now I am upgrading my website user experience, so I’m trying modify my form from form action to ajax.
Coding now work fine, server side can update the database, but I don’t know how to return the custom message to my user.

My html coding.

<form method="post" id="jnfarm_pop">
    blablabla...
    <button type="submit" class="layui-btn layui-btn-fluid" name="submitbutn" onclick="login();">submit</button>
</form>

My php file plugin.php

<?php
  //coding.....
  $final = 'custom wording';
  return json_encode(['final' => $final]);
?>

My jQuery

<script>
function login() {
    jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result) => {
        alert($final); //it doesn't work
    }).fail(result => {
       alert('fail');
    });
    event.preventDefault();
}
</script>

Now the alert doesn’t work, I am also try like

jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result) => {
    result = JSON.parse(result); alert(result.final); //not working also
}

and

jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result = JSON.parse(result)) => {
     alert(result.final); //this show alert unidentified
}

Can someone correct my coding?

2

Answers


  1. Change

    return json_encode(['final' => $final]);
    

    to

    echo json_encode(['final' => $final]); 
    

    return is really only useful when you’re inside a PHP function. If you want to output something back to the caller of the script then you need to use echo, as always.

    Login or Signup to reply.
  2. To make your example work do the following:

    change your PHP code from

    <?php
      //coding.....
      $final = 'custom wording';
      return json_encode(['final' => $final]);
    ?>
    

    to:

    <?php
      //coding.....
      $final = 'custom wording';
      echo json_encode(['final' => $final]);
    ?>
    

    and your jQuery code from this:

    <script>
    function login() {
        jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result) => {
            alert($final); //it doesn't work
        }).fail(result => {
           alert('fail');
        });
        event.preventDefault();
    }
    </script>
    

    to this:

    <script>
    function login() {
        jQuery.get('plugin.php?id=cc&do=dd', jQuery('#jnfarm_pop').serialize(), (result) => {
            alert(result);
        }).fail(result => {
           alert('fail');
        });
        event.preventDefault();
    }
    </script>
    

    PHP can return something to an ajax call by either printing or echoing. And ajax can’t use variables you defined in PHP. The echo’ed value in your PHP script will be the result value in your ajax call.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search