Solved

Returning values with AJAX

Posted on 2011-10-01
7
372 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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

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 108

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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Introduction HyperText Transfer Protocol (http://www.ietf.org/rfc/rfc2616.txt) or "HTTP" is the underpinning of internet communication.  As a teacher of web development I have heard many questions, mostly from my younger students who have come to t…
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

746 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now