skip to Main Content

I have existing PHP that accepts arrays as parameters. This is currently being invoked from javascript and the javascript array is being set directly as part of the data object sent through AJAX call to the php.

Now, I want to send an array from an Android app and I don’t want to change the existing php and javascript. I have looked for an answer, but don’t see anything, other than the suggestion to encode the array as JSON and decode it in the php, but that will require lots of changes everywhere, including the javascript. It appears the javascript and the php are made to just work. Maybe something is done automatically to the array?

The PHP looks like this:

foreach($_POST as $key => $value) {
  if (is_array($_POST[$key])){
     for ($index = 0; $index < count($_POST[$key]); $index++){
          if(ini_get('magic_quotes_gpc'))
            $_POST[$key][$index] = stripslashes($_POST[$key][$index]);

          $_POST[$key][$index] = htmlspecialchars(strip_tags($_POST[$key][$index]));
     }
  }
  else {
      if(ini_get('magic_quotes_gpc'))
        $_POST[$key] = stripslashes($_POST[$key]);

      $_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
  }
}

So, it is definitely expecting some parameters to be arrays.

The javascript currently does this:

        $.ajax({
            type: "POST",
            url: 'php/getLibraryPatterns.php',
            dataType: 'json',
            data: data,

and data is a javascript object with arrays contained in it. For example:

        var data = {};
        if (sortBy.length > 0){
            data.sortBy = sortBy;
        }

and sortBy is an array in the javascript.

How do I pass an array from the Android app to this php? Currently, all of the parameters for my other calls to php have just been simple strings, so I use the following function to put all the parameters together in a string and then write that to the OutputStream of my HttpURLConnection. I have that all working, just not sure what to do with the arrays?

    private String buildParameterString() throws UnsupportedEncodingException
    {
        if (m_parameterMap == null) return "";
        StringBuilder result = new StringBuilder();
        boolean first = true;

        Iterator<Map.Entry<String, String>> itr = m_parameterMap.entrySet().iterator();

        while(itr.hasNext())
        {
            Map.Entry<String, String> param = itr.next();
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(param.getValue(), "UTF-8"));
        }
        return result.toString();
    }

I tried creating a JSONArray with the data, then convert to string and set it just like I would set the other strings I am sending. But, this does not appear to work, at least not automagically.

So, I am sending something like "[29]" or "[‘sortAsc’]" as strings in the parameters.
I got back an empty list. I will continue to debug in the php to see what those look like there, but I expect they will be just strings and the php won’t know what to do with that.

So, how can I send an array to the php? I don’t want to have to change the php, as that means that the javascript then also has to change. Is there any way to do this from a java Android app?

Solution Found!
I found an answer in the JQuery documentation for ajax method. It says there that arrays are encoded like this:

%5B is ‘[‘
and %5D is ‘]’
For example, { a: [1,2] } becomes the string "a%5B%5D=1&a%5B%5D=2" with the default traditional: false setting.
I have encoded my arrays like that in the string that I write to the output stream. From https://api.jquery.com/jQuery.ajax/

Here is the code I am using to create my output stream:

    private String buildParameterString() throws UnsupportedEncodingException
{
    if (m_parameterMap == null || m_parameterMap.size() == 0) return "";
    StringBuilder result = new StringBuilder();


    for (int iPair = 0; iPair < m_parameterMap.size(); iPair++)
    {
        Pair<String, Object> param = m_parameterMap.get(iPair);
        if (iPair > 0) result.append("&");

        Object value = param.second;
        if (value instanceof ArrayList){
            for (int i = 0; i < ((ArrayList)value).size(); i++){
                Object nextValue = ((ArrayList)value).get(i);
                String nextValueStr = "";
                if (nextValue instanceof String){
                    nextValueStr = (String)nextValue;
                }
                else {
                    nextValueStr = Integer.toString((Integer)nextValue);
                }
                if (i > 0) result.append("&");
                result.append(URLEncoder.encode(param.first, "UTF-8"));
                result.append("%5B%5D=");
                result.append(URLEncoder.encode(nextValueStr, "UTF-8"));
            }
        }
        else {
            result.append(URLEncoder.encode(param.first, "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode((String)value, "UTF-8"));
        }
    }
    return result.toString();
}

m_parameters is an ArrayList of Pair’s where Pair is in android.util.

It works, this is the answer. You don’t have to encode and decode in JSON string to do this. All the othere answers I have seen for this are just that. There is a way to encode the array into the string output.

2

Answers


  1. Try this:

    Outside of while loop:

    JSONArray data = new JSONArray();
    

    And put this in while loop:

    JSONObject jsonObjSend = new JSONObject();
    jsonObjSend.put(param.getKey(), param.getValue());
    data.put(jsonObjSend);
    
    Login or Signup to reply.
  2. From Android, send it as json data

      public String convertMapToJson() {
        Map<String, String> elements = new HashMap<>();
        elements.put("Key1", "Value1");
        elements.put("Key2", "Value2");
        elements.put("Key3", "Value3");
    
        JSONObject json = new JSONObject(elements);
        return json.toString();
    }
    

    In server side PHP,

    $json = file_get_contents('php://input');
    
    // Converts it into a PHP object
    $params = json_decode($json, true);
    echo $params["Key1"];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search