Solved

Returning values with AJAX

Posted on 2011-10-01
7
399 Views
Last Modified: 2012-05-12
Hello all,

I have setup an AJAX call to a php file to run a query and spit out some results - all good.

Now, what I'm looking to do is feed some of those results into an array and send it back to the original page that made the call for processing via javascript.

I've read about encoding to json and then decoding that via javascript.

So here's some code:

<script type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
	var ajaxRequest; 
	//Show loading graphic
	document.getElementById('loading').style.display="block";
	
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("A problem has occured with your request");
				return false;
			}
		}
	}
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function(){
			if(ajaxRequest.readyState == 4){
			document.getElementById('loading').style.display="none";
			document.getElementById('search_results').innerHTML = ajaxRequest.responseText;
		}
	}
	//Need to grab query string and append checked checkboxes array
	var checkboxes = document.getElementsByName("filter_option[]");
	var queryString = [];
	for(var i=0;i<checkboxes.length;i++) {
		if( checkboxes[i].checked ) {
			queryString.push( checkboxes[i].value );
		}
		
	}
	prevQS="<?php echo($_SERVER["QUERY_STRING"])?>";
	queryString = "?"+prevQS+"&filter_options=" + queryString.join(",");
	ajaxRequest.open("GET", "filter_query.php" + queryString, true);
	ajaxRequest.send(null);  
}

//-->
</script>

<label for="148"><input type="checkbox" onClick="ajaxFunction();" name="filter_option[]" value="148" id="148">Option 1</label>
<label for="149"><input type="checkbox" onClick="ajaxFunction();" name="filter_option[]" value="149" id="149">Option 2</label>
<label for="150"><input type="checkbox" onClick="ajaxFunction();" name="filter_option[]" value="150" id="150">Option 3</label>

Open in new window



So if a checkbox is clicked, it's id fires over a string of id's via GET to the filter_query.php which works some magic and outputs results.

What I want to now do, is get the php script to send an array back to javascript - an array of checkbox ids that I would use to then disable those checkboxes. This is kind of like showing the user what options are now appliceable after they've picked one option - narrowing them down.

Any help, hugely appreciated as usual.

Cheers
David


0
Comment
Question by:dolythgoe
  • 3
  • 3
7 Comments
 
LVL 82

Accepted Solution

by:
leakim971 earned 200 total points
ID: 36897856
>an array of checkbox ids that I would use to then disable those checkboxe

end of your php script :

echo "12,33,44,55,66";

?>

Open in new window


and client side use :

var myarray = ajaxRequest.responseText.split(",");
0
 

Author Comment

by:dolythgoe
ID: 36897861
Thanks for that but a lot more HTML is spat out in the result so wouldn't this try to split all the response HTML?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 36897881
no, an ajax response should contains only the required data...
if needed make two ajax calls
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 

Author Comment

by:dolythgoe
ID: 36897953
Ah ok, can I do 2 calls with what I have above? I do I check for the response from call 1 or call 2? Thanks!
0
 
LVL 82

Expert Comment

by:leakim971
ID: 36897957
successive ajax call, not at the "same" time
0
 
LVL 109

Assisted Solution

by:Ray Paseur
Ray Paseur earned 300 total points
ID: 36898207
Something to look out for... In PHP, JSON can confuse arrays and objects.  Example:
http://www.laprbass.com/RAY_temp_dolythgoe.php
<?php // RAY_temp_dolythgoe.php
error_reporting(E_ALL);
echo "<pre>" . PHP_EOL;

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

// CREATE SOME TEST DATA
$arr = array
( 'pink'  => 'Happy'
, 'blue'  => 'Sad'
, 'green' => 'Kermit'
)
;

// SHOW THE ARRAY
var_dump($arr);

// MAKE A JSON STRING FROM THE ARRAY
$json = json_encode($arr);
var_dump($json);

// TRY TO RECOVER THE ARRAY FROM THE JSON STRING... OOPS!
$new = json_decode($json);
var_dump($new);

// DID WE GET THE RIGHT DATA BACK?  NOPE.
if ($new ==  $arr) echo PHP_EOL . "Success!! We got a matching array";
if ($new === $arr) echo PHP_EOL . "Success!! We got an identical array";

// TRY IT AGAIN USING THE SECOND ARGUMENT
$new = json_decode($json, TRUE);
var_dump($new);

// DID WE GET THE RIGHT DATA BACK THIS TIME?  YEP.
if ($new ==  $arr) echo PHP_EOL . "Success!! We got a matching array";
if ($new === $arr) echo PHP_EOL . "Success!! We got an identical array";

Open in new window

0
 

Author Closing Comment

by:dolythgoe
ID: 36900017
Thanks guys
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction Got endorsements from your clients?  Great!  There is almost nothing better than word-of-mouth advertising.  But how can you do that on the internet?  Sure you can make a page for endorsement quotations and list them all, but who is …
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question