Question

I'm trying to get data from user and insert it into database, then again fetch all new data from same database and prepend to content box. All is fine, i'm getting only wanted data. But when I write post and click submit button it insert data in database but don't prepend new data. But when i write again a new post and click submit, it prepend the "last post" means it is working with 1 click delay. I tried to check with console.log, i'm getting perfect data on first click as well as 2nd click. So what is the issue in this code which restricting it to add data on first time? ( i don't know the title of problem -_- so if anyone can correct, please do )

$(document).ready(function() {
$("#submit").click(function(e){
    e.preventDefault();
    var post = $("#s-content").val();
    post = $.trim(post);
    if (post=="")
    {
        $("#status-warning").show(100);setTimeout(function(){$("#status-warning").hide(100)},3000);
    }
    else
    {
        $.ajax({
            type:"POST",
            url:"process/post.php",
            data:$("#post").serialize(),
            cache:false,
            success: function(data){
                var request = $.ajax({
                        type:"GET",
                    url:"process/getNewPost.php?id=<?php echo $_SESSION['id']."&token=".session_id(); ?>",
                    /*success:function(data){
                        $("#all-posts").prepend(data);
                        console.log(data);
                        }*/
                    });
                    request.done(function(check){
                        console.log(check);
                        $("#all-posts").prepend(check);
                    });

                /*var a=''; 
                a += '<div><li style="white-space:pre;">';
                a += $("#s-content").val();
                a += '</li></div>';
                $("#all-posts").prepend(check);*/
                $("#s-content").val("");
                $("#remove").remove();
        });
    }
});
});
Was it helpful?

Solution

I'm not sure if it is the cause of your problem, but your solution is needlessly complicated.

  1. You don't need to make 2 ajax requests. You already have the variables available in javascript so you can use these to modify your #all-posts section in the success function of your first ajax call. Even if you don't have everything available, you should have process/post.php return it and not make a new request to the server.
  2. You don't need to add session variables to your url. Just start the session in php and you will have them all available. Although this probably does not matter any more as the second ajax call is innecessary.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top