1

I need to pass a two objects and a string as post parameters to php.

This is how my code is now:

var obj1 = {'a':'b', 'c':'d'};

var obj2 = {'e':'f', 'g':'h'};

var url = 'hello';

dataParams = { 
    object1: obj1,
    object2: obj2,
    url: url
}
$.ajax({
    url: '/sample.php',
    dataType: 'json',
    method: 'POST',
    data: dataParams
});

In sample.php

echo $_POST['url'] gives hello
echo $_POST['object1'] or json_decode($_POST['object1']) gives null.
echo $_POST['object2'] or json_decode($_POST['object2']) gives null.

What is wrong with the code?

9
  • 1
    similar post that might help you stackoverflow.com/questions/14265826/… Commented Mar 20, 2014 at 11:16
  • 2
    In your post there's a simple error, you don't close ' after object1 and object2. Try to print $_POST and analyze the output Commented Mar 20, 2014 at 11:17
  • 1
    have you tried var_dump($_POST) in your php sacript to see what json sends you? Commented Mar 20, 2014 at 11:19
  • 2
    Would you mind posting whole code? because i can't see 'url' in the object that you have passed as 'data'. Commented Mar 20, 2014 at 11:21
  • @gafreax it just has the url property Commented Mar 20, 2014 at 11:27

2 Answers 2

2

Thanks for all ur quick responses.

In my code I am populating the obj1 and obj2 from the DOM input fields. I have initialized them as arrays instead of objects.

obj1 = [] instead of obj1 ={}

After making that change, its working fine.

Thanks

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

Comments

2

You are using

method = 'POST'

when it should be:

type: 'POST'

Also, echo $_POST['object1'] will return 'Array'! If you want to see the values, use print_r($_POST['object1']), ok? ;)

10 Comments

BTW, why are you using DataType? Are you going to return a json object ?
I have to return a json object in future. But even after removing the dataType property its not working
try running the JSON.stringify also on the dataParams, or enclose object1 and object2 in '', that should do the trick!
BTW: echo $_POST['object1'] will return 'Array'! If you want to see the values, you need to do print_r($_POST['object1']), ok?
I have just tested the code, and it works fine! This is what I did: <!DOCTYPE html> <html> <head> <title>Test</title> <script src="http://code.jquery.com/jquery-1.11.0.js"></script> <script> var obj1 = {'a':'b', 'c':'d'}; var obj2 = {'e':'f', 'g':'h'}; var url = 'hello'; dataParams = { object1: obj1, object2: obj2, url: url } $.ajax({ url: 'http://localhost/test.php', dataType: 'text', type: 'POST', data: dataParams, success: function(data){ alert(data); } }); </script> </head> <body> </body> </html>
|

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.