I have my form defined as follows in the PHP file :
<form id = "testForm" action="" method="post" >
First name: <input type="text" name="FirstName" id="FirstName" value="Mickey"><br>
Last name: <input type="text" name="LastName" id="LastName" value="Mouse"><br>
<button type = "button" onclick="submit()">Submit Top Test </button>
</form>
The following functions is called when the button is clicked.
function submit(){
var formdata = $("#testForm").serializeArray();
var sendJson = JSON.stringify(formdata);
var request = $.ajax({
url: 'php/<path to php file>/processPost.php',
type:'POST',
data:{myData:sendJson},
success: function(msg) {
alert(msg);
},
error: function(e){
alert("Error in Ajax "+e.message);
}
});
}
In processPost.php
file, I have defined the following :
1) $json_obj = json_encode($_POST["myData"]);
2) var_dump($json_obj);
To define the above PHP stuff, I used the answer posted by Akhan Ismailov
with just a minor change(instead of json_decode
, I am using
json_encode
)
I can see the following getting printed in the alert(msg)
window.
string(93) ""[{\"name\":\"FirstName\",\"value\":\"Mickey\"},{\"name\":\"LastName\",\"value\":\"Mouse\"}]""
I plan on making a curl request to my java webservice and I want to send JSON something like this :
[{
"name": "FirstName",
"value": "Mickey"
}, {
"name": "LastName",
"value": "Mouse"
}]
How can I get rid of string(93)
and forward slashes /
from the above code to make it a valid json first. Once, I have
a valid json, I am planning on sending it as an object using cURL.