John Arellano John Arellano - 1 year ago 94
Javascript Question

Sending data from knockout to php

I created a login function

self.login = function() {
var credentials = {
pass: self.pass()
var data = ko.toJS(credentials);
url: 'client/scripts/pages/login/login.php',
type: 'post',
data: {data: data},
contentType: 'application/json',
success: function (result) {

This will send request to php file when the form is submitted.
Here is the login.php code,

$data = json_decode($_POST['data']);
return $data['email'];

When i execute this, the result is Undefined index: data

I tried JSON.strignify but it is not working. how can I get the email of the user in php?

Answer Source

I'm using the following code:

Client-side (JS):

    type: "POST",
    async: async,
    url: dataServiceBaseUrl + "request.php", //
    data: {
        "jsonrpc": "2.0",
        "method": method,
        "dbname": dbName,
        "params": JSON.stringify(params)
    success: function(data) {
        var obj = JSON.parse(data);
    error: function() {

Server-side (PHP):

function process_request() {
    $dbname = $_POST["dbname"];
    $method = $_POST["method"];
    $params = json_decode($_POST["params"], true);
    $result = call_user_func_array("methods::" .  $method, $params);
    return json_encode(array("jsonrpc" => "2.0", "result" => $result, "error" => null, "usename"=>$usename));

Of course,

var data = ko.toJS(credentials);

is necessary to get serializable data to sent.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download