skip to Main Content

I have some difficulties to understand how to build a set of data values that I can use in an Ajax call (using jQuery). I have a function that generates some data values that I want to use in the Ajax call. In the code below I have simplified the get_data function to just return a string of data entries:

// get_data() will return a string:
// --> stringA: 'This is A', stringB: 'This is B', stringC: 'This is C'
function get_data() {
    var data = "";
    data += "stringA: 'This is A',";
    data += "stringB: 'This is B',";
    data += "stringC: 'This is C'";
    return data;
}

var my_variables = get_data();

$.ajax({
        url: "my_ajax_handler.php",
        data: {
            firstString: "Hello World!", 
            my_variables  // I would like this to expand to: stringA: 'This is A', stringB: 'This...etc'
        },
        type: "POST",
        success: function(result){ 
            document.write(result);
        }
    });

This will obviously not work, since the my_variables is a clean string and won’t be treated as three separate data values. In the my_ajax_handler I have the following code:

<?php
echo "<pre>";
print_r($_POST);
echo "</pre>";
?>

This will result in the following output:

Array
(
    [firstString] => Hello World!
    [my_variables] => stringA: 'This is A',stringB: 'This is B',stringC: 'This is C'
)

I.e. the data values are treated as one single string. What do I need to do to get the following output?

Array
(
    [firstString] => Hello World!
    [stringA] => This is A
    [stringB] => This is B
    [stringC] => This is C
)

2

Answers


  1. try to use this:

    function get_data(data) {
        data['stringA'] = "This is A";
        data['stringB'] = "This is B";
        data['stringC'] = "This is C";
        return data;
    }
    
    var myPostData = {};
    
    myPostData['firstString'] = "Hello World!";
    myPostData = get_data(myPostData);
    
    $.ajax({
        url: "my_ajax_handler.php",
        data: myPostData,
        type: "POST",
        success: function(result){
            document.write(result);
        }
    });
    
    Login or Signup to reply.
  2. I think the best solution is to send the data this way, any value within a cell in an array

    function get_data() {
       var data = [];
        data['stringA'] = 'This is A';
        data['stringB'] = 'This is B';
        data['stringC'] = 'This is C';
        return data;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search