Enregistrer des données dans une table mysql via ajax

Par barpoi78, il y a 5 ans


Bonjour,

J'essai d'insérer des données dans une table mysql via ajax et cela ne fonctionne pas alors je fais:

$(".frmComment").submit(function() { $.ajax({ method: "POST", url"../content/insertComment.php", data: $(".frmComment").serialize(), }) .done(function() { $(".return").html("<link rel='stylesheet' type='text/css' href='../content/bootstrap-5.0.0-alpha3-dist/css/bootstrap.min.css'><p class='alert-success p-3 rounded text-center col-lg-4'>Votre commentaire a bien été enregistré !</p>") }) return false; });

Mon php fonctionnel:

<?php require_once '../controller/dbConfig.php'; if (isset($_POST['myComment'])) { $myComment = $_POST['myComment']; } if (isset($_POST['regComment']) && $_POST['myComment']) { $stmt3 = $conn->prepare('UPDATE demandes SET myComment = ? WHERE demande_id = ?'); $stmt3->bind_param('si', $_POST['myComment'], $_POST['hidden_demande_id']); $stmt3->execute(); $stmt3->close(); }

Mon formulaire:

<form action="" method="POST" name="frmComment" class="frmComment" id="frmComment"> <input type="hidden" name="hidden_demande_id" value="<?php echo $demande_id; ?>"> <div class="col"> <textarea class="col-lg-4 mb-1 myComment" name="myComment" id="myComment"></textarea> </div> <div class="col"> <button class="btn btn-secondary float-left" type="submit" name="regComment" id="regComment">Enregistrer</button> </div> </form>

Je précise que mon php fonctionne bien et enregistre bien mes données dans ma table si je ne passe pas par ajax.

Je vous remercie de votre aide

3 réponses

HarryMazza, il y a 5 ans

Vous devez créer un fichier php qui insérera les données publiées dans votre table et l'appellera avec ajax comme ceci:

$ .ajax ({
url: "/file.php",
tapez: "POST",
cache: faux,
dataType: "json",
données: postValue,
succès: fonction (résultats) {
ici tu mets ta fonction thetermpapers
});
},
erreur: fonction (résultats) {
bootbox.alert (results.message, function () {
bootbox.setIcons (null);
});
}

Pierrot01, il y a 5 ans

note sur la fonction sérialise de jquery

"Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized."

donc :

data: $(".frmComment").serialize() + "&nomdetonbouton=true,

a+

Pierre

barpoi78, il y a 5 ans

Merci, tout fonctionne.