Reputation: 51
I can get my data to show properly from KnockOut; however, I cannot figure out a good way to get it the the PHP and have PHP prepare the data for mySQL:
From my form page I can trigger the data to display on submit, no problem:
var json = ko.utils.stringifyJson( this.Stuff );
alert("This is what I wanna save: \n" + json );
But, say I want to send it to a php file to write it to mySql--what do I do next?
ko.utils.postJson( $("form")[0], this.Stuff );
// or
$.get( "_php/savetodb.php" , json );
...And when the PHP page receives the JSON formatted data, then what?
Every solution I have seen online has basically said "you can do it." but not what it is that I would be doing.
The path I am trying ( from what I have read, this is the preferred path) is: FORM DATA -> KNOCKOUT -> ENCODE JSON -> PHP -> DECODE JSON -> MYSQL
Upvotes: 1
Views: 4214
Reputation: 51
There were some helpful answers out there-- mostly they boiled down to "Hey, why don't you read the documentation?"
For the first part where I am trying to send data to PHP via JSON I found this link helpful: [factsandpeople.com]
so the code that is working for me (well for testing) is: HTML
<form name="info" action="" method="get">
First : <input type="text" name="first" value="Sandra" size="23"><br>
Last : <input type="text" name="last" value="Grastlath" size="23"><br>
<input type="button" name="valid" value="Validate" onclick="validate()">
<div id="fullresponse"><span/></div>
<div id="sales1Lastname"><span/></div>
Next was the java script:
var data =
{
"sales": [
{ "firstname" : "John", "lastname" : "Brown" },
{ "firstname" : "Marc", "lastname" : "Johnson" }
] // end of sales array
}
function validate()
{
var p = document.forms['info'];
data['sales'].push( { "firstname" : document.forms['info']['first'].value , "lastname" : document.forms['info']['last'].value } );
var dataString = JSON.stringify(data);
$.get('parser.php', { data: dataString}, showResult, "text");
}
function showResult(res)
{
$("#fullresponse").html("<br><b>Full response: </b><br>" +res);
var obj = JSON.parse(res);
var l = obj.sales.length - 1;
$("#sales1Lastname").html("<br><b>Lastname of sales[1]: </b><br>" +obj.sales[l].lastname);
}
And now the PHP:
$logFile = 'logFile';
$req = $_REQUEST['data'];
$res = json_decode(stripslashes( $req ), true);
error_log("result: ".$req.", res=".json_encode($res), 3, $logFile);
error_log(", sales1_lastname: ".$res['sales'][1]['lastname'], 3, $logFile);
error_log("\n", 3, $logFile);
header("Content-type: text/plain");
echo json_encode($res);
?>
Like I said, this was really simple, but I am at a place now where I can at least follow all the great advice I was given... and read the documentation.
Upvotes: 4
Reputation: 7584
In your PHP you need to:
json_decode
INSERT
on your MySql Database: http://www.w3schools.com/php/php_mysql_insert.aspUpvotes: 0