idelara
idelara

Reputation: 1816

Fetching JSON data from a php file with jQuery's $.ajax( ) function does not work

I am trying to understand the magic of the .ajax() function with jQuery. I am having a hard time getting what I want to be done. I basically want a div with content that refreshes every x time (about every 10 seconds). Mainly, this will output the latest posts that have been posted to a table in my database. Pretty much I am using this example to get an idea of how I can achieve my goal, but unfortunately I am not getting what I want.

I am trying to set my file so that when the refresh button is clicked, the div refreshes and brings up the latest posts.

On one side we have the index.php file:

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <title>Test page</title>
</head>
<body>
    <h1>Welcome to the form</h1>
    <h2>We are going to try to process this with AJAX</h2>
    <h3>I hope it works!</h3>
    <div id="content"></div>
    <button id="refresh>Refresh!</button>
    <script type="text/javascript">


    $('#refresh').on('click', function(){
        $.ajax({
            type: "POST",
            url: "process.php",
            data: ,     
            error: function(data){
                $('#content').text('Update unsuccessful!').
                slideDown('slow');
                console.log(data);
            },
            success: function(data){
                $('#content').text('Update completed!');
                console.log(data);
                        //somewhere over here use the $.getJSON() function
            },
            complete: function(data){
                setTimeout(function(){
                    $('#content').slideUp('slow');
                }, 3000);
            }
        });

      });



    </script>   
</body>
</html>

And on the other hand, we have the process.php file that queries the results from the database:

$dbhost = "localhost";

$dbname = "test";

$dbuser = "root";

$dbpass = "root";

$db = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

$sth = $db->query("SELECT * FROM posts");

$sth->setFetchMode(PDO::FETCH_ASSOC); 

echo json_encode($sth);

Do you have any idea of how to accomplish this?

To structure my results, I want to use something like this inside the success part of my jQuery code:

    $('#outputdiv').html(
       //html code here fetching the JSON data to appear within custom divs (so I can  apply css styles to them)

);

Also, do you know how can I automatize the div to bring new results using the same &.ajax() function every x time? I have read the documentation throughly and followed many examples, but I still cant get what I want!

Thanks in advance!

Cheers!


Edits: -Fixed the echo json_encode, the "process.php", erased the data: line, and put the passing (data) into the success: error: and complete: areas and still doesnt work

Upvotes: 0

Views: 2037

Answers (4)

kuldeep.kamboj
kuldeep.kamboj

Reputation: 2606

Well I think you need PDO fetch after setFetchMode. Also Its better to use send JSON Response headers in Ajax request

$data = array();
while ($row = $sth->fetch()) {
   $data[] = $row;
}

header('Content-type: application/json');

echo json_encode($data); 

Upvotes: 0

Sohil Desai
Sohil Desai

Reputation: 2988

first url should be string type so it would look like this

url: "process.php",

then in process.php file echo your result like this

echo json_encode($sth);

and in your error, success functions add an parameter like this

error: function(data){
    //your code
},
success: function(data){
    //your code
}

also your variable form_data is not needed according to your code. so remove this line

data: form_data,

Upvotes: 1

Anthony Chu
Anthony Chu

Reputation: 37540

3 things...

url: process.php should be url: "process.php"

form_data isn't really defined anywhere

success: function(){ should be success: function (data) {

Upvotes: 0

nes
nes

Reputation: 1106

Your success function must take data argument.

And i recommend you to read about $.getJSON shortcut for this case.

Upvotes: 1

Related Questions