简体   繁体   中英

Ajax, add to database and update div content

Okay, so I am trying to use ajax. I've tried several ways of doing this but nothing is working for me. I believe the main problem I have is that ajax won't add to my database, the rest is managable for me.

Here is the relevant ajax-code:

$(document).ready(function(){
console.log($("going to attach submit to:","form[name='threadForm']"));
$("form[name='threadForm']").on("submit",function(e){
    e.preventDefault();
    var message = $("#message").val();
   //assumming validate_post returns true of false(y)
   if(!validatepost(message)){
       console.log("invalid, do not post");
       return;
   }
   console.log("submitting threadForm");
   update_post(message);
});
});

function update_post(message){
    var dataString = "message=" + message;
    alert(dataString);

    $.ajax({
        url: 'post_process.php',
        async: true,
        data: dataString ,
        type: 'post',
        success: function() {
            posts();
        }
    });
 }

 function posts(){
     console.log("getting url:",sessionStorage.page);
     $.get(sessionStorage.page,function(data){
         $("#threads").html(data);
     });
 }

 function validatepost(text){
     $(document).ready(function(){

    var y = $.trim(text);
    if (y==null || y=="") {
        alert("String is empty");
        return false;
    } else {
        return true;
    }
    }); 
  }

Here is the post_process.php:

<?php
    // Contains sessionStart and the db-connection
require_once "include/bootstrap.php";   

$message = $con->real_escape_string($_POST["message"]); 

if (validateEmpty($message)){
    send();
}

function send(){
    global $con, $message;

    $con->create_post($_SESSION['username'], $_SESSION['category'], $_SESSION("subject"), $message);
}

//header("Location: index.php");
?>

And lastly, here is the html-form:

<div id="post_div">
<form name="threadForm" method="POST" action="">
    <label for="message">Meddelande</label><br>
    <textarea id="message" name="message" id="message" maxlength="500">

    </textarea><br>
    <input type="submit" value="Skicka!" name="post_btn" id="post_btn"><br>
</form>

create_post is a function I've written, it and everything else worked fine until I introduced ajax.

As it is now, none of the console.log:S are getting reached.

Ajax works when jumping between pages on the website but the code above literally does nothing right now. And also, it works if I put post_process.php as the form action and don't comment out the header in post_process-php.

I apologize for forgetting some info. I am tired and just want this to work.

I would first test the update_post by removing the button.submit.onclick and making the form.onsubmit=return update_post. If that is successful place the validate_post in the update_post as a condition, if( !validate_post(this) ){ return false;}

If it's not successful then the problem is in the php.

You also call posts() to do what looks like what $.get would do. You could simply call $.get in the ajax return. I'm not clear what you are trying to accomplish in the "posts" function.

First you can just submit the form to PHP and see if PHP does what it's supposed to do. If so then try to submit using JavaScript:

$("form[name='threadForm']").on("submit",function(e){
  e.preventDefault();
  //assumming validate_post returns true of false(y)
  if(!validate_post()){
    console.log("invalid, do not post");
    return;
  }
  console.log("submitting threadForm");
  update_post();
});

Press F12 in Chrome or firefox with the firebug plugin installed and see if there are any errors. The POST should show in the console as well so you can inspect what's posted. Note that console.log causes an error in IE when you don't have the console opened (press F12 to open), you should remove the logs if you want to support IE.

Your function posts could use jQuery as well as it makes the code shorter:

function posts(){
  console.log("getting url:",sessionStorage.page);
  $.get(sessionStorage.page,function(data){
    $("#threads").html(data);
  });
}

UPDATE

Can you console log if the form is found when you attach the event listener to it?

console.log($("going to attach submit to:","form[name='threadForm']"));
$("form[name='threadForm']").on("submit",function(e){
   ....

Then set the action of the form to google.com or something to see if the form gets submitted (it should not if the code works). Then check out the console to see the xhr request and see if there are any errors in the request/responses.

Looking at your code it seems you got the post ajax request wrong.

function update_post(message){ console.log(message);

$.ajax({
    url: 'post_process.php',
    async: true,
    //data could be a string but I guess it has to
    // be a valid POST or GET string (escape message)
    // easier to just let jQuery handle this one
    data: {message:message} ,
    type: 'post',
    success: function() {
        posts();
    }
});

UPDATE

Something is wrong with your binding to the submit event. Here is an example how it can be done:

<!DOCTYPE html>
<html>
  <head>
    <script src="the jquery library"></script>
  </head>
  <body>
<form name="threadForm" method="POST" action="http://www.google.com">
    <label for="message">Meddelande</label><br>
    <textarea id="message" name="message" id="message" maxlength="500">
    </textarea><br>
    <input type="submit" value="Skicka!" name="post_btn" id="post_btn"><br>
</form>
      <script>
$("form[name='threadForm']").on("submit",function(e){
  e.preventDefault();
  console.log("message is:",$("#message").val());
});   
      </script>
  </body>
</html>

Even with message having 2 id properties (you should remove one) it works fine, the form is not submitted. Maybe your html is invalid or you are not attaching the event handler but looking at your updated question I think you got how to use document.ready wrong, in my example I don't need to use document.ready because the script accesses the form after the html is loaded, if the script was before the html code that defines the form you should use document ready.

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