$POST PHP Issue - php

I wonder whether someone may be able to help me please.
I'm currently working on a website that through a User Input Form, XML and PHP, users will add and save google map information to my SQL database.
I've successfully been using one of the examples on the Google site which explains how to use PHP and XML to save user defined information to the database.
The example use the $GET method, but from the information I've been reading on the web, the $POST option does seem the better method to use.
However when I change my coding to the $POST method I can create a record on the database but the values keyed into the form are not copied scross to the database. I know that I'm perhaps making a really stupid beginners mistake, but I just wondered whether someone may be able to tell me what I need to do to get it to work.
I've included cut down versions of the files below.
Many thanks
Chris
HTML Form Submit Button
function savedata() {
var locationname = document.getElementById("locationname").value;
var returnedaddress = document.getElementById("returnedaddress").value;
var url = "phpfilename.php?locationname=" + locationname + "&returnedaddress=" + returnedaddress;
downloadUrl(url, function(data, responseCode) {
if (responseCode == 200 && data.length <= 1) {
}
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('POST', url, true);
request.send(null);
}
function doNothing() {}
</script>
HTML Form
<body>
<label><br />
</label>
<form name="searchforlocationformgeocode" id="searchforlocationformgeocode">
<div>
<label for="address">
<div align="center">
<p>Location Name</p>
<p>
<input name="locationname" type="text" id="locationname" size="80" />
</p>
</div>
<p align="left"><label>Returned Address</label> </p>
<div align="left">
<input name="returnedaddress" type="text" id="returnedaddress" size="100" />
</div>
PHP File
<?php
require("phpfilename.php");
// Gets data from URL parameters
$locationname = $_POST['locationname'];
$address = $_POST['returnedaddress'];
// Opens a connection to a MySQL server
$connection = mysql_connect ("xxxxxxxx", $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Insert new row with user data
$query = sprintf("INSERT INTO tablename " .
" (locationname, address) " .
" VALUES ('%s', '%s', '%s' );",
mysql_real_escape_string($locationname),
mysql_real_escape_string($address));
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>

You are passing the values using a query string, to get them you need to use $_GET.
var url = "phpfilename.php?locationname=" + locationname + "&returnedaddress=" + returnedaddress;
To use $_POST, instead of adding the encoded name/value pairs to the end of the URL, send them via the request.send() method:
request.send("locationname=" + locationname + "&returnedaddress=" + returnedaddress);

A general rule of thumb is that if your target page is supposed to just retrieve some info using GET is just fine however if your data is supposed to make any changes to the database etc. you should always use POST.
BTW, your form tag must contain the method you are using to submit the data in this case method="post"
<form name="searchforlocationformgeocode" id="searchforlocationformgeocode" method="post">

Related

Why can't i fetch data from my SQL database, in a html document, using php?

So I am writing a API, on the front-end it uses HTML, JS and CSS, and on the back end it uses PHP which will have access to my SQL database.
My task is once a button is clicked, create a function that will send information that is encoded in JSON off to the .php file, there I need to decode that object from JSON to PHP, then connect to the SQL database, and return relevant information encoded in JSON back to the HTML page, and later functionality will be able to update/delete certain data.
This API uses two main pages being the HTML and PHP files, along with the SQL database. Can somebody tell me why this is not working and how I can fix it? To clarify I would like to be able to select a radio button option, then press the app_list_button, which will return all Applications sorted by app_name or their review rating. Any help will be greatly appreciated and if I am able to structure anything better please let me know.
index.html
<div id='app_content'>
<label>Refine search by</label>
</br>
<input type="radio" id="name_radio">
<label>Name</label>
</br>
<input type="radio" id="rating_radio">
<label>Rating</label>
</br>
<button id="app_list_button" onclick="load_list_function()">View App List</button>
</br>
<p id='app_list_p'></p>
<input type="submit" name="app_detail_button" value="View App
Details">
</br>
</div>
</div>
</body>
<script>
var app_list_bttn = document.getElementById('app_list_button');
var radio = {};
//List apps
function load_list_function() {
var xhr = new XMLHttpRequest();
//name radio checked
radio.sortByName = document.getElementById('name_radio').checked;
//rating radio checked
radio.sortByRating =
document.getElementById('rating_radio').checked;
document.getElementById('app_list_p').innerHTML = this.responseText;
xhr.open('GET', 'API.php', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(radio));
}
</script>
API.php
<?
$conn = mysqli_connect('localhost', '30319329', 'password', 'Application');
$errors = array();
$json_response = array();
$radio_req = file_get_contents('php://input');
$radio_result = json_decode($radio_req);
//get a list of all apps
//encode into json to send back
if ($radio_result - > sortByName == true) {
//order by name
$results = mysqli_query($conn, "SELECT app_name FROM App");
while ($row = mysqli_fetch_assoc($results)) {
// You can modify the $row here as well, or filter out certain rows
$json_response[] = $row;
}
header("Content-Type: application/json");
echo json_encode($json_response);
} else($radio_result - > sortByRating == true) {
//order by rating
//order by name
$results = mysqli_query($conn, 'SELECT app_name, rating FROM App, App_Review ORDER BY rating ');
while ($row = mysqli_fetch_assoc($results)) {
// You can modify the $row here as well, or filter out certain rows
$json_response[] = $row;
}
header("Content-Type: application/json"); echo json_encode($json_response);
}
$conn - > close();
?>
Most likely the issue is this:
file_get_contents('php://radio');
That will not give you anything, it needs to be:
file_get_contents('php://input');
Also, when you do:
document.getElementById('app_list_p').innerHTML = this.responseText;
you are setting the innerHTML before you've even done the ajax request - this in this context is the window, so this.responseText will always be undefined.
You need to do it more like:
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
document.getElementById('app_list_p').innerHTML =xhr.responseText;
}
}

How to fetch data and pass. into form and response customername onkeyup or keydown json and php

This is Mysql DB connection.php
<?php
$conn = new mysqli("localhost", 'root', "", "laravel");
$query = mysqli_query($conn,"select * from customers");
while ($result2=mysqli_fetch_assoc($query)) {
$data[] = $result2['customername'];
}
echo json_encode($data);
?>
The json is not responding onKeyup or keydown it is displaying the whole output. But i want to display only the current related matched names on to display. I was new to json and ajax. i think ajax and json both respond the same.
<form action="">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
<script>
function showHint(str) {
var xhttp;
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "connection.php?q="+str, true);
xhttp.send();
}
</script>
Thanks for your suggestions. All suggestions are welcome.
How pass into form and response on keyup or keydown and related suggestions customername should display down. I am new to JSON and javascript and examples sites. Thanks in advance. All suggestions are welcome.
You have a couple of options;
One is that you re-pull all the data in an ajax call by appending the text box input to the SQL query in a "WHERE name LIKE %" . $input . "%'"; but this will be costly in terms of speed an network traffic.
Another option and the one I would opt for, is getting all of the names in a SELECT as you have done, then using RegEx within javascript to filter the results shown.
Here is a good link on using regular expressions.
https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
Edit:
None of this is tested as I don't have the means to test right now.
For the first example, I am going to assume you are passing the query via the GET and thus in your PHP file you change your code to as follows:
<?php
// Your DB connection
$conn = new mysqli("localhost", 'root', "", "laravel");
// Initialise the query string
$qString = "SELECT * FROM customers";
// Providing a parameter is sent in the GET request to the PHP page, look for names
// containing that string
isset($_GET['q']) ? $qString .= " WHERE customername LIKE '%" . $_GET['q'] . "%'" : "";
$qHandler = mysqli_query($conn, $qString);
while ($qResult = mysqli_fetch_assoc($qHandler)) {
$data[] = $qResult['customername'];
}
echo json_encode($data);
?>
So when a request is made via call of showHint(str) it will append that str to the query in a 'like' statement, with the %% wildcards. So you put 'art' in the text box, it will return names like 'bART', 'mARTher', etc.

PHP if (isset($_POST['uname'])) not doing anything?

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

Why does this work with Mysql but not Postgres

I am busy learning Ajax and need to use Postgres for the backed DB. I found an example for Mysql which works but when I convert it to Postgres, it stops working. I have not made any changes to the HTML code when swapping from Mysql to Postgres.
When I execute the php code at command line (php test.php), it works and outputs the correct number of rows and data.
Here is the php
<?php
$dbh = pg_connect("host=192.168.0.8 dbname=test user=test password=test");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// execute query
$sql = "SELECT * FROM users";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
// iterate over result set
// print each row
while ($row = pg_fetch_array($result)) {
echo "Name: " . $row[1];
echo "<BR />";
}
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
?>
And here is the html
<html>
<head>
<script language="JavaScript" type="text/javascript">
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "test.php";
var fn = document.getElementById("name").value;
var vars = "name="+fn;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
document.getElementById("name").value = "";
}
</script>
<script type="text/javascript">
function setFocus()
{
document.getElementById("name").focus();
}
</script>
</head>
<body onload="setFocus()">
<div>
<form name="input" action="" onsubmit="ajax_post(); return false;">
Barcode : <input type="text" id="name" size="30"><br />
</form>
</div>
<div style="background-color: lightyellow; border: 1px solid black; width: 400; height: 300;">
<div id="status"></div>
</div>
</body>
One thing I have noticed is that when I run the test.php file at command line with postgres, anew-line character is always appended to the end of the data.
Thanks
O
Install Firefox and the Firebug add-on. In Firebug, you can conveniently watch the whole communication between your HTML and PHP page, and there's also a great JS debugger with breakpoints etc. included. You don't seem to have a good idea what the error exactly is, but you should still be able to spot it with these tools.

prototype ajax not properly executing query

So I decided to start using prototype and here's my first question. I'm trying to send out an ajax request to a php page which updates s single record. When I do this by hand (ie: typing the address + parameters it works fine but when I use this code from javascript:
var pars = 'trackname=' + track + '&tracktime=' + time;
new Ajax.Request('php/setSongTime.php', {
method: 'get',
parameters: pars,
onSuccess: function(transport){
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response);
},
onFailure: function(){ alert('Something went wrong...') }
The onSuccess fires and displays the correct information from php, but the update is not made. What the php returns is the UPDATE string, so I'm checking the parameters and they look fine. Does anyone see a problem? Thanks...
Total javascript:
/*This file handles all the user-based computations*/
//variable declarations to be used throughout the session
var untimedSongArray = [];
function beginProcess(){
new Ajax.Request('php/getUntimed.php', {
method: 'get',
onSuccess: function(transport){
var response = transport.responseText || "no response text";
untimedSongArray = response.split("+");
alert(response);
getFlashMovie("trackTimer").timeThisTrack(untimedSongArray[0]);
//alert("Success! \n\n" + response);
//var html = response;
},
onFailure: function(){ alert('Something went wrong...') }
});
}
function getFlashMovie(movieName) {
var isIE = navigator.appName.indexOf("Microsoft") != -1;
return (isIE) ? window[movieName] : document[movieName]; }
function setSongTime(track, time){
alert("track " + track + " has a time of " + time);
//$.get("php/setSongTime.php", { trackname: track, tracktime: time } );
var pars = 'trackname=' + track + '&tracktime=' + time;
new Ajax.Request('php/setSongTime.php', {
method: 'get',
parameters: pars,
onSuccess: function(transport){
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response);
},
onFailure: function(){ alert('Something went wrong...') }
});
}
Total php code:
<?php
//turn on error reporting
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
//header('Content-Type: text/xml');
/////////////Main script
//pull variables
//need to do some error checking here
$trackname = ($_GET['trackname']);
$tracktime = ($_GET['tracktime']);
//remove leading track information
$trackname = str_replace('../music_directory/moe/moe2009-07-18/', '', $trackname);
$trackname = str_replace('.mp3', '', $trackname);
//echo $trackname;
//connect with database
$con = mysql_connect("localhost","root","");
if(!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("musicneverstopped", $con);
//end connecting to database
//////////////////////////////////////////
//update given song time
$sql = "UPDATE songs SET length = ".$tracktime." WHERE unique_song_id = ".$trackname;
echo $sql;
mysql_query("UPDATE songs SET length = '$tracktime' WHERE unique_song_id = '$trackname'");
//error check
//if(!$attempt){
//die(mysql_error());
//}
//////////////////////////////////////////
//close database connection
mysql_close($con);//close mysql connection
?>
Anyone see any failing errors?
Try echoing the exact same SQL you actually run in mysql_query (store it in $sql then pass that into the query, instead of writing out the query twice).
Then try running the query that gets echoed out in the response directly in the mysql command line on your server and see what happens.
Also, just to echo Max on the importance of escaping your SQL queries, I would add to the input sanitisation that you should use bind variables in your query, rather than just concatenating your user input with the rest of the SQL.
Something like this would ensure your variables are suitably escaped to avoid an SQL injection attack.
$sql = "UPDATE songs SET length = '%s' WHERE unique_song_id = '%s'";
$query = sprintf(
$sql,
mysql_real_escape_string($tracktime),
mysql_real_escape_string($trackname)
);
mysql_query($query);
Found it! Somehow I was getting an extra space before the finalized $trackname. ltrim fixed it right up. Thanks to everyone and thanks to those that mentioned security features. I'll definitely implement those. Dan

Categories