简体   繁体   中英

I've tried to some the ajax request but it won't work

I am trying to make a request to 'inserir.php' that's where I'm going to process the data from the ajax request and insert it to the database. But when I click the button nothing happens.. Not even an error. This is my form.. :

<div class="modal-body">
                    <!-- FORM-->
                    <form method="POST" id="formulariopost">
                        <div class="form-group">
                            <label for="exampleInputEmail1" style="font-family: Arial, Helvetica, sans-serif;">Email</label>
                            <input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Email" style="font-family: Arial, Helvetica, sans-serif;" required>
                            <small id="emailHelp" class="form-text text-muted" style="font-family: Arial, Helvetica, sans-serif;">Nunca vamos partilhar o seu email com mais ninguem.</small>
                        </div>
                        <div class="form-group">
                            <label for="exampleInputPassword1" style="font-family: Arial, Helvetica, sans-serif;">Nome da Equipa</label>
                            <input type="text" class="form-control" id="nome_equipa" placeholder="Nome da Equipa" style="font-family: Arial, Helvetica, sans-serif;" required>
                        </div>
                        <div class="form-group">
                            <label for="exampleInputPassword1" style="font-family: Arial, Helvetica, sans-serif;">Nickname dos jogadores</label>
                            <input type="text" class="form-control" id="nickname" placeholder="(GAMETAG)" style="font-family: Arial, Helvetica, sans-serif;" required>
                        </div>
                        <div class="form-group">
                            <label for="exampleInputPassword1" style="font-family: Arial, Helvetica, sans-serif;">Numero do whatsapp</label>
                            <input type="text" class="form-control" id="numero" placeholder="Numero do whatsapp" style="font-family: Arial, Helvetica, sans-serif;" maxlength="15" data-mask="(00) 00000-0000" required>
                        </div>
                        <button id="enviar" class="btn btn-secondary" >Close</button>
                        <!--<button type="submit" class="btn btn-primary" style="font-family: Arial, Helvetica, sans-serif;margin-bottom: 30px;float: right;">Submit</button>-->
                    </form>
                    <br>
                    <!--PAYPAL-->
                    <div id="paypal-button-container"></div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="saveg">Save changes</button>
                </div>
            </div>

This is my javascript:

$(document).ready(function() {

        $('#saveg').click(function(e){

            e.preventDefault();

            var email = $("#email").val();
            var nome_equipa = $("#nome_equipa").val();
            var gametag = $("#nickname").val();
            var numerowhats = $("#numero").val();


            $.ajax({
                type: "POST",
                url: "inserir.php",
                dataType: "json",
                data: {email:email, nome_equipa:nome_equipa, nickname:nickname, numero:numero},
                success : function(data){
                    if (data.code == "200"){
                        alert("Success: " +data.msg);
                    } else {
                        console.log('mona');
                    }
                }
            });


        });
    });

And this is my php where I want to make the ajax request:

    $servername = "localhost";
$username = "root";
$password = "root";
$dbname = "copacobre";


$email = $_POST["email"];
$nome_equipa = $_POST["nome_equipa"];
$gametag = $_POST["nickname"];
$numerowhats = $_POST["numero"];
$newURL="/copac/#";
echo $email;

$errorMSG = "error test";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$sql = "INSERT INTO pagamentos (email, nome_equipa, gametag, numerowhats)
VALUES ('".$email."', '".$nome_equipa."', '".$gametag."', ".$numerowhats.")";



$conn->close();

echo json_encode(array('code' => 200));

Looks the event binding is wrong. You need to bind to the submit event.

Also in your HTML code, the submit button is for close, and a regular button is assigned to Save Changes, usually submit is to perform the action of submit the data and continue.

JQuery submit documentation

if should be something like

$('#formulariopost').submit(function(e){
    ....
})

and remember at the end of the function, you should return true in case it was successful, or false to cancel the event.

There can be many reasons why event is not binded. You can try to debug it in few steps.

Clear cache

Yes, browsers loves caching. Make sure you have actual version of JS file loaded in your page.

If you are using Chrome, CTRL+F5 will do the job.

Check how far code goes

Add breakpoints in Developer Tools console or - easy way - some console.logs to few points in code - eg after document.ready, after button click, before ajax request and into ajax success. Don't forgot AJAX can also return with error code, and the method 'success' can't handle error responses.

Depending on how far code gets (eg using console.logs) you can determine where the problem is. If you can't see log right behind document.ready, there is probably some problem with including file.

Debug AJAX

Check if AJAX request was sent and what was the response. You can do this in Developer Tools in Networking tab. You can see request and response body, so it can help you determine where the problem is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM