Jump to content

Passing Form Parameters Using Ajax And Post


lanmind
 Share

Recommended Posts

Hello everybody,On my site http://lanmind.net/ I am using a form and the GET method to pass a url and query parameter to javascript which uses Ajax to make a httprequest. On the server end I use PHP to insert the query into a database and it also echo's the same query which is simply written to the page for confirmation.My problem is I want to use the POST method and I tried separating the url and query parameter in the form's onSubmit= "Ajaxfunction()" using commas so I could put the query parameter in "xmlHttp.send(null)" instead of null.I've not been able to effectively pass the url and query parameter to the javascript for use as separate variables. Here is the html, javascript and PHP functioning correctly with the GET method: Thank you for your time.

<!DOCTYPE htmlPUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">	<head>		<meta http-equiv="content-type" content="text/html; charset=utf-8"/>		<meta name="description" content="Lanmind.net is in beta, likely forever." />		<link rel="shortcut icon" href="/favicon.ico" />		<link rel="icon" type="image/ico" href="favicon.ico" />		<title>Lanmind.net | Beta</title>		<link rel="stylesheet" type="text/css" href="mystyle.css" />		<script src="lanmind_javascript.js" type="text/javascript"></script>	</head>		<body>				<div id="wrap">						<a href="http://lanmind.net/" id="headerhome">Home</a>			<a href="http://lanmind.net/about.html" id="headerabout">About</a>						<br />						<form id="main" action="lanmindphp.php" method="get" onsubmit="ajaxFunction(this.action + '?name=' + escape(this.name.value)); return false;">								<p>					Enter anything you want:				</p>								<div id="searchbox">										<input type="text" name="name" />					<input type="submit" />									</div>							</form>						<div id="q_placeholder">								<p id="question"></p>							</div>					</div>			</body>	</html>

function ajaxFunction(url){	var xmlHttp;	try	{		// Firefox, Opera 8.0+, Safari		xmlHttp=new XMLHttpRequest();	}	catch (e)	{		// Internet Explorer		try		{			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");		}		catch (e)		{			try			{				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");			}			catch (e)			{				alert("Your browser does not support AJAX!");				return false;			}		}	}	xmlHttp.open("GET", url, true);	xmlHttp.onreadystatechange=function()	{		if(xmlHttp.readyState==4)		{			var xmlDoc = xmlHttp.responseText;			document.getElementById("question").innerHTML = xmlDoc;					}	}	xmlHttp.send(null);}

<?php	require('currentlanmind_dbinfo.php');		// Opens a connection to a MySQL server	$connection= mysql_connect ($hostname, $username, $password);	if (!$connection)	{		die('Not connected : ' . mysql_error());	}		$userquestion=mysql_real_escape_string($_GET['name'], $connection);	// Set the active MySQL database	$db_selected = mysql_select_db($database, $connection);	if (!$db_selected)	{		die ('Can\'t use db : ' . mysql_error());	}		mysql_query("INSERT INTO questions (question) VALUES ('$userquestion')");		$txt="hello";	echo $userquestion;  ?>

Link to comment
Share on other sites

I ran into this same problem earlier. The url variable is making it into the request fine but the query which I put in the parameter variable isn't. In the javascript "ajaxFunction(url, query)" is it wrong to name it "query". I'm confused on that. Here is the codes:

<form id="main" action="lanmindphp.php" method="post" onsubmit="ajaxFunction(this.action, this.name.value); return false;">								<p>					Enter anything you want:				</p>								<div id="searchbox">										<input type="text" name="name" />					<input type="submit" />									</div>							</form>

function ajaxFunction(url, query){	url += "?name=";	var parameter = escape(query);	var xmlHttp;	try	{		// Firefox, Opera 8.0+, Safari		xmlHttp=new XMLHttpRequest();	}	catch (e)	{		// Internet Explorer		try		{			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");		}		catch (e)		{			try			{				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");			}			catch (e)			{				alert("Your browser does not support AJAX!");				return false;			}		}	}	xmlHttp.open("POST", url, true);	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");	xmlHttp.onreadystatechange=function()	{		if(xmlHttp.readyState==4)		{			var xmlDoc = xmlHttp.responseText;			document.getElementById("question").innerHTML = xmlDoc;					}	}	xmlHttp.send(parameter);}

<?php	require('currentlanmind_dbinfo.php');		// Opens a connection to a MySQL server	$connection= mysql_connect ($hostname, $username, $password);	if (!$connection)	{		die('Not connected : ' . mysql_error());	}		$userquestion=mysql_real_escape_string($_POST['name'], $connection);	// Set the active MySQL database	$db_selected = mysql_select_db($database, $connection);	if (!$db_selected)	{		die ('Can\'t use db : ' . mysql_error());	}		mysql_query("INSERT INTO questions (question) VALUES ('$userquestion')");		$txt="hello";	echo $userquestion;  ?>

Link to comment
Share on other sites

Use this generic function instead:

function ajaxFunction(url, params){  var data = "";  for (var i in params)  {	data += (data == "" ? "" : "&") + i + "=" + encodeURIComponent(params[i]);  }  var xmlHttp;  try  {	// Firefox, Opera 8.0+, Safari	xmlHttp=new XMLHttpRequest();  }  catch (e)  {	// Internet Explorer	try	{	  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");	}	catch (e)	{	  try	  {		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");	  }	  catch (e)	  {		alert("Your browser does not support AJAX!");		return false;	  }	}  }  xmlHttp.open("POST", url, true);  xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");  xmlHttp.onreadystatechange=function()  {	if(xmlHttp.readyState==4)	{	  var xmlDoc = xmlHttp.responseText;	  document.getElementById("question").innerHTML = xmlDoc;	}  }  xmlHttp.send(data);}

You send it an object with the names and values of things you want to send.

onsubmit="ajaxFunction(this.action, {name: this.name.value, param2: "some other value"}); return false;"

If you want to change your other function, you're setting the URL to be "<url>?name=", and then sending the name as the request body. The request body needs to be the entire URL-encoded string, e.g. "name=test%20name", not just the value. You can leave the name off the URL since you're using POST to submit.

Link to comment
Share on other sites

This is really the only important part:ajaxFunction(this.action, {name: this.name.value, param2: "some other value"});That's a shorthand object notation. If you create this:

var obj = {  name: "some name",  email: "some email",  title: "some title"};

Then you create a generic object with properties called "name", "email", and "title". That's equivalent to doing this:

var obj = new Object();obj.name = "some name";obj.email = "some email";obj.title = "some title";

So that's how you send the data to the ajax function, send each piece of data as a property of a generic object. The first loop in the function will convert that into a string like this:name=some%20name&email=some%20email&title=some%20titleThat's what gets submitted through post to the server.

Edited by justsomeguy
Link to comment
Share on other sites

Ok it has taken me a while but now I know that the loop in the recommended function is not a "for loop" but a "for...in loop". I was trying to figure out why or how you put a "in" operator in a for loop's argument lol. I've never used a for...in loop so I forgot it totally.So it loops through the object "params" properties and each time it sets the var data as...well I'm still working on that part. Specifically:"" ? "" : "&"I do know that encodeURIComponent(params); encodes each property in the object "params" for the URI. I'm also confused about why it's called "URI". I read on wikipedia that a URI is basically a string used to identify something on a network, like the internet. So it's used to identify a webpage. Isn't that a URL? Is the URI the URL?I get so confused with arrays even though I understand their basics. Especially confusing to me is what variable is in each array and how it's carried over so on and so forth...I'm tired but I will study this function more tomorrow. It works though! I just don't know exactly how...Thank you.

Link to comment
Share on other sites

URL == URI (URI is an older name).The ?...: syntax is the ternary conditional operator. Basically, it means if...then...else in a very concise fashion. E.g.

var a = b ? c : d;

That is equivalent to:

if (b) {	var a = c;} else {	var a = d;}

Link to comment
Share on other sites

Here is the bit of code again:
data == "" ? "" : "&"

Basically this is saying: If data == "" then data == "". Else data == "&".Is this correct?

You probably meant it like this, but yes.
If data == "" then data = "". Else data = "&".

Link to comment
Share on other sites

I went through it all again and I understand everything but two things:First in the if then else statement below data == "" if data == "". Well right before the statement the variable data was defined as "". So how does data ever become the ampersand required for the URL? Since data is empty the else will never be called. Unless data is defined first with the object parameter and then the if then else statement happens after wards. I'm confused about this.

 var data = "";  for (var i in params)  {    data += (data == "" ? "" : "&") + i + "=" + encodeURIComponent(params[i]);  }

Second on my site http://www.lanmind.net/ the user query that was posted to the PHP is echoed out for confirmation. When the user enters a single quotation or backslash character it is prepended with three backslashes. Like such:"Don't" outputs: "Don\\\'t""\" outputs: "\\\\"At first I thought it was the js encodeURI() function but now I don't know what's causing it. Any ideas?

Link to comment
Share on other sites

I went through it all again and I understand everything but two things:First in the if then else statement below data == "" if data == "". Well right before the statement the variable data was defined as "". So how does data ever become the ampersand required for the URL? Since data is empty the else will never be called. Unless data is defined first with the object parameter and then the if then else statement happens after wards. I'm confused about this.
 var data = "";  for (var i in params)  {    data += (data == "" ? "" : "&") + i + "=" + encodeURIComponent(params[i]);  }

Second on my site http://www.lanmind.net/ the user query that was posted to the PHP is echoed out for confirmation. When the user enters a single quotation or backslash character it is prepended with three backslashes. Like such:"Don't" outputs: "Don\\\'t""\" outputs: "\\\\"At first I thought it was the js encodeURI() function but now I don't know what's causing it. Any ideas?

Since var data = "" is not within the loop, it will only happen on the first iteration. After that, data will have another value when the loop repeats itself, so it will add an ampersand as well.To your second question: it looks like your web host has magic quotes activated, and additionally, you're using mysql_real_escape_string() or addslashes() to the result.
Link to comment
Share on other sites

Hello again,Are there any tutorials on creating a custom php.ini file? My web host has one php.ini file for all hosting accounts on my shared server. I'm running PHP 5 and I'm not sure if I need to set a lot of php settings or if I can just turn off magic quotes and all other settings will remain the same. I don't know if my php.ini file will only add magic quotes = off or override the entire server file. Is there some PHP code that will allow me to output or echo the current file so I could copy and add what I like? I need some clarity on this and I'm having a hard time finding it with Google.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...