简体   繁体   中英

Why is this jquery ajax call not returning data from my php script?

I'm new to jQuery, and have not been able to debug this ajax call in Firebug:

This is my ajax call:

var styndx = $('#studylist option:selected').val();
var studyname = $('#edit_field').val();


$.post("saveStudyName.php", {'type': 'update', 'studyname':studyname, 'styndx':styndx},
    function(resultmsg) {
    $('#edit_field').val('');
    $('#savebtn').attr('disabled',true);
    refresh_studynames();
});

And this is the function refresh_studynames:

function refresh_studynames()
{
  $.ajax({                                      
     url: 'getStudyNames.php',                  
     data: "",                                                             
     dataType: 'json',               
          error: function() {
            alert('Refresh of study names failed.');
          },
     success: function(data)
     {
        $data.each(data, function(val, sname) {
        $('#studylist').append( $('<option></option>').val(val).html(sname) )
      });
     } 
  });
}

Finally, this is the php script getStudyNames.php ($dbname,$dbconnect, $hostname are all populated, and $dbconnect works; the backend database is Postgres, and pg_fetch_all is a Postgres function in PHP that returns result as an array):

$dbconnect = pg_pconnect("host=".$hostname." user=".$dbuser." dbname=".$dbname);    
    if (!$dbconnect)    {
        showerror(0,"Failed to connect to database",'saveStudyName',30,"username=".$dbuser.", dbname=".$dbname);
        exit;
    }

    $sql = "SELECT ST.studyindex,ST.studyabrv AS studyname
            FROM ibg_studies ST
            ORDER BY studyname";


    $fetchresult = pg_exec($dbconnect, $sql);
    if ($fetchresult) {
        $array = pg_fetch_all($fetchresult);
        echo json_encode($array);
    } else {
        $msg = "Failure! SQL="+$sql;
        echo $msg;
    }

Any help much appreciated....

The line

$('#studylist').append( $('<option></option>').val(val).html(sname) );

looks wrong.

I'm not too sure but you could try :

var $studylist = $('#studylist').empty();
$data.each(data, function(i, record) {
    $studylist.append( $('<option/>').html(record.sname) );
});

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