1

I am trying to write some data in a mysql database with jquery and ajax. The query works successfully but I am unable to append the data in a div array.

EDITED:

$(document).ready(function(){

    $("#sub").click( function() {
      $.ajax({
            type: "POST",
            url:  "insert.php", 
            dataType: 'json',
            data: $("#myForm :input").serializeArray(),
            success: function(data) { 
                data = $.parseJSON(data);
                $("#data").append("<div class=\"row\">"
                           +data.position+"  "   //this section must be changed to 
                           +data.text+"  "       // something but I dont know what
                           +data.id+"  "
                           +data.date_added+"  "
                           +"</div>"); 
            },
            error:function (xhr, ajaxOptions, thrownError){
            $("#error").html(thrownError);
            }
     })
     return false;
    });

    //disable form redirection
    $("#myForm").submit( function() {
      return false; 
    });

    //clear input fields
    function clearInput() {
    $("#myForm :input").each( function() {
       $(data).val('');
    });
    }

    update();


}); 

function update() {
     $.ajax({
            type: "POST",
            url:  "fetch.php", 
            dataType: 'json',
            success: function(data) {
                $.each(data, function(){
                    $("#data").append("<div class=\"row\">"
                                       +this['position']+"  "
                                       +this['text']+"  "
                                       +this['id']+"  "
                                       +this['date_added']+"  "+
                                      "</div>");

                })
            },
            error:function (xhr, ajaxOptions, thrownError){
            $("#error").html(thrownError);
            }
     });
     return false;
};

How I am going to show the data posted AFTER the query was successful ?

EDIT:

<body>
        <div class="navbar navbar-inverse">
          <div class="navbar-inner noRadius">
            <a class="brand" href="#">toDo</a>
            <ul class="nav">
              <li class="active"><a href="#">Home</a></li>
              <li><a href="#">Home</a></li>
            </ul>
          </div>
        </div>

        <div id="main" class="container">

        <div id="data"> </div>

            <form id="myForm" action="insert.php" method="post">
                Task: <input class="input-large" type="text" name="text" />
                <br />
                <button class="btn" id="sub">Save</button>
            </form>

            <span id="error"></span>

        </div>

        <!-- Including our scripts -->
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
        <script type="text/javascript" src="script.js"></script>

        <link href="library/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
        <script src="library/js/bootstrap.min.js"></script>
        <!--<script src="library/js/ajaxy.js"></script>-->

    </body>

fetch.php

<?php
    include_once('db.php');


    $sql = mysql_query("SELECT * FROM todo");
    $tasks = array();

    while( $row = mysql_fetch_assoc($sql) ){
        $tasks[] = $row;
    }

    echo json_encode($tasks);
?>

insert.php

<?php

    include_once('db.php');

    $text = $_POST['text'];
    $query=mysql_query("INSERT INTO todo(text) VALUES('$text')");
    if($query){
        echo "Data for $text inserted successfully!";
        }
    else{ 
        echo "An error occurred!"; 
        }

?>

I am trying to build a simple todo application.

I updated insert.php because I was going to insert data into the db with select. I am a beginner and I am trying hard ! Please help me unstuck !

3
  • 1
    move the append inside the post callback (function(data){.....) Commented Jul 19, 2013 at 20:26
  • We would need to know the response format and what you want to show from it. Also it seems that you are already showing the response inside the #result element, does that display correctly (as expected)? Commented Jul 19, 2013 at 20:27
  • yes, it does display but not what I am posting. Commented Jul 19, 2013 at 20:46

2 Answers 2

1

Move the append to inside the success callback.. AJAX is asynchronous. SO the way you have written the code , the data object is being accessed before the response is populated with the data. So any processing that is to be handled on the response object much be moved to success callback.

$("#sub").click( function() {
      $.post( $("#myForm").attr("action"), 
              $("#myForm :input").serializeArray(), 
              function(data) { 

               $("#result").html(data);
               $("#data").append("<div class=\"row\">"
                           +data[0]+"  "   //this section must be changed to 
                           +data[1]+"  "   // something but I don't know what
                           +data[2]+"  "
                           +data[3]+"  "
                           +"</div>");
      });
});

And the this[0] should be data[0] assuming that the response is in the form of an array.

It might change based on the response that you expect.

Sign up to request clarification or add additional context in comments.

13 Comments

i get a "S u c c " message, what should that mean ?
Open the console in developer tools and paste how the response looks like
it says "Successfully Inserted" so it makes sense , but I have no idea where this message comes from . I am going to post the rest of the files.
I did a little mistake with the wrong file and corrected it. Now I am getting the first characters of the json array: [ { " i
Just reading won't help in any way unless you keep using it :) .. It is the same with everyone out there
|
0

I needed to echo json data from a SELECT after persisting data to the database

if($query){
        $data=mysql_query("SELECT * FROM todo WHERE text = '$text'");
        $tasks[]=mysql_fetch_assoc($data);
        echo json_encode($tasks);
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.