Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get JSON data from ajax call to PHP page through POST

Tags:

I want to get some data from a form making AJAX call. I am getting the data as a string in my PHP page. The string looks like

'fname':'abc','lname':'xyz','email':'','pass':'','phone':'','gender':'','dob':''

Now I want to convert this entire string into array which would look like ["fname"] => "abc", ["lname"] => "xyz"... and so on

The ajax call is like below:

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 try to convert the string into 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.

But this does not give me the required array. I have checked several answers here, but they do not solve my issue. I tried to google but did not find any resolution. Is there something wrong in the code? Kindly help. Thanks in advance.

like image 306
CoolJavaProgrammer Avatar asked Dec 20 '17 19:12

CoolJavaProgrammer


1 Answers

Change quotes and add braces. Then you can decode resulting json

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

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

result

Array
(
    [fname] => abc
    [lname] => xyz
    [email] => 
    [pass] => 
    [phone] => 
    [gender] => 
    [dob] => 
)
like image 176
splash58 Avatar answered Oct 11 '22 16:10

splash58