php - Can't print the json from ajax post using json_decode -
php - Can't print the json from ajax post using json_decode -
i using ajax post info php script work done... basically, i'm taking form variabes, , creating json... taking json , sending controller script:
function createjson() { jsonobj = []; $("input[class=form-control]").each(function() { var id = $(this).attr("id"); var value = $(this).val(); item = {} item [id] = value; jsonobj.push(item); }); jsondata = json.stringify(jsonobj); var request = $.ajax({ url: "../../../../ajax/signupcontroller.php", type: "post", data: jsondata, datatype: "html" }); request.done(function( msg ) { console.log(msg); }); request.fail(function( jqxhr, textstatus ) { alert( "request failed: " + textstatus ); }); }
my code gets php script fine, , when utilize "print_r" in php print output, this:
array ( [0] => stdclass object ( [mail-firstname] => fname ) [1] => stdclass object ( [mail-lastname] => lname ) )
my problem is, can't @ elements... have tried:
$data = json_decode(file_get_contents('php://input')); foreach ($data $key => $value) { print "<p>$key | $value</p>"; }
but can't @ array elements... error... missing accessing array after decoding file contents?
thanks.
update:
modified foreach:
foreach($data $key=>$value){ print $value->ccyear;//now can @ individual elements }
but value has dash causing script fail... example, if name "mail-firstname" php thinks it's mail service , firstname...
the problem values nested level in data. , each have different keys, it's hard @ them. improve if utilize id
keys of top-level array, rather nesting them:
jsonobj = {}; $("input[class=form-control]").each(function() { var id = this.id var value = this.value; jsonobj[id] = value; });
then should alter php utilize sec argument json_decode()
, associative array instead of stdclass
object:
$data = json_decode(file_get_contents('php://input', true));
i'm not sure why need send json. why not use:
data: jsonobj;
then can access inputs $_post['mail-firstname']
, etc.
php jquery ajax json
Comments
Post a Comment