1

this is a noob question.

my javascript function(part of knockout.js model that I have defined):

self.loadData = function(){
        alert("loadData got called");
        $.ajax({
            url: 'database_connection.php',
            dataType: 'json',
            success: function(data){    //json string of records returned from server
                alert('success from server call');              

            },
            error: function(){
                alert('error from server call');            
            }

        });
    };

Contents of database_connection.php:

<?php
    echo "this is called";
    $db = new MySqli('localhost', 'username', 'password', 'database');
    $activities = $db->query("SELECT * FROM MainActivity");
    $activities_r = array();

    while($row = $activities->fetch_array()){
        $val = $row['mActivityID'];
        $act = $row['Name'];

        $activities_r[] = array('val'=>$val, 'act' => $act);
        }

        echo json_encode($activities_r);

?>

The php is correct, coz if I directly access this file through browser, it correctly displays the result from database table.

However, when executed through the loadData function, I get two alerts: 1. "loadData is called" 2. "error from server call"

the first line of database_connection.php is not being executed since I cant see the result of echo, so that means the script is not getting called.

Am I using the ajax function wrongly?

Tuhina Singh
  • 927
  • 2
  • 10
  • 19
  • the way you are using the ajax function looks fine. are you sure that `database_connection.php` can be called like that as a relative part from where you are actually calling the loadData function? – Timothy Groote Sep 28 '15 at 07:17
  • http://stackoverflow.com/questions/4064444/returning-json-from-a-php-script – Dan Belden Sep 28 '15 at 07:17
  • 1
    @DanBelden i'm not sure that will help OP answer his question. – Timothy Groote Sep 28 '15 at 07:19
  • Did you check network call? – syms Sep 28 '15 at 07:19
  • another way to figure out what is going wrong is to properly implement your error function : `Function( jqXHR jqXHR, String textStatus, String errorThrown )` and place a breakpoint in it, or `alert` or `console.log` the variables. – Timothy Groote Sep 28 '15 at 07:19
  • Use firebug console to look which data is coming – Ali Mehdi Sep 28 '15 at 07:19
  • @syms He is not returning the correct headers for one - which would indicate the content type of the response to the JS client. Secondly, I also believe there is an issue in the JS success method (Too many closing braces)? – Dan Belden Sep 28 '15 at 07:21
  • @Den Belden yeah right there is one extra closing brace. – syms Sep 28 '15 at 07:23
  • Don't you think there is one extra } after success – Sunil Pachlangia Sep 28 '15 at 07:24
  • 1
    you missing `type` in ajax call . try clarifying which kind of request it is GET,POST & a typo `sucess` callback which should be `success`.. – super cool Sep 28 '15 at 08:32
  • Hi, sorry for late response. Typo in word `success` was there which I corrected. Thanks @supercool . The extra brace seen here in code for `success` however, was a typo specific to this page when I deleted some irrelevant code. Thanks for pointing that out @Dan @syms @sunil – Tuhina Singh Sep 29 '15 at 07:27

3 Answers3

2

Your AJAX request contains:

dataType: "json"

This means that if server returns invalid JSON with a 200 OK status then jQuery fires the error function

Use the following code to ensure the reponse is JSON format.. (PHP vsersion)

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

Note : empty response is also considered invalid JSON; you could return {} or null which validate as JSON

Shailendra Sharma
  • 6,976
  • 2
  • 28
  • 48
1

you need to add headers in php file, because your data type is json in ajax call.

header('Content-Type: application/json');
echo json_encode($activities_r);
Noman
  • 4,088
  • 1
  • 21
  • 36
  • Tried this out. I still get error call in loadData function. However, now when I open the php file directly from browser, I get this error: `Warning: Cannot modify header information - headers already sent by (output started at /path/to/file/database_connection.php:2)` – Tuhina Singh Sep 29 '15 at 07:33
0

You need to set the type of your request and may be remove dataType. Also in the success callback it was one extra bracket. Check it :

self.loadData = function(){
    alert("loadData got called");
    $.ajax({
        url: 'database_connection.php',
        type : 'GET',
        // dataType: 'json',
        sucess: function(data){     //json string of records returned from server
            alert('success from server call');              

        },
        error: function(){
            alert('error from server call');            
        }

    });
};
MysterX
  • 2,318
  • 1
  • 12
  • 11
  • Tried this out. The good news is I get `success` from server call. Unfortunately, I am encountering two issues now: 1. This goes into infinite loop. As soon as I press `ok` button for `success` message, it pops up again. Have to force quit the browser to end this infinite loop. 2. The data this page is getting is empty. [I only have two lines in the table I am trying to access.] – Tuhina Singh Sep 29 '15 at 07:37