Jump to content

[SOLVED] Adding an Array as a parameter


xtopolis

Recommended Posts

I'm trying to use code from "Javascript Pro Techniques" in order to send an array via POST to a page, I'm just having trouble with the syntax I think.  There are two functions involved, ajax and serialize.  Don't let all the code scare you, the bottom two blocks are for further reference only.

 

example of "ajax":  (works if I remove the third {} line from params:

        window.onload = function(){
            // Then load the RSS feed using AJAX
            ajax({
                // The URL of the HTML sports scores
                url: "test.php",

                // It's an HTML document
                type: "POST",
                
                params: [
                  {name: 'name', value: 'Chris'},
                  {name: 'age', value: '21'},
                  {name: 'checks', value: ['Cake','Pie']}// <-- needs to become an array
                ],

            });//ajax
        };//onload

This sends vars as &name=Chris&age=21

 

serialize()

// SERIALIZE ----------------------------------------------------------
// takes an array or object
function serialize(a){
  var s = [];
  
  if( (typeof a) === 'undefined' ){
    return '';
  }else if( a.constructor == Array  ){
    //set name = value for all pairs
    for( var i=0; i < a.length; i++ ){
      s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
    }
  }else{
    for( var j in a ){
      s.push( j + "=" + encodeURIComponent( a[j] ) );
    }
  }
  
  return s.join("&");
}

 

 

So how can I add an array to the params property?  I thought it would be something like {name: 'checks', value: ['Cake','Pie']}    , but that returns it as ["checks"]=>  string( 8 ) "Cake,Pie".

 

 

 

 

Full code for reference: (note test.php, the target, only has "var_dump($_POST)")

test.html

<html>
<head>
    <title>Loaded via AJAX</title>
    <!—Load in our generic AJAX function -->
    <script src="ajax.js"></script>
    <script>
        // Wait for the document to be fully loaded
        window.onload = function(){
            // Then load the RSS feed using AJAX
            ajax({
                // The URL of the HTML sports scores
                url: "test.php",

                // It's an HTML document
                type: "POST",
                
                params: [
                  {name: 'name', value: 'Chris'},
                  {name: 'age', value: '21'},
                  {name: 'checks', value: ['Cake','Pie']}              
                ],

                // This function will be executed whenever the request is complete
                onSuccess: function( html ) {
                    // We're going to be inserting into the div that has an id of 'scores'
                    var scores = document.getElementById("scores");

                    // Inject the new HTML into the document
                    scores.innerHTML = html;
                }
            });
        };
    </script>
</head>
<body>
    <h1>Loaded via AJAX </h1>
    <div id="scores"></div>
</body>
</html>

 

ajax.js (includes other functions like serialize)

// XMLHTTPREQUESTOBJECT -----------------------------------------------
function XMLHRO(){
  try { return new XMLHttpRequest(); } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
  try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
  alert("XMLHttpRequest not supported");
  return null;
}

// SERIALIZE ----------------------------------------------------------
// takes an array or object
function serialize(a){
  var s = [];
  
  if( (typeof a) === 'undefined' ){
    return '';
  }else if( a.constructor == Array  ){
    //set name = value for all pairs
    for( var i=0; i < a.length; i++ ){
      s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
    }
  }else{
    for( var j in a ){
      s.push( j + "=" + encodeURIComponent( a[j] ) );
    }
  }
  
  return s.join("&");
}
// A generic function for performming AJAX requests
// It takes one argument, which is an object that contains a set of options
// All of which are outline in the comments, below
function ajax( options ) {
    // Load the options object with defaults, if no
    // values were provided by the user
    options = {
        // The type of HTTP Request
        type: options.type || "POST",

        // The URL the request will be made to
        url: options.url || "",
        
        params: serialize(options.params),

        // How long to wait before considering the request to be a timeout
        timeout: options.timeout || 5000,

        // Functions to call when the request fails, succeeds,
        // or completes (either fail or succeed)
        onComplete: options.onComplete || function(){},
        onError: options.onError || function(){},
        onSuccess: options.onSuccess || function(){},

        // The data type that'll be returned from the server
        // the default is simply to determine what data was returned from the
        // and act accordingly.
        data: options.data || ""
    };

    if(options.type == "POST") { options.url = options.url + "?";}
    
    // Create the request object
    var xml = new XMLHRO();

    // Open the asynchronous POST request
    xml.open(options.type, options.url, true);

      //post method?
      if(options.type == "POST"){
        xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xml.setRequestHeader("Content-length", options.params.length);
        xml.setRequestHeader("Connection", "close");
      }

    // We're going to wait for a request for 5 seconds, before giving up
    var timeoutLength = 5000;

    // Keep track of when the request has been succesfully completed
    var requestDone = false;

    // Initalize a callback which will fire 5 seconds from now, cancelling
    // the request (if it has not already occurred).
    setTimeout(function(){
         requestDone = true;
    }, timeoutLength);

    // Watch for when the state of the document gets updated
    xml.onreadystatechange = function(){
        // Wait until the data is fully loaded,
        // and make sure that the request hasn't already timed out
        if ( xml.readyState == 4 && !requestDone ) {

            // Check to see if the request was successful
            if ( httpSuccess( xml ) ) {

                // Execute the success callback with the data returned from the server
                options.onSuccess( httpData( xml, options.type ) );

            // Otherwise, an error occurred, so execute the error callback
            } else {
                options.onError();
            }

            // Call the completion callback
            options.onComplete();

            // Clean up after ourselves, to avoid memory leaks
            xml = null;
        }
    };

    // Establish the connection to the server
    xml.send(options.params);

    // Determine the success of the HTTP response
    function httpSuccess(r) {
        try {
            // If no server status is provided, and we're actually 
            // requesting a local file, then it was successful
            return !r.status && location.protocol == "file:" ||

                // Any status in the 200 range is good
                ( r.status >= 200 && r.status < 300 ) ||

                // Successful if the document has not been modified
                r.status == 304 ||

                // Safari returns an empty status if the file has not been modified
                navigator.userAgent.indexOf("Safari") >= 0 && typeof r.status == "undefined";
        } catch(e){}

        // If checking the status failed, then assume that the request failed too
        return false;
    }

    // Extract the correct data from the HTTP response
    function httpData(r,type) {
        // Get the content-type header
        var ct = r.getResponseHeader("content-type");

        // If no default type was provided, determine if some
        // form of XML was returned from the server
        var data = !type && ct && ct.indexOf("xml") >= 0;

        // Get the XML Document object if XML was returned from
        // the server, otherwise return the text contents returned by the server
        data = type == "xml" || data ? r.responseXML : r.responseText;

        // If the specified type is "script", execute the returned text
        // response as if it was JavaScript
        if ( type == "script" )
            eval.call( window, data );

        // Return the response data (either an XML Document or a text string)
        return data;
    }

}

Link to comment
Share on other sites

The raw POST header needs to look like:

 

checks[]=Cake&checks[]=Pie

 

 

So, you need to figure out how to make the code you are using do that.

 

 

You could try:

 

params: [

                  {name: 'name', value: 'Chris'},

                  {name: 'age', value: '21'},

                  {name: 'checks[]', value: 'Cake'}// <-- needs to become an array

                  {name: 'checks[]', value: 'Pie'}// <-- needs to become an array

                ],

 

Or:

 

                  {name: 'checks[0]', value: 'Cake'}// <-- needs to become an array

                  {name: 'checks[1]', value: 'Pie'}// <-- needs to become an array

 

 

But glancing at the serialize function, I'm not sure either of those will work.  You could always just modify the code to handle an array in the value variable.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.