Get JSON data from ajax call to PHP page via POST

I want to get some data from an AJAX invocation form. I get data as a string in my PHP page. The line looks like

'FName': 'ABC', 'LName': 'hoog', 'email': '', 'pass':' ',' phone ':' ',' gender ':' ',' DOB ':' ''

Now I want to convert this whole string to an array that will look like ["fname"] => "abc", ["lname"] => "xyz" ... etc.

The ajax call is as follows:

fname = $("#form-fname").val();
lname = $("#form-lname").val();
email = $("#form-username").val();
pwd = $("#form-password").val();
phone = $("#form-phone").val();
gender = $("#form-gender").val();
dob = $("#form-dob").val();
var user = {"fname":fname,"lname":lname,"email":email,"pass":pwd,"phone":phone,"gender":gender,"dob":dob};
$.ajax({
      type: "POST",
      url: "doRegistration.php",
      data: user
 })
 .done(function( msg ) {                        
       window.location.href = "../profile.php";
 })
 .fail(function(msg) {
       sessionStorage.setItem("success","0");
       window.location.reload();
 }); 

And here is my PHP code:

$content = file_get_contents("php://input");
file_put_contents("log1.txt",$content); //This produces the string I get above

Now I am trying to convert a string to an array as above

$dec = explode(",",$content);
$dec1 = array();
for($i=0;$i<count($dec);$i++)
{
    $dec1[i] = substr($dec[i],strpos($dec[i],":"));
}
//After this $dec1 is empty and count($dec1) gives 0.

. , . Google, . - ? . .

+4
2

. json

$string = "'fname':'abc','lname':'xyz','email':'','pass':'','phone':'','gender':'','dob':''";

print_r(json_decode('{' . str_replace("'", '"', $string) . '}', true));

Array
(
    [fname] => abc
    [lname] => xyz
    [email] => 
    [pass] => 
    [phone] => 
    [gender] => 
    [dob] => 
)
+4

for . ( , Java). :

<?php
$string = "'fname':'abc','lname':'xyz','email':'','pass':'','phone':'','gender':'','dob':''";
$pieces=explode(',',$string);
foreach($pieces as $array_format){
list($key,$value) = explode(':',$array_format);
$array[$key]=$value;
}
0

Source: https://habr.com/ru/post/1691137/


All Articles