mardi 3 mars 2015

Inserting a database record from an HTML form with jQuery + AJAX

Inserting a database record from an HTML form with jQuery + AJAX is what I'm trying to do but it doesn't seem to work for me.


The HTML looks like this:



<form method="post" id="message-form">
<textarea id="new-message" name="message" placeholder="Nieuw bericht"></textarea>
<input type="hidden" id="message-sender" name="sender" value="<?=$_SESSION["user_id"]?>">
<input type="hidden" id="message-recipient" name="recipient" value="<?=$aConversationPartner["id"]?>">
<input type="submit" name="submit-message" id="send-message" value="Verstuur bericht">
</form>


The jQuery code looks like this:



$("#send-message").click(function (e) {
e.preventDefault();
if($("#new-message").val()==='')
{
alert("Uw bericht is leeg!");
return false;
}

var myData = 'message='+ $("#new-message").val() + '&sender=' + $("#message-sender").val() + '&recipient=' + $("#message-recipient").val(); //build a post data structure
jQuery.ajax({
type: "POST",
url: "sendmessage.php",
dataType:"text",
data:myData,
success:function(response){

console.log("great succes");

}
});
});


sendmessage.php looks like this:



<?

require_once("config.php");
require_once("lib.php");

sendMessage($_POST["sender"], $_POST["recipient"], $_POST["message"], 1);

?>


The sendMessage php function works perfectly if I use it without AJAX so that wouldn't be the problem. What is very weird though is that I don't get any console errors at all and the console.log("great succes"); is fired. I'm new to jQuery + AJAX and desperate for an answer. Please give me an answer I can understand and implement.


Aucun commentaire:

Enregistrer un commentaire