views:

119

answers:

1

I am trying to send json data from an HTML form back to php server via a POST method. Here is my code. It goes to fail block in callback function. Firebug console(ctrl+shift+J) displays no error.

<script> 
function ADDLISITEM(form)
{ 
var options = form.txtInput.value;
options = JSON.stringify(options);
var url = "conn_mysql.php"
var request = null;
request = new XMLHttpRequest();
request.open("POST", url, true);
request.onreadystatechange = function(){
    if (request.readyState == 4) {
            if (request.status == 200) {
                alert(request.responseText);
        } else {
            alert(request.status); 
        }
    }
}
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send("options=" + encodeURIComponent(options).replace(/%20/g, '+'));
}
</script>

conn_mysql.php

<?php  
    $json = $_POST['options'];
    $options = json_decode($json);
    $username = "user";  
    $password = "********";  
    $hostname = "localhost";  
    $dbh = mysql_connect($hostname, $username, $password) or die("Unable to 
    connect to MySQL");  
    $selected = mysql_select_db("spec",$dbh) or die("Could not select first_test");
    $query1 = "INSERT INTO user_spec (options) VALUES ('$options')";
    mysql_query($query1);
    //if(!mysql_query($query1, $dbh))
    //{die('error:' .mysql_error());} echo'success';
    $query = "SELECT * FROM user_spec";  
    $result=mysql_query($query);     
    $outArray = array(); 
     if ($result)
     { 
       while ($row = mysql_fetch_assoc($result)) $outArray[] = $row; 
     } 
      echo json_encode($outArray);
?>