I'm writing a little install script for my current project. The first "step" of this script asks the user for his MySQL credentials and tests them. Everything is done via an AJAX query using jQuery's $.ajax.
My client-side script looks like this:
<section class="col-md-6" style="display: none;" id="pane2">
<h1 style="text-align: center;">MySQL Setup</h1>
<form method="POST" action="stuff.php" role="form" class="installform">
<input type="text" class="form-control" placeholder="Host" name="host" id="host">
<input type="text" class="form-control" placeholder="Database Name" name="dbname" id="dbname">
<input type="text" class="form-control" placeholder="Username" name="sqlusername" id="sqlusername">
<input type="password" class="form-control" placeholder="Password" name="sqlpassword" id="sqlpassword">
</form>
<a><button class="btn btn-primary btn-lg btn-block" id="sqlbutton">Next</button></a>
<script>
$(function() {
$('#sqlbutton').click(function() {
var host = $('#host').val();
var dbname = $('#dbname').val();
var username = $('#sqlusername').val();
var password = $('#sqlpassword').val();
var credentials = "host=" + host + "&dbname=" + dbname + "&username=" + username + "&password=" + password;
$.ajax({
type: "POST",
url: "sqlchecker.php",
data: credentials,
success: function(data) {
if (data == 'success') {
$('#sqlbutton').html("All right.");
}
else {
$('#sqlbutton').html("Something is wrong");
}
}
});
});
});
</script>
And my sqlchecker.php script is currently this:
<?php
$host = $_POST['host'];
$dbname = $_POST['dbname'];
$username = $_POST['username'];
$password = $_POST['password'];
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
// Opens a connection to the database using PDO
try {
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Couldn't connect to the database. Error code: " . $ex->getMessage());
}
echo('success');
?>
Of course, at the moment, it makes absolutely no distinction between errors, if there wasn't any, it displays "All right." and if there was one, then it displays "Something is wrong". But I'd like it to be a bit more specific and tell the user what exactly is wrong in the query.
I'm looking to kind of "parse" PDO exceptions, the problem is that they return a complete sentence that is almost impossible to use in an if statement. Is there a way to configure PDO at the connection so it only returns an error code, that would be way easier to interpret using jQuery?
Thanks a lot for your answers!
A call to getCode on the exception should give you a code you can work with. You could then switch on this and give your user some appropriate feedback. This would definitely be cleaner than trying to manipulate the string message returned.
$errorCode = $ex->getCode();
switch($errorCode) {
case 1000:
//...
break;
default:
//...
break;
}
For my sql I believe the error code will be listed here:
https://dev.mysql.com/doc/refman/5.0/en/error-messages-server.html
Related
I want to validate my form using JQuery and use php to send it to my database.
This is what I've tried:
<body>
<form id="first_form" method="post" action="">
<div>
<label for="first_name">First Name:</label>
<input type="text" id="first_name" name="first_name"></input>
</div>
<div>
<label for="last_name">Last Name:</label>
<input type="text" id="last_name" name="last_name"></input>
</div>
<div>
<label for="handphone">Handphone:</label>
<input type="text" id="handphone" name="handphone"></input>
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
<script>
$(document).ready(function() {
$('#first_form').submit(function(e) {
e.preventDefault();
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var handphone = $('#handphone').val();
$(".error").remove();
if (first_name.length < 1) {
$('#first_name').after('<span class="error">This field is required</span>');
return false;
}
if (last_name.length < 1) {
$('#last_name').after('<span class="error">This field is required</span>');
return false;
}
if (handphone.length < 1) {
$('#handphone').after('<span class="error">This field is required</span>');
return false;
}
});
});
</script>
<?php
$first_name = "<script>var first_name = $('#first_name').val();</script>";
$last_name = "<script>var first_name = $('#last_name').val();</script>";
$handphone = "<script>var first_name = $('#handphone').val();</script>";
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO vali (first_name, last_name, handphone)
VALUES (first_name, last_name, handphone)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
</body>
So as you can see, the first part is just the html and form.
The second part is where I used Jquery to validate (which works).
Now the issue is at the php part, where it sends the data to my database as empty.
The logic behind my php code is that, I take the values of the variables I set in Jquery and just update it to the database. But its updating empty values.
I tried to return false in Jquery, but its not working for me. May I know what am I doing wrong here?
Firsty, you have to understand JavaScript in this case is a client-scripting language and PHP is a server-scripting language. Variables can't be pass from JavaScript to PHP is the <script> tag.
Secondly, we have different types of requests; GET, POST, PUT, DELETE and so on. This we can check via PHP. A form can only send two types of request as at the time of me typing this answer, GET and POST request, this is the method value you set in your form. Every value set in a form can be accessed in the request global array and the name of the value being the key/indetifier. $_GET[] if you sent a get request and $_POST[] if you sent a post request.
In your form above, your method is set to POST, meaning all the values would be available in the global $_POST[].
When ever a page loads, the server script gets loaded first before the Client Side / HTML / CSS and other resources used by your document.
PHP has a function called isset() which is used to check if a variable available regardless it's value which is very useful for form validation.
If you ever have PHP codes in file performing logic/operations, it is advisable you placed them topmost of you file since it isn't used in rendering your document/view.
From your code, you should edit as
<?php
if(isset($_POST['submit'])){
// This block will only be executed when a submit button is triggered
//Make your connection here, it is not a must but good practice to always make connection first in order to make it available everywhere. Ensure to check if connection was successful or not.
$first_name = $_POST['first_name']; // this gives you the exact value you passed in the form.
...
// All you variables should be assigned using the above method
//in the above assignation of variables, we didn't sanitize. mysqli has a method real_escape_string() which does that for us. Ensure to always sanitize and properly validate inputs you send to your DB
//Sanitizing inputs
$first_name = $con ->real_escape_string($first_name);
// Do the above for other inputs, then you are good to perform an insert.
$result = $conn->query($sql);
if($result){
//Record has been inserted, you can choose to redirect or do some other logic
}else{
//Record was not successfully inserted. Print your error if in development to get an insight to what went wrong
}
}
$conn->close()
?>
So I'm making a simple login/registration web application but I keep getting the following error:
XML Parsing Error: no root element found Location: file:///C:/xampp/htdocs/EdgarSerna95_Lab/login.html Line Number 37, Column 3:
and
XML Parsing Error: no root element found Location: file:///C:/xampp/htdocs/EdgarSerna95_Lab/php/login.phpLine Number 37, Column 3:
here is my login.php
<?php
header('Content-type: application/json');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "jammer";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
header('HTTP/1.1 500 Bad connection to Database');
die("The server is down, we couldn't establish the DB connection");
}
else {
$conn ->set_charset('utf8_general_ci');
$userName = $_POST['username'];
$userPassword = $_POST['userPassword'];
$sql = "SELECT username, firstName, lastName FROM users WHERE username = '$userName' AND password = '$userPassword'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response = array('firstName' => $row['firstNameName'], 'lastName' => $row['lastName']);
}
echo json_encode($response);
}
else {
header('HTTP/1.1 406 User not found');
die("Wrong credentials provided!");
}
}
$conn->close();
?>
I've done some research about xml parsing errors but I still cant manage to make my project work, ive tried with Google Chrome and Firefox
AHA! Got this today for a reason which will make me look pretty silly but which might one day help someone.
Having set up an Apache server on my machine, with PHP and so on... I got this error... and then realised why: I had clicked on the HTML file in question (i.e. the one containing the Javascript/JQuery), so the address bar in the browser showed "file:///D:/apps/Apache24/htdocs/experiments/forms/index.html".
What you have to do to actually use the Apache server (assuming it's running, etc.) is go "http://localhost/experiments/forms/index.html" in the browser's address bar.
In mitigation I have up to now been using an "index.php" file and just changed to an "index.html" file. Bit of a gotcha, since with the former you are obliged to access it "properly" using localhost.
I had same situation in Spring MVC Application as it was declared as void, changing it to return String solved the issue
#PostMapping()
public void aPostMethod(#RequestBody( required = false) String body) throws IOException {
System.out.println("DoSome thing" + body);
}
To
#PostMapping()
public String aPostMethod(#RequestBody( required = false) String body) throws IOException {
System.out.println("DoSome thing" + body);
return "justReturn something";
}
Assuming you are working with javascript, you need to put a header in front of echoing your data:
header('Content-Type: application/json');
echo json_encode($response);
Make sure you're php server is running and that the php code is in the appropriate folder. I ran into this same issue if the php was not there. I also recommend putting your html in that same folder to prevent cross-origin errors when testing.
If that is not the issue, ensure that every SQL call is correct in the php, and that you are using current php standards... Php changes quickly, unlike html, css and Javascript, so some functions may be deprecated.
Also, I noticed that you may not be collecting your variable correctly, which can also cause this error. If you are sending variables via form, they need to be in proper format and sent either by POST or GET, based on your preference. For example, if I had a login page for a maze game:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<form class="modal-content animate" method="post">
<div class="container">
<label><b>Username</b></label>
<input type="text" id="usernameinput" placeholder="Enter username" name="uname" required>
<label><b>Password</b></label>
<input type="password" id="passwordinput" placeholder="Enter Password" name="psw" required>
<button onclick="document.getElementById('id01').style.display='block'">Sign Up</button>
<button type="button" id="loginsubmit" onclick="myLogin(document.getElementById('usernameinput').value, document.getElementById('passwordinput').value)">Login</button>
</div>
</form>
JavaScript
function myLogin(username, password){
var datasend=("user="+username+"&pwd="+password);
$.ajax({
url: 'makeUserEntry.php',
type: 'POST',
data: datasend,
success: function(response, status) {
if(response=="Username or Password did not match"){
alert("Username or Password did not match");
}
if(response=="Connection Failure"){
alert("Connection Failure");
}
else{
localStorage.userid = response;
window.location.href = "./maze.html"
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
var response = xhr.responseText;
console.log(response);
var statusMessage = xhr.status + ' ' + xhr.statusText;
var message = 'Query failed, php script returned this status: ';
var message = message + statusMessage + ' response: ' + response;
alert(message);
}
}); // end ajax call
}
PHP
<?php
$MazeUser=$_POST['user'];
$MazePass=$_POST['pwd'];
//Connect to DB
$servername="127.0.0.1";
$username="root";
$password="password";
$dbname="infinitymaze";
//Create Connection
$conn = new MySQLi($servername, $username, $password, $dbname);
//Check connetion
if ($conn->connect_error){
die("Connection Failed: " . $conn->connect_error);
echo json_encode("Connection Failure");
}
$verifyUPmatchSQL=("SELECT * FROM mazeusers WHERE username LIKE '$MazeUser' and password LIKE '$MazePass'");
$result = $conn->query($verifyUPmatchSQL);
$num_rows = $result->num_rows;
if($num_rows>0){
$userIDSQL =("SELECT mazeuserid FROM mazeusers WHERE username LIKE '$MazeUser' and password LIKE '$MazePass'");
$userID = $conn->query($userIDSQL);
echo json_encode($userID);
}
else{
echo json_encode("Username or Password did not match");
}
$conn->close();
?>
It would help if you included the other parts of the code such as the html and JavaScript as I wouldn't have to give my own example like this. However, I hope these pointers help!
Pretty new to php/mysql and jquery, and I'm having trouble getting my form data to upload to my mysql db. I've tried a few different approaches and done my research, but none of the suggestions I've found online are working for me, which is why I'm posting here. So here's my most recent failed approach:
in my index file:
<head>
...
<script type="text/javascript">
$(document).ready(function() {
// Announcement form AJAX submit
$('#announcementForm').submit(function() {
$.ajax({
url: 'ajax.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
if (data.error) {
$('#error').css('display', 'block');
} else {
$('#note').show();
$('#error').hide();
$('#fields').hide();
}
}
});
return false;
});
});
</script>
</head>
<body>
...
<form class="dl_form" id="announcementForm" method="post">
<dl>
<dt>Announcement</dt>
<dd><textarea id="Announcement" sytle="width: 300px; height: 150px;" name="Announcement"></textarea></dd>
</dl>
<dl>
<dt>Announcement Type:</dt>
<dd><input type="radio" name="Type" value="schedule">Scheduling</input></dd>
<dd><input type="radio" name="Type" value="general">General</input></dd>
</dl>
<dl>
<dt></dt>
<dd><input type="submit" value="submit" /></dd>
</dl>
</form>
<div id="note">
<p>Announcement posted successfully!"</p>
</div>
<div id="error">You haven't completed all of the required fields</div>
And then in my ajax.php file I have (some lines have been replaced with "######" for security reasons):
<?php
//database credentials
$server = '######';
$username = '######';
$password = '######';
$database = '######';
$connect = mysql_connect($server, $username, $password ) or die(mysql_error.'error connecting to db');
//select database
mysql_select_db($database, $connect) or die(mysql_error.'error selecting db');
//$typeValue = $('input:radio[name=Type]:checked').val());
if (!empty($_POST)){
$Announcement = $_POST['Announcement'];
$Type = $_POST['Type'];
if (!empty($Announcement) && !empty($Type) )
{
//insert data into db
mysql_query("INSERT into announcements (AnnouncementID, Type, Announcement)
VALUES ('', '".$Type."', '".$Announcement."')") or die(mysql_error());
}else {
echo json_encode(array(
'error' => true,
'msg' => "You haven't completed all required fields!"
));
exit;
}
}
?>
Any help you guys can provide would be much appreciated.
Thanks
UPDATE IN RESPONSE TO Jay Blanchard:
I just ran the console in my browser. The only error I'm getting is:
SCRIPT1004: Expected ';'
in reference to the first line of my JS:
$function() {
...
UPDATE 2:
Just updated my code to reflect my most recent changes...before I could at least trigger the submit click even and the fields would empty, indicating that at least something was happening. With my new round of changes however, not even that triggers, so I'm still pretty stuck
In your php you've made a mistake with your echo statement its not jason_encode instead its json_encode.
Additionally
Also you Should remove AnnouncementID from your query if in database it is auto increment, because db will warn you for incorrect integer value for column AnnouncementID.
EDIT: In your php part in statement
mysql_query("INSERT into announcements (AnnouncementID, Type, Announcement)
VALUES ('', '".$Type."', '".$Announcement"')") or die(mysql_error());
You are forgetting a concatenation operator . after '".$Announcement which should be
mysql_query("INSERT into announcements (AnnouncementID, Type, Announcement)
VALUES ('', '".$Type."', '".$Announcement."')") or die(mysql_error());
and in your jquery instead of
$function() {
use
$(document).ready(function(){
Below i have written code of a soap webservice in php with its client,It is working fine, actually m new to php so don't know how to post data to my server php service from html page, i know by using javascript it is possible but how.....any help by code or helpful link will be appreciated.
<?php
require_once "lib/nusoap.php";
function getProd($username,$password) {
$user = "root";
$pswd = "root";
$db = "LOGIN";
$conn = mysql_connect('localhost', $user, $pswd);
mysql_select_db($db, $conn);
//run the query to search for the username and password the match
$query = "SELECT * FROM PEOPLE WHERE USERNAME = '$username' AND PASSWORD = '$password'";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens
if(mysql_num_rows($result) > 0)
$valid="LoginSucessful";
else
$valid="LoginFailed";
return $valid;
}
$server = new soap_server();
$server->configureWSDL("productlist", "urn:productlist");
$server->register("getProd",
array("username" => "xsd:string","password" => "xsd:string"),
array("return" => "xsd:string"),
"urn:productlist",
"urn:productlist#getProd",
"rpc",
"encoded",
"Get a listing of products by category");
if ( !isset( $HTTP_RAW_POST_DATA ) ) $HTTP_RAW_POST_DATA =file_get_contents( 'php://input' );
$server->service($HTTP_RAW_POST_DATA);
#client of service#
<?php
require_once "lib/nusoap.php";
$client = new nusoap_client("http://localhost/expa/productlis.php");
$result = $client->call("getProd",array("category" => "admin","item" => "admin"));
Overall just need to pass parameter to the php function.
There are few ways to get data from the user:
Pass data via url parameters:
Foo equals Bar
<?php
$foo = (isset($_GET['foo'])) ? $_GET['foo'] : 'undefined';
echo "foo equals $foo";
?>
A straight up form:
// index.php
// An example form that loops back to itself.
<form action="index.php" method="post" id="the_demo_form">
<fieldset>
<label for="foo">Foo</label>
<input type="text" name="foo">
</fieldset>
<input type="submit"/>
</form>
<pre>
<?php
// the $_POST global contains the data sent in the request.
var_dump($_POST);
?>
</pre>
Ajax
If you need to submit the data without reloading via javascript the page you would use AJAX.
This is an example using jQuery that catches the form submit event and sends the form without reloading the page.
// index.php
// An example form
<form action="index.php" method="post" id="the_demo_form">
<fieldset>
<label for="foo">Foo</label>
<input type="text" name="foo">
</fieldset>
<input type="submit"/>
</form>
<script>
$(document).ready(function(){
$("#the_demo_form").submit(function(event){
// This prevents the browser from following the form.
event.preventDefault();
// We take the data and send it to server via AJAX.
$.ajax({
// set this to server side script
url : "index.php",
data : $(this).serialize(),
success: function(data){
alert("eureka!");
}
});
});
});
</script>
I want to send some data to php to change something in my MySQL database, but I keep getting this 405 error 'POST method not allowed'. I googled a lot, but can't find any useful solution. Can someone explain to me what I'm doing wrong?
I'm using Razor inside HTML to render the data on the webpage:
#foreach(var row in db.Query(getKamers))
{
<form id="#row.id" action='_DataConn.php' method='post' class='ajaxform'>
<input type="text" value="#row.id" name="id" id="td-id" />
<input type="text" value="#row.oppervlakte" name="oppervlakte" id="td-opp" />
<input type="text" value="#row.locatie" name="locatie" id="td-loc" />
<input type="text" value="#row.type" name="type" id="td-type" />
<input type="text" value="#row.kamernr" name="nummer" id="td-kamernr" />
<input type="text" value="#row.vrij" name="vrij" id="td-vrij" />
<input type="submit" value="opslaan" name="opslaan" id="#row.id" />
</form>
}
then I have this JavaScript file:
$(document).ready(function () {
$('.ajaxform').submit(function () {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
console.log(data);
}
});
return false;
});
});
and my PHP looks like this:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$dbname = "Studentenkamers";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$id = $_POST['id'];
$oppervlakte = $_POST['oppervlakte'];
$locatie = $_POST['locatie'];
$kamernr = $_POST['nummer'];
$type = $_POST['type'];
$vrij = $_POST['vrij'];
echo 'ok'
// Escape User Input to help prevent SQL Injection
$id = mysql_real_escape_string($id);
$oppervlakte = mysql_real_escape_string($oppervlakte);
$locatie = mysql_real_escape_string($locatie);
$kamernr = mysql_real_escape_string($kamernr);
$type = mysql_real_escape_string($type);
$vrij = mysql_real_escape_string($vrij);
//build query
//"UPDATE Studentkamer SET oppervlakte='" + room[1] + "', locatie='" + room[2] + "', type='" + room[3] + "', vrij='" + room[4] + "' WHERE id='" + room[0] + "'";
$query = "UPDATE Studentkamer SET oppervlakte = '$id', locatie = '$locatie', type='$type', kamernr = '$kamernr', vrij = '$vrij' WHERE id='$id'";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
?>
EDIT:
Below is the link to a screenshot of the error info, does it has something to do with the static context?
http://img41.imageshack.us/img41/9139/errorde.jpg
I am working in Webmatrix using localhost, do I need to put this website online for it to work?
Look at the submit button and form id. Does the razor translate that into a valid string? It looks to me as if the ids contain #. The # in the id values is not permitted according to http://www.w3.org/TR/html4/types.html. This might be passed as values containing those characters
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number
of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
Try
#(row.id)
Reference - MVC3 Razor syntax. How do I convert this ASP.NET style to Razor. (also issues with # within quotes)
You have to allow POST method in config for your web-server