Problem with Ajax and php

1

I'm doing a test with ajax and php, however 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>

test2.php

<?php

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

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

This comes 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, as per the result in the paragraph (below the input)? I have tried document.getElementyId("abc").innerHTML = resposta; , but the error that document.getElementyId is not a function.

    
asked by anonymous 31.07.2018 / 04:10

2 answers

1

As you are doing, the variable nome in data: of Ajax is going empty for PHP, causing the error.

The first problem observed was this value: name.valueOf() . name is a global variable of window , it has nothing to do with what you want to pass. It could make nome.valueOf().value since input had id="nome" . You could even change name="nome" to id="nome" since you're going to use Ajax.

But I suggested that you take the value of input inside the enviar() pend function instead of passing as a parameter, leaving only onclick="enviar()" on the button.

In the function, using jQuery, you would get the value of input by name with:

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

Your HTML and script would stay:

<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 return s are incorrect, so the return of Ajax with the resposta variable will be empty. You need to 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 confuse with booleans true and false . expects 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 at your discretion.

  

As for document.getElementyId , it is syntax error. The correct is    document.getElementById . There was a " B " before " y ".

    
31.07.2018 / 05:17
-1

I took the liberty of messing around in the code

    <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)
    }) ;

});

action.php

if ($_POST) {

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

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


}

echo $result;
    
31.07.2018 / 05:08