Problem with Ajax and php

Asked

Viewed 139 times

1

I’m doing a test with ajax and php, but it’s returning a value nothing to see

test2.html

<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <script src="jquery-3.3.1.min.js"></script>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div>
            Nome: <input type="text" name="nome">
            <input type="button" value="Enviar" onclick="enviar(name.valueOf())">
            <p id="abc"> </p>
        </div>
        <script>
            function enviar(nome) {
                $.ajax({
                    url: "teste2.php",
                    type: "POST",
                    data: "nome=" + nome,
                    dataType: "html"

                }).done(function (resposta) {
                    console.log(resposta);


                }).fail(function () {
                    console.log("Falha");

                }).always(function () {
                    console.log("Ok");
                });
            }
        </script>
    </body>
</html>

teste2.php

<?php

if($_POST){
    $vlr = $_POST['nome'];

    if($vlr == 'Leandro'){
        return true;
    } else {
        return false;
    }
}

comes this back:

<br />
<font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined variable: nome in C:\wamp64\www\php_pdo\projeto\teste2.php on line <i>6</i></th></tr>
<tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
<tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
<tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.4036</td><td bgcolor='#eeeeec' align='right'>403528</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp64\www\php_pdo\projeto\teste2.php' bgcolor='#eeeeec'>...\teste2.php<b>:</b>0</td></tr>
</table></font>

One more question, how to put the result in the paragraph (below the input)? I tried document.getElementyId("abc").innerHTML = resposta;, but gives the error that document.getElementyId is not a function.

  • The right thing is document.getElementById("abc").innerHTML = resposta;.. see the difference to getElementyId. As for the return of Ajax, it is returning an error generated by the requested PHP page.

  • Teste2.php only has this content shown?

  • Yes, there is only this code in teste2.php

2 answers

1


The way you’re doing it, the variable nome in the data: Ajax is going empty for PHP, causing error.

The first problem observed was this value: name.valueOf(). The name is a global variable of window, has nothing to do with what you want to go through. Could do nome.valueOf().value SINCE THE input had a id="nome". You could even change the name="nome" for id="nome" since you will use Ajax.

But I would suggest that you take the value of input within the function enviar() instead of passing as parameter, leaving only onclick="enviar()" on the button.

In the function, using jQuery, you would take the value of the input for name with:

var nome = $("[name='nome']").val(); or var nome = $("input[name='nome']").val();.

Your HTML and script would be:

<div>
   Nome: <input type="text" name="nome">
   <input type="button" value="Enviar" onclick="enviar()">
   <p id="abc"> </p>
</div>
<script>
function enviar() {

    var nome = $("[name='nome']").val();

    $.ajax({
        url: "teste2.php",
        type: "POST",
        data: "nome=" + nome,
        dataType: "html"

    }).done(function (resposta) {
        console.log(resposta);
        if(resposta == "true"){
           console.log("correto");
        }else{
           console.log("errado");
        }


    }).fail(function () {
        console.log("Falha");

    }).always(function () {
        console.log("Ok");
    });
}
</script>

Regarding PHP, these returns are incorrect, with this, the return of Ajax by the variable resposta will come empty. You need to make a echo in PHP to return something. You could do:

<?php
if($_POST){
    $vlr = $_POST['nome'];

    if($vlr == 'Leandro'){
        echo "true";
    } else {
        echo "false";
    }
}
?>

And in Ajax check through a if if the return is the string "true" or "false" (not to be confused with boolean true and false. You expect to receive a PHP string). Instead of returning "true" or "false", you could use any strings, for example, "certo" and "errado", "valido" and "invalido" etc., this is up to you.

As to the document.getElementyId, is syntax error. Correct is document.getElementById. Lacked a "B" before the "y".

  • Just one question, is always going to the else in ajax, and continues to show the same return on the island (the one I quoted in the question)

  • You copied exactly the code I put in the answer?

  • Yeah, I even copied it again to check, but it’s still the same

  • I’ve done it, and the return remains the same.

  • I found out he’s showing that random code on console.log(resposta)

  • I put the value that is passed by ajax in a $_SESSION, and the value I entered is being passed correctly

  • I took the comments from the code, and it’s working.. I decoded the console.log(resposta), and is showing the return of PHP. I really can’t understand the problem, but it worked. Thank you!

  • Phew! Good :D

  • Sam, you can take a look at this: https://gist.github.com/LeTarzan/f9fabf3338df78d11570b3750c1fe763 is the same problem, but I’m having trouble on the way..

  • Dude, I don’t know a lot about these controllers and no htacess. Maybe if I asked a new question someone who knows about this could help.

Show 5 more comments

-1

I took the liberty of tweaking the code a little bit

    <html>
<head>
    <title>TODO supply a title</title>
    <meta charset="UTF-8">
    <script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>
    <form id="form" method="post" action="action.php">
        <label> Nome:
            <input type="text" name="nome">
        </label>
        <input type="submit" value="Enviar">
        <br/>
        <span id="result"></span>
    </form>
</div>
<script>
    $("#form").submit(function (e) {
        e.preventDefault();

        var form = $(this);
        var url = form.attr('action');
        let ajax =  $.ajax({
            type: "POST",
            url: url,
            data: form.serialize(),

        });
    ajax.done(function (result) {
        $('#result').html(result)
    }) ;

});

php action.

if ($_POST) {

    $vlr = isset($_POST['nome']) ? $_POST['nome']  : "";

    if($vlr == 'Leandro'){
        $result =  "Nome válido";
    } else {
        $result  = "Nome inválido";
    }


}

echo $result;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.