开发者

Help required in sending json to php server using POST method

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);
?> 


Your request shows "fail" because the onreadystatechange function is called multiple times with different readyStates. Here is an improved, better indented version:

request.onreadystatechange = function(){
    if (request.readyState == 4) {
        if (request.status == 200) {
            alert('http.responseText');
        } else {
            alert('fail'); // fails here
        }
    }
}

You should only check the status when readyState reached 4.

Moreover, when assigning parameters to a URL, you should use encodeURIComponent to properly encode the parameters (e.g., when sending & in a value the parser thinks it marks the beginning of a new key/value pair). And when using POST as method, you should change all instances of %20 to + per the spec and send your data as a parameter to the send function and not concatenate it to the URL:

var url = "conn_sql.php";
…
request.send("options=" + encodeURIComponent(options).replace(/%20/g, '+'));

UPDATE: To process the sent string in PHP, use json_decode, e.g.:

<?php
    $json = $_POST['options'];
    $options = json_decode($json);
    // now $options contains a PHP object
?>

(Also see How to decode a JSON String)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜