I need some help getting the included ajax script's xmlhttp.open() to target a php code within the same page --something like $_SERVER[PHP_SELF]

here is the script:

<script type="text/javascript">
function showResult3(strss)
{
if (strss.length==0)
  { 
  document.getElementById("livesearch3").innerHTML="";
  document.getElementById("livesearch3").style.border="0px";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  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("livesearch3").innerHTML=xmlhttp.responseText;
    document.getElementById("livesearch3").style.border="1px solid #A5ACB2";
    }
  }

xmlhttp.open("GET","q="+strss,true);//$_SERVER[PHP_SELF]
xmlhttp.send();

}
</script>

I want to pass the variable $q to a php code in the same page as the code above. I know typically the xmlhtpp.open() need a url which tent to be an external one. I'm hoping that there is a work around.

I appreciate any help!

Mbar,

Try:

xmlhttp.open("GET", window.location.pathName+strss, true);

Airshow

Thank you air show for the post. how do I get the variable inside the php script since the $q variable is not in the syntax.

I know normally I would get it like this:

$q=$_GET["q"];

Mbar,

Sorry, I was assuming that strss was a ready-built querystring.

Try:

var url = window.location.pathName + '?q=' + strss;
alert(url);//to inspect the url string.
xmlhttp.open("GET", url, true);

Airshow

Thanks Airshow. There is definitely progress with the last solution. However, when the alert appears --displaying the correct path and the correct $q variable, after click the ok button, a duplicate of the same page loads at the bottom. I have echo'ed the $q inside the php code, it only appears in the duplicate page.

Nothing happens when I comment out the alert(url);

Any thoughts!

Mbar,

That's different question.

The code is doing exactly what is was written to do, namely to insert the ajax responseText into DOM element "livesearch3".

If you want something different to be inserted, then you have to adapt the server-side script to return something different. Alternatively, call a different script (ie. a different php file) which is designed to return the content you desire.

Typically, in applications that employ ajax, you initially serve one page to provide all the peripheral HTML content (doctype, metas, styles, javascript, masthead, primary navigation, controls, page footer ...) and skeleton elements (eg divs and spans) to accommodate ajax responses. Then, on various user interactions, you call one or more scripts (typically NOT the original page) to provide additional/alternative page content (eg search results).

If your php file is set up to deliver the whole page every time (from !doctype through to </html>), then you really shouldn't be using ajax. Instead, simple rely on old-fashioned, standard HTML form submission. By setting action="", the browser will cause the same page to be re-requested, and will append name=value pairs to the requested url, representing the contents of the form.

<form action="" method="get">
...
<form>

If you need to do something (eg data validation or transforms) prior to the form being submitteed, then you can intercept the submission with, eg.

<form action="" method="get" onsubmit="return myFunction(this);">
...
<form>

where myFunction is a javascript function that does whatever is nesessary (validation etc.) then returns false to suppress form submission or true to allow it. This is a very important and frequently used pattern.

Airshow

I appreciate the follow up and the additional explanation. I'm beginning to think that I need to abandon this method.

If you can indulge me for a moment, let me explain the core goal I'm trying to achieve and the issue preventing it. See if you can suggest another method.

Starting from my intended goal --though maybe considered illogical, it is the best option I'm prevy too at the moment.

On the current page, a client LookUP form is populated by an ajax code. This code takes its initial value from an input box on the form "clientID". This is the code:

var ajax = new sack();
	var currentClientID=false;
	function getClientData()
	{
		var clientId = document.getElementById('clientID').value.replace(/[^0-9|a-z|A-Z]/g,'');//here to incorporate the client id with numbers and letters
		if(clientId.length >0 && clientId!=currentClientID){//here to change the client id lenght
			currentClientID = clientId
			
			ajax.requestFile = 'getClient.php?getClientId='+clientId;	
			ajax.onCompletion = showClientData;	
			ajax.runAJAX();				
				
		}
		
	}
	
	function showClientData()
	{
		var formObj = document.forms['clientForm'];	
		eval(ajax.response);
			}
	
	
	function initFormEvents()
	{
		document.getElementById('clientID').onblur = function(){getClientData();
}
		document.getElementById('clientID').focus();
	    }

Now this ajax has a companion external php file which processes and retrieves necessary form fields and returns the values back to the form. this is the php:

$res = mysql_query("select * from additional_cars where clientID='".$_GET['getClientId']."'") or die(mysql_error());
    if($inf = mysql_fetch_array($res)){
    echo "formObj.firstname.value = '".toSafeString($inf["firstname"])."';\n";    
    echo "formObj.lastname.value = '".toSafeString($inf["lastname"])."';\n"; 
    echo "formObj.lastname1.value = '".toSafeString($inf["lastname"])."';\n";    
    echo "formObj.address.value = '".toSafeString($inf["address"])."';\n";    
    echo "formObj.zipcode.value = '".toSafeString($inf["zipcode"])."';\n";    
    echo "formObj.city.value = '".toSafeString($inf["city"])."';\n";    
    echo "formObj.state.value = '".toSafeString($inf["state"])."';\n";
    echo "formObj.dhtmlgoodies_category.value = '".toSafeString($inf["dhtmlgoodies_category"])."';\n";
    echo "formObj.dhtmlgoodies_subcategory.value = '".toSafeString($inf["dhtmlgoodies_subcategory"])."';\n";
    echo "formObj.caryear.value = '".toSafeString($inf["caryear"])."';\n";
    echo "formObj.servicedesc.value = '".toSafeString($inf["servicedesc"])."';\n"; 
    echo "formObj.currentmileage.value = '".toSafeString($inf["currentmileage"])."';\n";
    echo "formObj.servicearea.value = '".toSafeString($inf["servicearea"])."';\n";
    echo "formObj.drivenmileage.value = '".toSafeString($inf["drivenmileage"])."';\n"; 
    echo "formObj.clientid.value = '".toSafeString($inf["clientID"])."';\n"; 
    echo "formObj.clientid2.value = '".toSafeString($inf["clientID"])."';\n"; 
    echo "formObj.clientid3.value = '".toSafeString($inf["clientID"])."';\n"; 
    echo "formObj.displayname.value = '".toSafeString($inf["lastname"]).",".toSafeString($inf["firstname"])."';\n"; 


  }
  else
  {
    echo "formObj.firstname.value = '';\n";    
    echo "formObj.lastname.value = '';\n";    
    echo "formObj.lastname1.value = '';\n";    
    echo "formObj.address.value = '';\n";    
    echo "formObj.zipcode.value = '';\n";    
    echo "formObj.city.value = '';\n";    
    echo "formObj.state.value = '';\n";
    echo "formObj.dhtmlgoodies_category.value = '';\n";
    echo "formObj.dhtmlgoodies_subcategory.value = '';\n";
    echo "formObj.caryear.value = '';\n";
    echo "formObj.servicedesc.value = '';\n";
    echo "formObj.currentmileage.value = '';\n";
    echo "formObj.servicearea.value = '';\n";
    echo "formObj.drivenmileage.value = '';\n";
    echo "formObj.clientid.value = '';\n";
    echo "formObj.clientid2.value = '';\n";
    echo "formObj.clientid3.value = '';\n";
    echo "formObj.displayname.value = '';\n";
        }    

}

Now on the form, the values are not displayed as variables($), instead the are displayed as formObj value (ie: clientid).

This is where my problem begins; whereas, I want to pass the clientid as a variable to a page outside of the current thru url (ie: insertclientinfonew.php?clientid=$clientid"). But cannot do this because clientid in the current page is not a variable.

So, in my somewhat novice coder mind, I thought that if I created a php code within the same page and using ajax, pass the clientid to this code and then from there, create a variable of clientid.

So, if there is a simpler way to achieve this goal, based on my explanation here, please advise...

Best,
Mossa

Mossa,

I can't see anything that should make you abandon your method. It's just a question of getting the detail right.

As far as I can tell, the client id remains in the 'clientID' field and is therfore available to be sent as a parameter in as many ajax requests as you want to make, not just the first one.

However, it's probably best not to rely on the value in the 'clientID' foeld as there's a small chance it may not still correspond to the client data currently shown in the form (eg. if the user has entered a new clientID but getClient.php has not yet re-responded).

A safer stategy is therefore to get getClient.php to include a statement in its response to populate a hidden form field (let's name it "returnedClientId") with the original clientid which was in the request. 99.9% of the time this will be the same value still shown in 'clientID' .

Now, when the user initiates another ajax request requiring the client id (eg. to "insertclientinfonew.php"), the value in "returnedClientId" can be used rather than the value in 'clientID' (which may have changed).

To make this work, you need to do three things :
1. Add a new field to the form - <input type="hidden" name="returnedClientId"> .

2. Add the following statements to getClient.php :

...
echo "formObj.returnedClientId.value = " . $_GET['getClientId'];
...
else{
...
echo "formObj.returnedClientId.value = ''";

3a. If "insertclientinfonew.php" is requested by trad form submit, then the client id (as "returnedClientId") will be automatically included in the request (as part of the form). Server-side pick it up as $_GET (or the post equivalent).

3b. If "insertclientinfonew.php" is requested by ajax, then get the client id from the hidden field with document.forms['clientForm'].returnedClientId.value (I think). In this case you have more freedom to build the request string to your own specifiction, and can use "....php?...&clientId=....." to be picked up server-side as eg. $_GET (or the post equivalent).

In 3a and 3b, the client id included in the request is guaranteed to correspond to the values (client details) currently displayed in the form, regardless of what the user may have done in the original input field.

Airshow

Great angle! I'm attempting the strategy now!
Does it make a difference if in the getClient.php, I added

echo "formObj.returnedClientId.value = '".toSafeString($inf["clientID"])."';\n";
echo "formObj.returnedClientId.value = '';\n";

rather than

echo "formObj.returnedClientId.value = " . $_GET['getClientId'];
echo "formObj.returnedClientId.value = ''";

because the latter returns a blank field, while the former returns the correct value.

If I'm understanding you correctly, the idea in your last suggestion is to populated another field with the value of clientID --as hidden and named "returnedClientId"-- and pass this value to ajax.

At this point, I'm back to how does this value is passed the my php code that is within the same page to therefore get returnedClientId as

$_GET['returnedClientId']

My apology if this is redundant...

Mossa--

Great angle! I'm attempting the strategy now!
Does it make a difference if in the getClient.php, I added

echo "formObj.returnedClientId.value = '".toSafeString($inf["clientID"])."';\n";
echo "formObj.returnedClientId.value = '';\n";

rather than

echo "formObj.returnedClientId.value = " . $_GET['getClientId'];
echo "formObj.returnedClientId.value = ''";

because the latter returns a blank field, while the former returns the correct value.

No, it doesn't matter. In fact, that's what I should have typed in the first place. (Just make sure that the empty string is in your php else clause).

If I'm understanding you correctly, the idea in your last suggestion is to populated another field with the value of clientID --as hidden and named "returnedClientId"-- and pass this value to ajax.

Yes, in my 3a and 3b, I explain how the returned client id string (now in a hidden form field) will be available for resubmission with the rest of the client details.

At this point, I'm back to how does this value is passed the my php code that is within the same page to therefore get returnedClientId as

$_GET['returnedClientId']

I fear we are passing like ships in the night on this point. I can't penetrate your concern. Is it that you don't know how to send the form data without causing the page to refresh; ie. how to bundle up the form data into name|value pairs to form a querystring? If so that's just some simple-in-concept (nauseating-in-practice) string handling.

Airshow

No, it doesn't matter. In fact, that's what I should have typed in the first place. (Just make sure that the empty string is in your php else clause).


Yes, in my 3a and 3b, I explain how the returned client id string (now in a hidden form field) will be available for resubmission with the rest of the client details.


I fear we are passing like ships in the night on this point. I can't penetrate your concern. Is it that you don't know how to send the form data without causing the page to refresh; ie. how to bundle up the form data into name|value pairs to form a querystring? If so that's just some simple-in-concept (nauseating-in-practice) string handling.

Airshow

I fear we are passing like ships in the night on this point. I can't penetrate your concern. Is it that you don't know how to send the form data without causing the page to refresh; ie. how to bundle up the form data into name|value pairs to form a querystring? If so that's just some simple-in-concept (nauseating-in-practice) string handling.

I think in this latter point may lie some truth, but I believe it is in part because this is obviously not a traditional form submission --as there are no submission buttons. I'm digesting your explanation and will give it another shot.

Seriously, I do appreciate you kindness and willingness to help...very much appreciated!

Best
Mossa

Cannot get pass this area.

Is it that you don't know how to send the form data without causing the page to refresh; ie. how to bundle up the form data into name|value pairs to form a querystring? If so that's just some simple-in-concept (nauseating-in-practice) string handling.

The hidden field is created. The js var is written like

var newclientid = document.clientForm.returnedClientId.value;

Now this returnedClientId field is only one I need to pass to this php code in the same page

<?php
		
error_reporting(0);
error_reporting(E_ERROR | E_WARNING | E_PARSE);
include 'datalogin.php';

//this query pulls all client id from ajax and makes it available for ajax hint to compare with what is being inputed on the form
$result = mysql_query("SELECT clientID, customerid FROM additional_cars");
while($row=mysql_fetch_array($result)) {
     $clientID=$row["clientID"];
     $a[]= "$clientID";
    //echo "client id is $clientID";

}
//get the q parameter f
$q=$_GET["q"];
echo "q is $q";

//lookup all hints from array if length of q>0
if (strlen($q) > 0)
  {
  $hint="";
  for($i=0; $i<count($a); $i++)
    {
    if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
      {
      if ($hint=="")
        {
        $hint=$a[$i];
        }
      else
        {
        $hint=$hint." , ".$a[$i];
        }
      }
    }
  }

// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
  {
 //$response="no suggestion";
  }
else
  {
  $response=$hint;
  }

//output the response
//echo" id is $response";
$trimmed = trim($response); //trim whitespace from the stored variable

$get_swork2 = "select * from additional_cars where clientID='$trimmed'";// order by id desc limit 1";//here we are pulling dat from services where the license plate is $clientID, we use this to display last service(s) rendered
 $get_swork2_res = mysql_query($get_swork2); 

  if (mysql_num_rows($get_swork2_res) > 0) 
  { 
     while ( $swork2_info = mysql_fetch_array($get_swork2_res)) 
    { 
       $firstname = $swork2_info['firstname']; 
       $lastname = $swork2_info['lastname']; 
       $comma=", ";
       $sel_id="$lastname$comma$firstname";

				        }
	        }
    ?>

and then from the variable within the above code get $sel_id and $lastname and append to a link --in the same page like this

<a href="addentrynew_passed.php?sel_id=<?php echo $sel_id?>&lastname=<?php echo $lastname?>">PROCESS CLIENT</a>

getting the js variable into the above code is my challenge. my initial thought was to use xmlhttp.open() and target it to the same page, something like this:

<script type="text/javascript">

function showResult3(strss)
{
if (strss.length==0)
  { 
  document.getElementById("livesearch3").innerHTML="";
 // document.getElementById("livesearch3").style.border="0px";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  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("livesearch3").innerHTML=xmlhttp.responseText;
    //document.getElementById("livesearch3").style.border="1px solid #A5ACB2";
    }
  }
 //xmlhttp.open("GET","lookupclient.php?q="+strs,true);
var newclientid = document.clientForm.returnedClientId.value;
var url = window.location.pathname + '?q=' + newclientid;
alert(url);//to inspect the url string.
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>

as you remember, I noted that the page was duplicating itself.
is this whole thing doable?

No worries Mossa. It may be my misunderstanding yet. :-/

I must get some sleep. I've been up all night playing with some tricky code of my own making.

Will have a look at your last post later today.

Airshow

Mossa,

Of course it's doable, though I am working half-blind here because I don't have a complete overview of your application.

First, my limited understanding.

You have a web application involving (at least in part) a single page which interacts with its server via ajax to fetch data and to initiate actions associated with the fetched data. I am sort of confident in saying this because it's more-or-less a truism for interactive ajax applications.

After adopting my suggestion, when client details are displayed, you have two versions of client id :
a) clientID: The user-entered client id (still in a user-editable field)
b) returnedClientID: The client id that comes back with client details (in a tamper-proof, hidden field)

These two versions will be the same 99.9% of the time and should be used in ajax requests as follows :

a) clientID: When making the original request for client details and when making any further ajax requests of the same or similar type.
b) returnedClientID: When making other types of ajax request that relate to the client details that are currently on screen. This ensures that the client id sent with this type of request corresponds with what the user sees on screen. It also ensures that any of the on-screen details that are also included in the request, correspond to the client id that is sent.

Looking at your "hint" script, I can't tell for sure whether the request should be of type (a) or a type (b). As it appears to involve incomplete client ids, I can only assume that the script is called repeatedly as the user types in a new client id. If so, then the request is a type (a) and should therefore include clientID not returnedClientID .

A php script you mentioned previously was one to update the client details. That would definately be of type (b). It would be critical to ensure that the client id and the updated details correspond one with the other.

(continued in next post) .........

At the risk of being insufferably patronizing, this is kinda worrying.

..... to pass to this php code in the same page

It possibly reveals a fundamental misunderstanding of what's going on, but may just be shorthand English.

Ignoring the sentence's subject ("returnedClientId field", which is covered in the previous post), if you had said,
"..... to pass to this php script, in an ajax request from my single web page, which will subsequently handle the php script's response."

then I would be a whole lot happier.

Does my rewording help you at all? Or do you just hate me?

Airshow

Airshow, thank you for the post. I'm currently away from my computer and will be away for a few hours, but I just wanted provide a quick response. Quite amusing the last post; any observation coming from someone such as yourself, who kindly offer your wisdom and knowledge to those of us who seek it, is taken to heart. So my apologies for the incorrect usage of the English language.

As to the issue at hand, I'll look at it in detail when I return to my computer.

Thanks again
Mossa

Transmitting from a mobile device.

This project is intended for a local intranet network so I do not have a public link for you to see the app -I believe you may have a better grasp of what's happening. Should you like, I can send you a link, user access info and other details on a private platform.

I am looking to open a URL in the same window. Does this code in the first response accomplish that task and, if so, would someone please fill in the window.location.pathName+strss with a literal example, say (hypothetically) for opening www.hope.com/child.htm

xmlhttp.open("GET", window.location.pathName+strss, true);

Thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.