I have two pages. 1st page has two text forms like so:
<form name="NameForm">
Name: <input type = "text" name = "uname">
Location: <input type = "text" name = "ulocation">
<button type="button" onClick="MakeRequest()"">Save</button>
</form>
It pushes the information into page number two using javascript like so (note this is on the same page as the code above):
<script>
function MakeRequest()
{
// get values
var uname = document.NameForm.uname.value;
var ulocation = document.NameForm.ulocation.value;
// validation stuff here that detects browser
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
var url = "location.php?uname=" + uname + "&ulocation=" + ulocation;
xmlhttp.open("POST", url, true);
xmlhttp.send();
}
</script>
So the problem is this, the php scripts on the page that does all server communication is not reading and storing the variables from this post request into my database.(my other get methods that view items in the database works fine)
if (isset($_POST['uname']))
{
$name = $_POST['uname'];
$location = $_POST['ulocation']
}
then the query goes somehting like
//$table and the other undefined variables are the names of my table & columns
$query = "INSERT INTO $table ($tablename, $tablelocation) VALUES ('$name', '$location')";
Basically I'm trying to get that query to work. If i remove the If statement, it stores $name to the database but not $location.
EDIT:
I forgot to add
<div id="result">
</div>
You are sending a GET.
to send a POST try:
[edited] perform the functions that order
function XHR(){
if(typeof XMLHttpRequest !=="undefined"){
try{ return new XMLHttpRequest(); } catch (e){}
}
if(typeof ActiveXObject !=="undefined"){
try{ return new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){}
try{ return new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){}
}
return false;
}
function MakeRequest()
{
// get values
var uname = document.NameForm.uname.value;
var ulocation = document.NameForm.ulocation.value;
// validation stuff here that detects browser
var url = "location.php";
xmlhttp = XHR();//Fixed
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");//Fixed
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4) {
if(xmlhttp.status==200){
document.getElementById("result").innerHTML = xmlhttp.responseText;
} else {
document.getElementById("result").innerHTML = "ERROR:"+xmlhttp.status;
}
}
};
xmlhttp.send("uname=" + uname + "&ulocation=" + ulocation);
}
<form name="NameForm">
Name: <input type = "text" name = "uname">
Location: <input type = "text" name = "ulocation">
<button type="button" onClick="MakeRequest()"">Save</button>
</form>
Your missing a form method. In your case you wish:
<form name='NameForm" method="POST">
If this does not resolve your issue, then download and use firebug for firefox or chrome console to debug javascript errors.
There will be no output of errors in JS to the text. You will need to use a debug console.
perform an insert via html form
I would modify your HTML to:
<form name="NameForm" method="POST">
Name: <input type = "text" name = "uname">
Location: <input type = "text" name = "ulocation">
<button type="button" onClick="MakeRequest()"">Save</button>
<input type='submit' name='SubmitForm' value='SUBMIT THIS FORM'>
</form>
Then my PHP code:
<?php
if(isset($_POST['SubmitForm'])){
$Name = $_POST['uname'];
$Location = $_POST['ulocation'];
// Perform validation for these inputs, check if empty, set correctly ETC
$query = "INSERT INTO $table ($tablename, $tablelocation) VALUES ('$name', '$location')";
}
then call your Javascript function inside your PHP script; or perform an ajax/jquery call to run the insert without the need of a submit button
Related
I want to build a simple program using XMLHttpRequest to calculate the area of the triangle. I used this code for client-side;
<body>
<form>
<label for="txtLength">Length</label>
<input type="text" id="txtLength" name="txtLength"><br><br>
<label for="txtWidth">Width</label>
<input type="text" id="txtWidth" name="txtWidth"><br><br>
<input type="hidden" name="submitted" value="1">
<input type="button" name="Calculate" value="Calculate" onclick="calArea();">
</form><br><br>
<div id="showArea">Enter Values and click Calculate.</div>
<script type="text/javascript">
function calArea() {
var len = document.getElementById("txtLength").value;
var wid = document.getElementById("txtWidth").value;
var sub = 1;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.readyState == 200) {
document.getElementById("showArea").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "calculate_area.php", true);
xhttp.send(len&wid&sub);
}
</script>
</body>
This code is for the server side.
<?php
print_r($_POST);
if (isset($_POST['sub'])) {
$len = $_POST['len'];
$wid = $_POST['wid'];
$area = (($len*$wid)/2);
echo $area;
}
else{
echo "Not input detected.";
}
?>
Even tried so many codes, It doesn't send the data to server side.
I found the mistake. I was sending the parameters as part of the URL, but need to send them as part of the request body.
Client-side code;
function calArea() {
var len = document.getElementById("txtLength").value;
var wid = document.getElementById("txtWidth").value;
var sub = 1;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("showArea").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "calculate_area.php", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send(JSON.stringify({len: len, wid: wid, sub: sub}));
}
Server-side code;
if (isset($_POST['sub'])) {
$len = $_POST['len'];
$wid = $_POST['wid'];
$area = (($len*$wid)/2);
echo $area;
}
else{
echo "Not input detected.";
}
len&wid&sub
Taking some variables and putting the Bitwise & between them is not going to give you a useful value to submit to the server.
You need to encode the data in a format that you can transmit over HTTP and which your server-side code can read.
PHP supports URL Encoded and Multipart Form Encoded data natively so pick one of those.
The URLSearchParams API will generate URL Encoded data for you.
e.g.
xhttp.send(new URLSearchParams({ len, wid, sub }));
Passing a URLSearchParams object will also let XHR automatically set the correct Content-Type request header so PHP will know what it needs to do to decode the data and populate $_POST with it.
You need to put all the parameters into a string of the form name=value with each one separated by &. And the values should be encoded in case they contain special characters.
You also need to set the content type so this data will be parsed correctly.
So change
xhttp.send(len&wid&sub);
should be:
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.send(`len=${encodeURIComponent(len)}&wid=${encodeURIComponent(wid)}&sub=${encodeURIComponent(sub)}`);
Using that javascript ajax function I pass the content of a form, that contain
the dato value, to the PHP login.php than trought the echo pass back the content
(the insert form) that I want to be switched to the cancel form, using
the content respondText (that may take only the echo of the PHP).
BUT INSTEAD the responseText contain ALL the html code, with the old html
plus the cancella_form passed by the echo, that's also out of the div
with id=visibile.
Any ideas why? D:
//ajaxSubmit(dato)
function ajaxSubmit( url , divId , hideId ) {
//in setXmlHttpObject() I just control the user's browser
// and assign the right XmlHttp Object
var ajaxRequest = setXmlHttpObject();
var dato = 'nome='+document.getElementsByName('dato')[0].value;
ajaxRequest.open("POST", url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(dato);
ajaxRequest.onreadystatechange = function() {
//Comunication complete
if (ajaxRequest.readyState == 4 && ajaxRequest.status==200) {
//Comuncation succesfull
if(ajaxRequest.statusText === "OK"){
var str= ajaxRequest.responseText;//<<<HERE///////
$(str).replaceAll("#visibile");
}
//Comuncation failed
else{
var str= "ERROR: Ajax: "+ajaxRequest.responseText;
document.write(str);
}
}
}
}//FINE ajaxRequest();
<?php
include("prova_login_adv.php");
$conn= mysql_connect('localhost','root','');
mysql_select_db('db_prova',$conn ) or die(mysql_error());
//
if(isset($_POST['nome'])){
$dato= $_POST['nome'];
mysql_query(" INSERT INTO test (valore) VALUES ('$dato') ") or die(mysql_error());
/// NOW I declare what I want to be replaced in the div id="visibile"
echo "
<form id='form_cancella' name='form_cancella' action='' methos='POST' onSubmit=' return false;' >
<text name='dato' value='".$dato."' >Benvenuto <b>".$dato."</b></text>
<input type='submit' name='cancella' value='cancella' onClick=\" ajaxSubmit('logout.php','visibile','form_cancella');\" />
</form>
";
}
?>
I'm building off of a question I had asked and resolved earlier: front end mysql, deleting a row
Basically, I've got a front end where users can view a DB. Instead of having a delete button next to each row, I'd like to have a checkboxes that can be selected for multiple rows. Then, the user only clicks a single delete button and all the selected rows are removed. I don't know much php and mysql at all, so I'm not sure how to approach the code that I already have.
Currently, the onclick calls a delete function. Can anyone help?
I've got a php file that outputs the html for the mysql data into a long strong, the part I need to change is:
$display_string .= "<td class='blank'><input type=\"button\" VALUE=\"Delete\" onclick='delFunction(" . $row['ID'] . ")' ></td>";
Next my delete function:
function delFunction(ID){
// confirm delete
if (!confirm(\"Are you sure you want to delete?\")) return false;
var ajaxRequest; // The variable that makes Ajax possible!
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(\"Your browser broke!\");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var queryString = \"?ID=\" + ID
ajaxRequest.open(\"GET\", \"delete_row.php\" + queryString, true);
ajaxRequest.send(null);
}
To my understanding of your problem, I am posting some codes for both front and back ends
Front-End Sample Code
<body>
<form action="delete.php" method="post">
<input type="checkbox" name="del_chk[]">Item1
<input type="checkbox" name="del_chk[]">Item2
<input type="checkbox" name="del_chk[]">Item3
<input type="checkbox" name="del_chk[]">Item4
.
.
<input type="submit">
</form>
................
Your back-end code would now be...
<?php
if(isset($_POST['del_chk'])){
$chkbox=$_POST['del_chk'];
foreach($chkbox as $key=>$value) {
//Now you can get your value and use it in mysql delete statements
//for example
$del_query="DELETE FROM `yourtable` WHERE `pri_key`=$value;";
if(mysql_query($del_query)) {
echo "Successful Deletion of: ".$value;
}
else
{
echo "Unsuccessful Deletion of: ".$value;
}
} //end foreach
}
?>
I don't know much of ajax. but you can use ajax to call this page..
I have a simple setup to allow a user to change his content on a page.
It calls up a query and populates the area with the results. My goal is to have the user enter in some new information, insert that info into the table, and requery the results.
Here is my Javascript function that is called:
function addLink(){
var ajaxRequest;
if(window.XMLHttpRequest){
ajaxRequest = new XMLHttpRequest();
}
else{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status==200){
var ajaxDisplay = document.getElementById('links');
ajaxDisplay.innerHTML = "<?php displayTitle('Links'); ?><?php displayContent('Links', $isLoggedIn); ?>"
}
var imgURL = document.getElementById('links_img').value;
var linkURL = document.getElementById('links_link').value;
var queryString = "?imgURL=" + imgURL + "&linkURL=" + linkURL;
ajaxRequest.open("GET", "addLink.php" + queryString, true);
ajaxRequest.send();
}
}
Those PHP functions merely spit out the HTML, the displayContent() specifically for the actual table data.
Here is my HTML for adding some info to the database:
<center><br /><br />
Image URL: <input type='text' id='links_img' />
Link URL: <input type='text' id='links_link' />
<input type='button' onclick='addLink()' value='add' /></center>
Here is my PHP for adding the information:
<?php
mysql_connect([sensitive information]) or die(mysql_error());
mysql_select_db([sensitive information]) or die(mysql_error());
$result = mysql_query("INSERT INTO linksMod (Image URL, Link URL) VALUES ("$_GET['imgURL']","$_GET['linkURL']") or die(mysql_error());
mysql_close();
?>
Thee page does nothing when I click the 'Add' button.
Thanks for your help!
These lines:
var imgURL = document.getElementById('links_img').value;
var linkURL = document.getElementById('links_link').value;
var queryString = "?imgURL=" + imgURL + "&linkURL=" + linkURL;
ajaxRequest.open("GET", "addLink.php" + queryString, true);
ajaxRequest.send();
need to be outside the "readystatechange" handler function. The way it's written now, they're inside the handler function and, since it isn't called, they'll never happen.
ajaxDisplay.innerHTML = "<?php displayTitle('Links'); ?><?php displayContent('Links', $isLoggedIn); ?>"
I don't think it's possible to embed php in javascript .
This is my code:
<html>
<head>
<script>
comenzar = function(){
document.getElementById('gene').onclick = xmlhttpPost("generador.php");
}
xmlhttpPost = function(strURL){
xmlHttpReq = false;
self = this;
self.xmlHttpReq = new XMLHttpRequest();
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function(){
if(self.xmlHttpReq.readyState == 4){
update(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getquerystring());
}
getquerystring = function(){
form = document.getElementById('formu');
combi = document.getElementById('sele').options[document.getElementById('sele').selectedIndex].value;
qstr = "tres=" + escape(combi);
return qstr;
}
update = function(resu){
document.getElementById('tag').innerHTML = resu;
}
window.onload = comenzar;
</script>
</head>
<body>
<form id=formu>
<select id=sele>
<option>C</option>
<option>v</option>
</select>
<button id=gene><p>generate</p></button>
</form>
<p id=tag></p>
</body>
</html>
//generador.php
<?php
echo( "tu combinacion" . $_POST['tres'] );
?>
The problem is not the getting of the value. The hook are these two things:
document.getElementById('gene').onclick = xmlhttpPost("generador.php");
...you may think that you set something to be executed to the onclick-Event of the button, but you don’t. This function will be executed immediately, not onclick.
You should write it that way:
document.getElementById('gene').onclick = function(){xmlhttpPost("generador.php");}
The other problem:
The default type of a <button> is submit, so if you click on the button, the form will be sent.
You can either set the type of the button to "button" or cancel the submitting of the form via JavaScript, otherwise your Ajax request is useless, because the form will be sent (and the page reloaded).