Jump to content

[SOLVED] Sending a PHP variable to a JS script


mark110384

Recommended Posts

Hey guys I been developing an AJAX portion of my website and I'm nearly there but I have come across a problem, I have 2 DIVs, one that displays the item number and name when the request is sent and another that is populated when the user selects the item, this includes a price and description. How would I send variables from my php script that aren't in the echo string to populate the second DIV? Hope it makes sense the Coding is as follows. Thanks

 

JS

 


//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
	return new XMLHttpRequest();
} else if(window.ActiveXObject) {
	return new ActiveXObject("Microsoft.XMLHTTP");
} else {
	alert("Your browser does not support this function!");
}
}

//Our XmlHttpRequest object to get the auto suggest
var searchReq = getXmlHttpRequestObject();

//Called from keyup on the search textbox.
//Starts the AJAX request.
function searchSuggest() {

//Check if the search field is empty. If so empty Search Suggest inner HTML.

if (document.getElementById('txtSearch').value == "") {
	document.getElementById('search_suggest').innerHTML = '';
}

else if (searchReq.readyState == 4 || searchReq.readyState == 0) {
	var str = escape(document.getElementById('txtSearch').value);
	searchReq.open("GET", 'searchSuggest.php?search=' + str+'&sid='+Math.random(), true);
	searchReq.onreadystatechange = handleSearchSuggest; 
	searchReq.send(null);
}

}

//Called when the AJAX response is returned.
function handleSearchSuggest() {
if (searchReq.readyState == 4) {
	var ss = document.getElementById('search_suggest')
	ss.innerHTML = '';
	var str = searchReq.responseText.split("\n");
	for(i=0; i < str.length - 1; i++) {

		var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
		suggest += 'onmouseout="javascript:suggestOut(this);" ';
		suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';

		suggest += 'class="suggest_link">' + str[i] + '</div>';
		ss.innerHTML += suggest;
	}
}

}

//Mouse over function
function suggestOver(div_value) {
div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
div_value.className = 'suggest_link';
}
//Click function
function setSearch(value) {
document.getElementById('chart_info').innerHTML =  value + "Price:" + ("<? echo $price; ?>"); 

}

 

PHP

 

<?
require('../functions.php');

$connect = @ConnectToAgents($dbhost, $dbuser, $dbname);

$search = $_GET['search'];
$pubtype = 'Chart';

$sql = "SELECT * FROM products WHERE (Code LIKE '%" . $search . "%' OR Description LIKE '%" . $search . "%') AND Type = '$pubtype' limit 0,20";






	$result = mysql_query($sql);	

	while($myrow = mysql_fetch_array($result)) 

	{

		$chartcode = $myrow['Code'];

		$chartp = $myrow['PPost'];

		$chartdescription = $myrow['Description'];

		$price = $myrow['Price'];

		echo "$chartcode $chartp - $chartdescription \n";


	}


?>

 

Link to comment
Share on other sites

Okay so the PHP script is called from the JavaScript using AJAX. You're then echo'in out all the variables (except $price) on the PHP side .. so firstly remember when you call a PHP script with AJAX, you only receive a string of text "searchReq.responseText" .. not the actual variables. So using $price isn't going to work... what you could do is format the and print out the string on the JS side. What I've done in the past is return the string in a var1|var2|var3 form .. then split the string into an array using the | as the delimitor. So for example:

 

PHP

echo $chartcode .'|'. $chartp .'|'. $chartdescription .'|'. $price ."\n";

 

JS

var records = searchReq.responseText.split("\n");

for (x in records) {
    var str = searchReq.responseText.split('|');
    var suggestTxt = str[0] + ' ' + str[1] + ' - ' + str[2];

    var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
    suggest += 'onmouseout="javascript:suggestOut(this);" ';
    suggest += 'onclick="javascript:setSearch(this.innerHTML, ' + str[3] + ');" ';

    suggest += 'class="suggest_link">' + suggestTxt + '</div>';
    ss.innerHTML += suggest;
}

 

Then you'll just need to change the setSearch function to:

 

function setSearch(value, price) {
document.getElementById('chart_info').innerHTML =  value + "Price: " + price; 

}

 

 

Not tested this code so there by an error or two, but should work with a little tweaking!

 

Adam

Link to comment
Share on other sites

Hmmm ,it only brings back one record several times and the second DIV doesn display anything now. I have the following for that Function now.

 

 

function handleSearchSuggest() {
if (searchReq.readyState == 4) {
	var ss = document.getElementById('search_suggest')
	ss.innerHTML = '';

	var records = searchReq.responseText.split("\n");

 for (x in records) {
                var str = searchReq.responseText.split('|');

                var suggestTxt = str[0] + ' ' + str[1] + ' - ' + str[2];

    var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
    suggest += 'onmouseout="javascript:suggestOut(this);" ';
    suggest += 'onclick="javascript:setSearch(this.innerHTML, ' + str[3] + ');" ';

    suggest += 'class="suggest_link">' + suggestTxt + '</div>';
    ss.innerHTML += suggest;
}
}
}
}

Link to comment
Share on other sites

I've managed to get the second DIV to work however it still doens't seem loop round and when I put in the original loop with coding it jsut causes the browser to crash. This is the coding that I have now for the function, any suggestions of how to make it loop with killing my browser?

 

 


function handleSearchSuggest() {
if (searchReq.readyState == 4) {
	var ss = document.getElementById('search_suggest')
	ss.innerHTML = '';

	var records = searchReq.responseText.split("\n");

	for (x in records) {
    	var str = searchReq.responseText.split('|');
    	var suggestTxt = str[0] + ' - ' + str[1];

    	var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
    	suggest += 'onmouseout="javascript:suggestOut(this);" ';
    	suggest += 'onclick="javascript:setSearch(this.innerHTML, ' + str[2] + ');" ';

    	suggest += 'class="suggest_link">' + suggestTxt + '</div>';
    	ss.innerHTML += suggest;
	}
}

}

Link to comment
Share on other sites

Yeah I managed to get working with a bit tinkering. I was spliting the first row only and repeating it thats why I was only geting the first result back this is the final coding. Thanks to everyone that helped.

 

 


function handleSearchSuggest() {
if (searchReq.readyState == 4) {

	var ss = document.getElementById('search_suggest')

	ss.innerHTML = '';

	var results = searchReq.responseText.split("\n");

	for (i=1; i < results.length -1; i++) {

    	var string = results[i].split('|'); //searchReq.responseText.split('|');	

   		var suggestString = string[0] + ' - ' + string[1];



    	var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
    	suggest += 'onmouseout="javascript:suggestOut(this);" ';
    	suggest += 'onclick="javascript:setSearch(this.innerHTML, ' + string[2] + ', ' + string[3] + ');" ';

    	suggest += 'class="suggest_link">' + suggestString + '</div>' ;

    	ss.innerHTML += suggest;



	}
}

}

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.