简体   繁体   中英

cannot pass a javascript object to php via ajax

I've created a new array in javascript and I'm adding values to it indexes from a function an then passing the array to the ajaxCall function were I try to convert it to json and send it to a php file via ajax, but the variable json is allways empty. I've been reading a lot about how to send javascript objects json_encoded via ajax and looks like this is the way to do it, but obviously I haven't readed enought or there is something I've been missing. Anycase I'm newbie in javascript and any help would be apreciated.

    function createArray()
    {
        var advancedFormVars = new Array();
        advancedFormVars['checkbox1'] = document.getElementById('OfferID').value;  
        advancedFormVars['checkbox2'] =document.getElementById('offerName').value;

    AjaxCall(advancedFormVars);
    }
    function AjaxCall(advancedFormVars){
    var json = new Array();
    json = JSON.stringify(advancedFormVars); //in debuger it shows me this as content of json variable--> [] but advancedFormVars is not empty

$.ajax({
        url : 'AL_loadForm.php',
        type : 'POST',
        data : {
            json : json 
        },
        dataType:'json',
        success : function(data) {
            alert(data);
    }
...

If all you have are two smaller arguments, I'd keep it simple and make an http get request. Encode your arguments if neccessary.

var url = "http://wherever.com/something.php?arg1=";
url += document.getElementById('OfferID').value;
url += "&arg2=" + document.getElementById('offerName').value;
httpGetAsync(url, returnMethod);

function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() { 
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
        callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous 
xmlHttp.send(null);
}

You are trying to use your array as a hash, so the values are not being set..

Instead of setting

var advancedFormVars = new Array();

Try setting

var advancedFormVars = {};

Example

JS:

var advancedFormVars = {};
advancedFormVars['checkbox1'] = 'valueA';
advancedFormVars['checkbox2'] = 'valueB';

var json = JSON.stringify(advancedFormVars);

console.log(json); //{"checkbox1":"valueA","checkbox2":"valueB"}

PHP

<?php
$json = '{"checkbox1":"valueA","checkbox2":"valueB"}';
$obj = json_decode($json);
var_dump($obj);
/*
    object(stdClass)#1 (2) {
      ["checkbox1"]=>
        string(6) "valueA"
      ["checkbox2"]=>
        string(6) "valueB"
    }
*/
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM