Declare variables in loop and pass the values throgh GET request?

Hi All,

here’s a part of my JS code which supposed to get some elements by id and my first problem is how to declare the variables inside the loop (num_of_users is a variable)


num_of_users = encodeURI(document.getElementById('num_of_users').value);
	for (var i=2;i<=num_of_users;i++)
	{
		username_2 = encodeURI(document.getElementById('username_2').checked);
                username_3 = encodeURI(document.getElementById('username_3').checked);
                username_4 = encodeURI(document.getElementById('username_4').checked);
                //.
                //. and so on until num_of_users
	}

My second question is HOW to pass these variables through :


http.open('get', '../ajax/insert.php?num_of_users='+num_of_users+'&username_2='+username_2+'&username_3='+username_3+'&username_4='+username_4);

Is it possible to pass an array? Did someone have a similar issue? Any suggestion will be highly appreciated!
P.S. How to format the code to be JS - like [ php ] for php?

If you want to actually do something with the values after then you could put them in an array. Which in fact might be a lot easier to deal with.

Since I’m going to recommend that you use jQuery for the AJAX part, we might as well take advantage of it here.


var num_of_users = parseInt( $("#num_of_users").val(), 10 ),
    i = 0,
    // we'll use an object to store the data we want to submit
   data = { "num_of_users": num_of_users, "users": [] }, 
   usernameFields = $(".username-field"); //assuming your username fields have been given a class of username-field


usernameFields.each(function() {
   var field = $(this);

   data.users.push( { field.attr("id"):( field.attr("checked") ? true : false );

});
 


// Should now have something like this:
data = {
    "num_of_users": 3,
    "users": [
        { username_1: true },
        { username_2: false },
        ...
    ]
};

Additionally, we should probably use POST rather than GET to do this as well. (Using jQuery.post())
e.g.




//We can submit this data via POST:
$.post("../ajax/insert.php", data, function(data, textStatus, jqXHR) {
    //do something with returned data and/or textStatus
});

If you need some more advanced AJAX options, check out jQuery’s AJAX method

[ highlight=javascript ] (without spaces of course)
You can also highlight a bunch of other languages. When you go to “Go Advanced” when writing a post, there is a menu item for this in the editor :slight_smile:

Hope this helped :slight_smile:

Thanks John! Sounds good. My knowledge in JS and jQuery is a bit limited so I’m going to post here more of my code in hope you can help me out…
Here’s the portion of the code where you can see how the variables are passed to the javascript for further processing :


// form method=post, action=javascript:insert()
$users_result = $database->retrieveAllTableRecords("users");
$num_of_users = $users_result->rowCount();
for ($i = 1; $i <= $num_of_users; $i++) {
	$users_row = $users_result->fetch(PDO::FETCH_ASSOC);
	echo "<li><input type='checkbox' name='username_".$i."' id='username_".$i."' value='' />".$users_row['full_name']."</li>";
}
// form submit

Now here is the WHOLE JS (I’ve tried to add your solution with the post method, but I couldn’t make it to work…) file which supposed to retrieve the submitted form variables and pass them to the insert.php :


function createObject() {
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}else{
request_type = new XMLHttpRequest();
}
return request_type;
}

var http = createObject();

/* -------------------------- */
/* INSERT */
/* -------------------------- */
var nocache = 0;

function insert() {
	// Optional: Show a waiting message in the layer with ID login_response
	document.getElementById('insert_response').innerHTML = "<div class='info'>Working...</div>"
	
	var insert_what	= encodeURI(document.getElementById('insert_what').value);
	if (insert_what == "assign_user") {
		
		var num_of_users = parseInt( $("#num_of_users").val(), 10 );
		
		// FROM SITEPOINT
		i = 0;
		// we'll use an object to store the data we want to submit
		data = { "num_of_users": num_of_users, "users": [] };
		usernameFields = $(".username_field"); //assuming your username fields have been given a class of username-field
		
		usernameFields.each(function() {
			var field = $(this);
			data.users.push( { field.attr("id"):( field.attr("checked") ? true : false );
		});
		// FROM SITEPOINT end
	}
	// Set te random number to add to URL request
	nocache = Math.random();
	
	// FROM SITEPOINT
	$.post("../ajax/insert.php", data, function(data, textStatus, jqXHR) {
		//do something with returned data and/or textStatus
		http.onreadystatechange = insertReply;
		http.send(null);
	});
	// FROM SITEPOINT end
}

function insertReply() {
		var response = http.responseText;
		// else if login is ok show a message: "Site added+ site URL".
		if(response == "Changes have been saved!") {
			document.getElementById('insert_response').innerHTML = '<div class="success">'+response+'</div>';
		}
		else{
			document.getElementById('insert_response').innerHTML = '<div class="error">'+response+'</div>';
		}
}

and, just-in-case here is how I tried to retrieve the passed values at insert.php:


$num_of_users = $_POST['num_of_users'];
$username_2 = $_POST['username_2']; // just to check if it is passed...
if ($username_2 == "true") { $username_2 = "checked!!!"; }
echo "Num of users : ".$num_of_users."<br />Username 2 :".$username_2;

I believe it’s not too complicated, even with my JS ‘knowledge’ but I also believe I need some instructions here and there… Can you please advise me where am I wrong with this code? Thank you in advance.

Sorry I didn’t specify this in the first post (I was just quickly writing that before dashing off to work), but some of the code I posted uses the jQuery library.

Whenever jQuery is used, you need to make sure that you’re including the library on the page as well. The easiest way is to simply include the library from the Google CDN before it is referenced anywhere:


<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

When you’re trying to diagnose JavaScript problems, you can usually do a quick check in your browser’s developer console to see if there are any JavaScript errors or warnings. For example in Chrome on Windows, hit F12 to open up the developer tools and head to the console tab. You’ll be able to see any errors over there.

Thanks for the tips again, actually I HAVE included the mentioned jQuery library before, as my other scripts also use it.
Now I have cleaned up the script a bit and have simplified it for testing. I’d really like to learn how to post an array… So here’s the script, please have a look at the comments :


function insert() {
	document.getElementById('insert_response').innerHTML = "<div class='info'>Working...</div>"	
	var insert_what	= encodeURI(document.getElementById('insert_what').value);
	if (insert_what == "assign_user") {
		var num_of_users = parseInt( $("#num_of_users").val(), 10 );
	}
	
	// prepare the data for POST request
	data = { "num_of_users": num_of_users, "insert_what": insert_what }; // array with only 2 pairs of variable/value
	// POST request
	$.post("../ajax/insert.php", data, function(data, textStatus, jqXHR));
	
        // the script IS working with the GET method...
	//http.open('get', '../ajax/insert.php?insert_what='+insert_what+'&num_of_users='+num_of_users+'&nocache='+nocache);
	http.onreadystatechange = insertReply;
	http.send(null);
}

function insertReply() {
	var response = http.responseText;
	if(response == "Changes have been saved!") {
		document.getElementById('insert_response').innerHTML = '<div class="success">'+response+'</div>';
	}
	else{
		document.getElementById('insert_response').innerHTML = '<div class="error">'+response+'</div>';
	}
}

This is really simply and I can’t see why doesn’t work… Any help is appreciated. :slight_smile:

OK, I managed to get some progress with the following :


/* ---------------------------- */
/* XMLHTTPRequest Enable */
/* ---------------------------- */
function createObject() {
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}else{
request_type = new XMLHttpRequest();
}
return request_type;
}

var http = createObject();

/* -------------------------- */
/* INSERT */
/* -------------------------- */
/* Required: var nocache is a random number to add to request. This value solve an Internet Explorer cache issue */
var nocache = 0;

function insert() {

	document.getElementById('insert_response').innerHTML = "<div class='info'>Working...</div>"
	var insert_what	= encodeURI(document.getElementById('insert_what').value);
	if (insert_what == "assign_user") {
		var num_of_users = parseInt( $("#num_of_users").val(), 10 );
	}
	
	var dataString = 'insert_what='+ insert_what + '&num_of_users=' + num_of_users + 'nocache='+ nocache;
	 $("#error").html("Processing...");
	 $.ajax({
	   type: "post",
	   url: "../ajax/insert.php",
	   data: dataString,
	   error: function(){
		 alert('Error loading document');
		 return false;
	   },
	   success: function() {
		var response = http.responseText;
		document.getElementById('insert_response').innerHTML = '<div class="success">Response : '+response+'</div>';
	   }
	 });
}

while at insert.php I only have


$num_of_users = $_POST['num_of_users'];
echo "Changes have been saved!";

I have checked the variable ‘num_of_users’ and it has the correct value. It seems my ‘response’ is EMPTY… Please someone help me, I’m ALMOST desperate… :slight_smile:

Looks like you’re trying to use the http object’s response, but it didn’t perform the AJAX request :wink:

When you’re using jQuery’s AJAX methods, their success, error and complete callbacks will receive arguments when called. In the success callback, the first argument is the returned data from the server.

So, just a tiny change to your script and it should work :slight_smile:


success: function(data) { //make sure data is specified as an argument
    document.getElementById('insert_response').innerHTML = '<div class="success">Response : ' + data + '</div>'; //then you can use it here
}

Of course we now still need to know how to pass along that array of users.

Here I’m just passing an object in to the data part rather than the query string, since objects are a lot easier to play with.
(I’ve removed some of your code from the insert() function just to make this example a bit shorter)

function insert() { 

// Just a static object at the moment, put your own values in here
    var data = {
        insert_what: "assign_user",
        num_of_users:  4,
        users: [
            { id: 1, name: "John" },
            { id: 2, name: "Steve" },
            { id: 3, name: "Tom" },
            { id: 4, name: "Harry" }
        ]
    };

    $.ajax({
        type: "post",
        url: "../ajax/insert.php",
        dataType: "json", //set the datatype to JSON
        data: data,
        error: function(){
            alert('Error loading document');
            return false;
        },
        success: function(data) {
            console.log(data); //check out what's in the console now.
            document.getElementById('insert_response').innerHTML = '<div class="success">Response : '+data.message+'</div>';
        }
    });
}

I also made a change to the PHP file:


$num_of_users = 
$_POST['num_of_users'];$users = $_POST["users"];

$returnData = array(
    "insertData" => array(
        "users" => $users,
        "num_of_users" => $num_of_users
    ),
    "message" => "Changes have been saved!");

header("Content-type: text/json");
print json_encode($returnData);

So here we grab some data from $_POST and stuff some relevant values (maybe extra return data too?) in to an associative array.

Then we send a json_encoded version of our $returnData back, jQuery will know it’s JSON because of the mime-type and convert this string in to a JavaScript object for us.

Hope this has clarified a few things :slight_smile:

That’s more than I expected!!! Thank you so much for clarifying all these steps. It looks so simple and logic. I knew SP was the best place for the solution! :slight_smile:

Is it possible that the ajax call


$.ajax({
        type: "post",
        url: "../ajax/insert.php",
        dataType: "json", //set the datatype to JSON
        data: dataString,
        error: function(){
            alert('Error loading document');
            return false;
        },
        success: function(data) {
            console.log(data); //check out what's in the console now.
            document.getElementById('insert_response').innerHTML = '<div class="success">'+data.message+'</div>';
        }
    });

is working on one server and is NOT working on another (when I changed the dataType to “text”, the success function was called and error function was called when dataType = “json” ?
According to phpinfo() :


json support 	enabled
json version 	1.2.1 

Hmmm … maybe try changing the Content-type of the output to application/json (sorry, I got that wrong, application/json is the correct mime-type for JSON, I mix them up all the time)

header("Content-type: application/json");

You never sleep John? :slight_smile: Thank you for helping me. Unfortunately changing the content-type to application/json didn’t solve the issue. It’s strange that the code was working on an older version of Apache server and returns the error on a newer one (I’m not sure if that’s a relevant info…).

I sleep, sometimes :stuck_out_tongue: … It’s only 8.35pm here :wink:

That certainly is odd. There could be a variety of reasons for that happening, but if just setting the dataType to “text” works for you, then I suppose sticking with that will work. (You can also try to just leave the dataType off completely and jQuery will try to figure it out for you.)