1

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.

Coder
  • 6,381
  • 2
  • 9
  • 10
  • The `string(93)` is coming from `var_dump()` -- it's not actually in the JSON string. – Alex Howansky Mar 20 '18 at 20:45
  • `var sendJson = JSON.stringify(formdata);` this line is unnecessary. direct use `data:formdata`, and then at php side print `$_POST` and see all data is coming or not – Alive to die - Anant Mar 20 '18 at 20:46
  • @AlivetoDie Yes, that worked for me. When I just used `echo $_POST["myData"];`, I saw what I was looking for. – Coder Mar 20 '18 at 20:55

3 Answers3

1

$_POST["myData"] is already JSON so you don't have to do anything

$json =  $_POST["myData"];
call_my_web_service($json);
Musa
  • 96,336
  • 17
  • 118
  • 137
1
var sendJson = JSON.stringify(formdata);

This line is unnecessary.

direct use

data:formdata,

and then at php side print $_POST and see all data is coming or not

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
1

$_POST['myData'] is already JSON, since you used JSON.stringify() to create it. You need to use json_decode() to decode it, not json_encode().

$obj = json_decode($_POST['myData'], true);
var_dump($obj);
Barmar
  • 741,623
  • 53
  • 500
  • 612