Asked  7 Months ago    Answers:  5   Viewed   36 times

I'm learning Ajax by failure and have hit a wall:

I have an array (if it matters, the array is storing number id's based on what checkboxes the user checks) that is written in Javascript.

I have a function that is called when the user clicks the 'save' button. The function is as follows:

function createAmenities() {
    if (window.XMLHttpRequest) {
        //code for IE7+, Firefox, Chrome and Opera
        xmlhttp = new XMLHttpRequest();
    }
    else {
        //code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById('message').innerHTML = xmlhttp.responseText;
        }
    }

    var url = "create_amenities.php";

    xmlhttp.open("GET", url, true);

    xmlhttp.send();

}

My question is: What can I put in this function to pull the array into the php script I'm trying to call ('create_amenities.php')?

furthermore, should I try using JSON? And if so, how could I send a JSON object via ajax?

Thanks in advance.

 Answers

13

If your array has more then 1 dimension or is an associative array you should use JSON.

Json turns a complete array structure into a string. This string can easily send to your php application and turned back into a php array.

More information on json: http://www.json.org/js.html

var my_array = { ... };
var json = JSON.stringify( my_array );

In php you can decode the string with json_decode:

http://www.php.net/manual/en/function.json-decode.php

var_dump(json_decode($json));
Wednesday, March 31, 2021
 
ammezie
answered 7 Months ago
73

There are three solution to this problem:

  • Call JSON.parse explicitly and pass the response text to it. The return value will be a JavaScript data type.

  • Set the dataType: 'json' option in your $.ajax call so that jQuery parses the JSON for you.

  • Set the right response headers for JSON in PHP. jQuery will detect the header and parse the JSON automatically as well.

If you want to modify the structure on the client side, have a look at Access / process (nested) objects, arrays or JSON.

Wednesday, March 31, 2021
 
Sendy
answered 7 Months ago
12

I took some liberties, and don't really understand PHP so I made up those parts. Anyway, here's what I got:

http://jsfiddle.net/zunrk/

<html>
  <head>
    <style type="text/css">

    </style>
    <script type="text/javascript">
var ids = new Array();
var use = new Array();
var ful = new Array();

ids[0] = "";
use[0] = "";
ful[0] = "";

ids[1] = 6;
use[1] = "bsmith";
ful[1] = "Buddy Smith";

ids[2] = 2;
use[2] = "lsmith";
ful[2] = "Libbie Smith";

ids[3] = 4;
use[3] = "asmith";
ful[3] = "Andy Smith";


        function Choice() {
            //x = document.getElementById("users");
            y = document.getElementById("selectUsers");

              //x.value = y.options[y.selectedIndex].text;
              document.getElementById("ids").value = ids[y.selectedIndex];
              document.getElementById("use").value = use[y.selectedIndex];
              document.getElementById("ful").value = ful[y.selectedIndex];
         }


    </script>
  </head>
  <body>
<form name="form1" method="post" action="">
<select id="selectUsers" name="users" onChange='Choice();'><option> </option>
<option value="1">bsmith</option>
<option value="2">lsmith</option>
<option value="3">asmith</option>
</select>
<p>ids <input type="text" id="ids" name="id" ></p>
<p>use <input type="text" id="use" name="username" ></p>
<p>ful <input type="text" id="ful" name="full_name" ></p>
</form>
  </body>
</html>
Wednesday, March 31, 2021
 
aaronhuisinga
answered 7 Months ago
15

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"
    }
*/
?>
Saturday, May 29, 2021
 
lena
answered 5 Months ago
99

1) $.post('url') - Ajax request is done by $.post() method and you have given "testing.php" as url which is invalid.

2) window.location = 'test.php' - This is used for redirecting to specific page and you have redirected to 'test.php' without any parameter/data. Thats why its showing "Notice: Undefined index: data"

3) Try to understand how ajax works. Follow it -

var songlist = ['song1', 'song2', 'song3'];

var sendData = function() {
  $.post('test.php', {
    data: songlist
  }, function(response) {
    console.log(response);
  });
}
sendData();
// test.php
<?php
if(isset($_POST)){
    if(isset($_POST['data'])){
    $songData = $_POST['data'];
    print_r($songData);
}}
?>
Monday, August 23, 2021
 
malrok44
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :