1

I'm using Laravel Framework, and I'm trying to create an Ajax request, so I can send the Form data to the Controller. The thing is, I'm passing a string but in the controller, when I try JSON_decode it says that I'm giving it an array and not a string. What am I doing wrong?

View (ajax)

function getData() {
   var name = $('#name').val();
   var tin = $('#tin').val();
   var password = $('#password').val();
   var currency = $('#currency').val();

   var data = {"name": name, 'tin': tin, 'password': password, 'currency': currency};
   var obj = JSON.stringify({"name": name, 'tin': tin, 'password': password, 'currency': currency});
   console.log(obj);
   $.ajax({
      type: "POST",
      url: "teste",
      data: obj,
      success: function (result) {
        alert(result);
      }
   });
}

Controller:

 $data = $_POST;
    //$string = json_encode($data);
    $test = json_decode($data);
    echo $test->name ;
    //echo "data: $string, gravada com sucesso!";
    die;

If someone could help me...

Just solved.

$.ajax({ 
   type: "POST",
   url: "teste",
   data: {"name": name, 'tin': tin, 'password': password, 'currency': currency},
   success: function (result) {
      alert(result);
    }
});

And in the controller, I encoded and then decoded..and it worked Thanks :)

3
  • $_POST is an array, change json_decode to json_encode Commented Feb 16, 2016 at 9:58
  • it says that I'm trying to get a property of non-object Commented Feb 16, 2016 at 10:00
  • I'd just started learning laravel Commented Feb 16, 2016 at 10:02

2 Answers 2

1

No need to use JSON.stringify

Remove JSON.stringify and directly pass data

or If you want to read in json format, then

url: "1.php", data: {"key":obj},

Sign up to request clarification or add additional context in comments.

Comments

1

In your example if you want to pass json string in than you need to pass OBJ as a param:

<script type="text/javascript">
var data = {"name": name, 'tin': tin, 'password': password, 'currency': currency};
var obj = JSON.stringify({"name": name, 'tin': tin, 'password': password, 'currency': currency});

$.ajax({
type: "POST",
url: "<?=g('base_url')?>home/index",
data: "obj="+obj, // add as a param
success: function (result) {
alert(result);
}
});
</script>

In PHP, you can get object in $_POST as:

$data = $_POST['obj'];
$test = json_decode($data);
echo $test->name;

UPDATE:

Second solution you have already updated in your question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.