I have 2 files in my directory: one is js/form-validation-reg.js and one is HTML/registeruser.php. The javascript file validates a form from another html file which I have already checked; all values are passed all the way till the ajax but the values does not seem to be send to registeruser.php to be send in my database.
form-validation-reg.js:
//data string creation
var dataString = 'name='+ name
+ '&pass=' + pass
+ '&nationality=' + nationality
+ '&contactno=' + contactno
+ '&dateofbirth=' + dateofbirth
+ '&eaddress=' + eaddress
+ '&address=' + address
+ '&gender=' + gender
+ '&monthlysub=' + monthlysub;
//ajax
$.ajax({
type:"POST",
url: "HTML/registeruser.php",
data: dataString,
success: success(),
error:function(jqXHR, textStatus, errorThrown){
alert("Error type" + textStatus + "occured, with value " + errorThrown);
}
});
});
no errors is displayed and i have also tried setting the url as "../HTML/registeruser.php" but it still doesn't work.
PHP file(NOTE:i have also made sure my database details are correct.):
$name = stripslashes(strip_tags($_POST['name']));
$pass = stripslashes(strip_tags($_POST['pass']));
$nationality = stripslashes(strip_tags($_POST['nationality']));
$contactno = stripslashes(strip_tags($_POST['contactno']));
$dateofbirth = stripslashes(strip_tags($_POST['dateofbirth']));
$eaddress = stripslashes(strip_tags($_POST['eaddress']));
$address = stripslashes(strip_tags($_POST['address']));
$gender = stripslashes(strip_tags($_POST['gender']));
$monthlysub = stripslashes(strip_tags($_POST['monthlysub']));
$mysqli = new mysqli("localhost", "root", "","testdb")or exit("Error connecting to the database.");
$stmt = $mysqli->prepare("INSERT INTO user
(name, password, nationality, contactno, dateofbirth, email, address, gender, monthlysub)
VALUES (?,?,?,?,?,?,?,?,?)");
$stmt->execute();
$stmt->bind_param("sssssssss", $name, $pass, $nationality, $contactno, $dateofbirth, $eaddress, $address, $gender, $monthlysub);
$stmt->fetch();
$stmt->close();
$mysqli->close();
try:
success: success,
instead of :
success: success(),
Not sure if this might help, but your dataString variable looks like you're building it to go into a URL which would use get instead of post. It could be that your php script doesn't know how to parse what's getting passed to it because it's looking in the post variables instead. Since you're passing a password you wouldn't want to use get for security reasons though.
You need to be calling the $stmt->bind_param before the $stmt->execute();
If there is still an issue then you need to break it down to see what is given you the issue:
1) Ensure that the Javascript is getting called. Put an alert() in your Javascript and reload the page. If the alert pops up then your are fine there and you can rule out any include URL issues.
2) If you are using Firefox, install firebug and then hit F12 and view the console. You will see the HTML/registeruser.php getting called and you will also be able to see the parameters that are getting sent and other info. You can also do this in Chrome. If the URL is getting called and you are receiving a 200 response then there are no problems there and that is one more thing you can rule out.
3) At this point we have ruled out the Javascript and the Ajax call. So now we focus on the Database connection and then the SQL query. After your connection on the registeruser.php do a select statement of a table that you know has records, echo them out to ensure you definitely have a connection and that you are connected to the correct database.
4) Echo your SQL statement to ensure that it has all the parameters.
By the way, you should also check your error handling, instead of using exit you should be checking for the mysqli error so after the new mysqli call then add this:
if (mysqli_connect_errno()) {
printf("Error connecting to the database: %s\n", mysqli_connect_error());
exit();
}
You may use a library that does that automatically, like http://phery-php-ajax.net already do the bridge between jQuery and PHP automatically
phery.remote('registeruser', {
'name': name,
'pass': pass,
'nationality': nationality,
'contactno': contactno,
'dateofbirth': dateofbirth,
'eaddress': eaddress,
'address': address,
'gender': gender,
'monthlysub': monthlysub,
});
Phery::instance()->set(array(
'registeruser' => function($data){
$data = array_map('strip_tags', $data);
/* rest of mysql code */
return PheryResponse::factory(); // do any DOM manipulation, redirect, etc
}
))->process();
Related
I'm trying to learn how to make a registration form. I was getting an error message: "PDOException : SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'firstname' cannot be null"
Someone told me I could fix it with AJAX, which is something I want to learn anyway. But I'm not sure what I'm doing.
First, I took the PHP code out of my main page (register.php) and put it in a new file (reg-code.php). Then I included reg-code.php in register.php.
Next, I put the following in the head section of register.php:
<script>
submitHandler: function(form) {
$.post(
'/test/register/reg-code.php',
$(form).serialize(),
success: function() {
// display success message or something
It works!
}
);
};
</script>
I fixed one syntax error, but I get another one on the line success: function() {
But I'm not even sure if I'm moving in the right direction. The tutorials are confusing.
This is the PHP code I put in a separate file:
try {
$sql = "INSERT INTO members (firstname, lastname, username, password, password_confirm, email, age) VALUES (:firstname, :lastname, :username, :password, :password_confirm, :email, :age)";
$query = $pdo->prepare($sql);
$query->bindParam(':firstname', $_GET['firstname'], PDO::PARAM_STR);
$query->bindParam(':lastname', $_GET['lastname'], PDO::PARAM_STR);
$query->bindParam(':username', $_GET['username'], PDO::PARAM_STR);
$query->bindParam(':password', $_GET['password'], PDO::PARAM_STR);
$query->bindParam(':password_confirm', $_GET['password_confirm'], PDO::PARAM_STR);
$query->bindParam(':email', $_GET['email'], PDO::PARAM_STR);
$query->bindParam(':age', $_GET['age'], PDO::PARAM_STR);
$query->execute();
} catch (PDOException $e) {
echo 'PDOException : '. $e->getMessage();
}
Do I just have to figure out a syntax error, or do I need to go back to square one?
That error message means that the firstname variable is not being passed in properly. Make sure the name/id of your form field is indeed "firstname".
actually there is no problem with your procedure but
In your members table firstname column is not null and you are passing null value to it
If you use jQuery $.post - then in your php-script you should use $_POST variables:
$query->bindParam(':firstname', $_POST['firstname'], PDO::PARAM_STR);
// etc
Also:
success: function() {
// display success message or something
It works! // this string will cause syntax error
}
Use standard alert() function:
success: function() {
// display success message or something
alert('It works!');
}
First of all, Ajax has nothing to do with that error you get! So you might wan't to consider changing your title.
But anyway.
This means that your $_GET['firstname'] doesn't have a value, which means that no input from your registration form is send trough to your code.
And my suggestion would be that you change all you $_GET varibles to $_POST['inputfieldname'].
Because if you are using a form to send the data, you can't access them trough GET, as GET is used to acces data sent via the URL, so let's say you sent something with the url, and the url was www.yoururl.com/sent.php?something=bla
You would get the value from "something" like so $_GET['something'] and that would now have the data "bla", just to clarify.
The reason it says that the column cannot be null, is because that you have set that rule in your database, and if you removed that, i would just be a blank field.
Hope it helps a bit.
I have a script that is supposed to take a form email value and query the database for duplicates. However, regardless of if I use an existing email (in the database) or a new one, I get "success".
My script looks like this:
if(!empty($_POST['email'])) {
$email = $_POST['email'];
// query the database for duplicates
$query = 'SELECT email FROM user_info WHERE email = "$email"';
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result)){
echo "Email already taken";
} else {
echo "Success";
}
Obviously mysqli_num_rows is returning some kind of data - or none at all.
Does anyone understand why I would not get a returned row if I'm selecting an email that already exists in the database?
EDIT
$('#email').blur( function() {
if(!this.value){
$('#jquery_msg').html("Email can't be empty");
} else if (!filter.test(this.value)){
$('#jquery_msg').html("Not a valid email");
} else {
var emailVal = $('#email').val();
// make an ajax call
$.ajax({
url: 'validation.php',
type: 'post',
data: {'email': 'emailVal'},
success: function(data, status) {
$('#jquery_msg').html(data);
// console.log(data);
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
}
});
The problem is in the data that's being passed to the PHP script via Ajax. What I thought was the value of $('#email').val(); was literally emailVal. Huh..
Now I need to solve how to pass the value into the Ajax call properly.
Thank you all for you help.
This is wrong:
$query = 'SELECT email FROM user_info WHERE email = "$email"';
Apart from the potential sql injection problem, variables do not get parsed when you use single quotes.
You should use a prepared statement instead:
$query = 'SELECT email FROM user_info WHERE email = ?';
Then you can prepare the statement, bind the placeholder and get the results. Check the manual for more information.
A quick solution would also be:
$query = 'SELECT email FROM user_info WHERE email = "'
. mysqli_real_escape_string($db, $email) . '"';
Edit: To trouble-shoot further problems, you should add error handling to your database calls. You can have mysqli throw exceptions telling you exactly what is wrong - if anything - by adding this to the top of your script:
ini_set('display_errors',1);
error_reporting(E_ALL | E_STRICT);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
guys im trying to make a simple commenting system, that when i click the submit the fields will automatically save in the database then fetch it using ajax. but im getting all the data repeatedly instead of getting the recently added data in the database here is the code:
<div id="wrap-body">
<form action="" method="post">
<input type="text" name="username" id="username">
<input type="text" name="msg" id="msg">
<input type="button" id="submit" value="Send">
</form>
<div id="info">
</div>
</div>
<script>
$(document).ready(function (){
$('#submit').click(function (){
var username = $('#username').val();
var msg = $('#msg').val();
if(username != "" && msg != ""){
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:{ 'username' : username , 'msg' : msg},
success: function (data){
var ilan=data[0].counter;
var i = 0;
for(i=0;i<=ilan;i++){
$('#info').append("<p> you are:"+data[i].username+"</p> <p> your message is:"+data[i].mesg);
}
}
});
}
else{
alert("some fields are required");
}
});
});
</script>
PHP:
<?php
$host='localhost';
$username='root';
$password='12345';
$db = 'feeds';
$connect = mysql_connect($host,$username,$password) or die("cant connect");
mysql_select_db($db) or die("cant select the".$db);
$username = $_POST['username'];
$msg = $_POST['msg'];
$insert = "INSERT INTO info(user_name,message) VALUES('$username','$msg')";
if(#!mysql_query($insert)){
die('error insertion'.mysql_error());
}
$get = "SELECT * FROM info ";
$result=mysql_query($get)or die(mysql_error());
$inside_counter = mysql_num_rows($result);
$data=array();
while ($row = mysql_fetch_array($result))
{
$data[] = array(
'username'=>$row['user_name'],
'mesg'=>$row['message'],
'counter'=>$inside_counter
);
}
echo json_encode($data);
?>
SELECT *
FROM "table_name"
ORDER BY "id" desc
LIMIT 1
This is a SQL query to get last record from table. It return last inserted according to id. id should be a auto increment field. I think this will be helpful for you.
Its because you are returning all the row in the table again to the ajax call via
$get = "SELECT * FROM info ";
if you do return all of them again you will have to test if they are not already there before appending them with the jQuery
Perhaps only return the newly inserted row.
or
The jQuery already knows the data it sent to the server, just return success true or false, and then append it if true with the jQuery, no need to return the data back again to the client side
EDIT
I'm not going to write code for you but perhaps these suggestions may help
mysql_query($insert)
link here for reference - http://php.net/manual/en/function.mysql-query.php
will return true of false depending on if the insert statement was successful
you could potentially also check that it acutally inserted a row by calling
mysql_affected_rows()
link here for reference - http://php.net/manual/en/function.mysql-affected-rows.php
then assuming that the insert was successful (i.e. true from mysql_query($insert) or mysql_affected_rows() > 0) simply return successful (i.e. something like
echo json_encode(true);
then on the client side you could do something like the following:
(jQuery Ajax success function only:)
success: function (data){
if (data) {
$('#info').append("<p> you are:"+username +"</p> <p> your message is:"+msg);
}
else
{
alert('There has been an error saving your message');
}
}
using the variables that you just used to send the request
(Please note code samples provided here are only for example, not intended to be used verbatim)
Couple of points though. Is your intention to post the data via ajax only? (i.e. no page refresh) as if that is the case, you will need to return false from you form submit event handler to stop the page full posting. Also you do not appear to have any logic, or are not worried about complete duplicates being entered (i.e. same username, same message) - not sure if you want to worry about this.
I would also potentially look at tracking all the messages via ids (although I don't know your DB structure), perhaps using
mysql_insert_id()
link here FYI - http://php.net/manual/en/function.mysql-insert-id.php
That way each message can have a unique id, may be easier to establish duplicates, even if the username and message are identical
There are numerous ways to deal with this.
Anyway hope that helps
PS - using the mysql_ - group of commands is generally discouraged these days, use the mysqli_ range of function instead
EDIT - got the transfer to happen
.. now I need to figure out how to get the successful transfers to delete each row after it is stored on the host. The function that grabs the data from the browsers SQL database is :
function grabLocal(){
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM entries', [], function(tx, results){
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
var qID = (results.rows.item(i).ID);
var qEmail = (results.rows.item(i).email);
var qPhone = (results.rows.item(i).phone);
var qMonth = (results.rows.item(i).birth_month);
var qDay = (results.rows.item(i).birth_day);
var qYear = (results.rows.item(i).birth_year);
var qMonth = (results.rows.item(i).birth_month);
var qGender = (results.rows.item(i).gender);
var qContest = (results.rows.item(i).contest);
var qStore = (results.rows.item(i).storeNo);
var qDate = (results.rows.item(i).added_on);
var localData = new Array((qEmail),(qPhone),(qMonth),(qDay),(qYear),(qGender),(qContest),(qStore),(qDate));
$.ajax({
type: "POST",
url: "sendIt.php",
data: "email=" + qEmail + "&phone=" + qPhone + "&month=" + qMonth + "&day=" + qDay + "&year=" + qYear + "&gender=" + qGender + "&contest=" + qContest + "&store=" + qStore + "&date=" + qDate,
success: function(){
// delete each row as passed to host
db.transaction(function(tx)
{
tx.executeSql('DELETE FROM entries WHERE ID = ?', [qID]);
});
// alert ("Success");
}
});
}
});
});
}
the php is simple like :
<?php
$link = mysql_connect('host', 'user', 'password');
if (!$link) {
die('Could not connect: ' .mysql_error());
}
echo 'Connected successfully';
$email = htmlspecialchars(trim($_POST['email']));
$phone = htmlspecialchars(trim($_POST['phone']));
$month = htmlspecialchars(trim($_POST['month']));
$day = htmlspecialchars(trim($_POST['day']));
$year = htmlspecialchars(trim($_POST['year']));
$gender = htmlspecialchars(trim($_POST['gender']));
$contest = htmlspecialchars(trim($_POST['contest']));
$store = htmlspecialchars(trim($_POST['store']));
$datestamp = htmlspecialchars(trim($_POST['date']));
mysql_select_db("sandbox_info") or die (mysql_error());
mysql_query("INSERT INTO `infoData` (email, phone, birth_month, birth_day, birth_year, gender, storeNo, contest, added_on) VALUES ('$email','$phone','$month','$day','$year','$gender','$store','$contest','$datestamp')");
echo 'Data uploaded';
mysql_close($link);
?>
Can someone please help explain what is wrong with the delete transaction? It does delete one row each time I run the process but I would like it to delete all of them. I guess I could drop the whole table but I would rather it runs a check after each transfer to the remote host and then deletes the local data. I would also appreciate any tips on how this code could just be improved in general. Thanks in advance for any advice!
REVELATION
OK i echoed back the qID in the success and found out since it is deleting out each row it is then giving a new id to the next available row and keeps echoing out the same id over and over. So... I know the problem but still need some help to find the fix.
You seem to have described it well enough: if you already have HTTP POST support in your app (using java.net.URL or HttpClient) and a PHP script that works on the server, you'll need to:
Detect when someone is online (look at their IP address or try and connect to your server).
Generate a list of all unsaved transactions: you've got the basic code for that above, maybe you need some flag.
For each row, generate a POST to the server: if the POST succeeds (returns a 200 success code) then delete the row from the local database (or mark it as synchronized in some other way).
That should do it?
I'm not 100% clear on what you are trying to do but...
You could have one side generate a list of INSERT statements from the data that would be executed on the other side.
Just wondering about a security issue. Right now I'm using the following function to delete movies from my database:
function deleteVideo(video_id){
function mycallbackform(v,m,f){
if(v=="yes"){
$.ajax({
type: "POST",
url: "delete.php?action=video",
data: "video_id=" + video_id,
success: function(html){
if(html == "1"){
//$("#result").html(html);
$("#row_"+video_id).fadeOut("slow");
$("#result").show();
$("#result").html("<div class='notification success png_bg'> <div><?php echo $LANG_video_succesfull_delete; ?> </div></div>");
setTimeout(function(){ $('#result').fadeOut('slow'); }, 5000);
}else{
$("#result").show();
$("#result").html(html);
}
}
});
}
}
$.prompt('Are you sure?',{ buttons: { Ok: 'yes', Cancel: 'no'}, callback: mycallbackform});
}
At the back end the following code is executed:
/*** DELETE data ***/
/*** prepare the SQL statement ***/
$stmt = $dbh->prepare("DELETE FROM videos WHERE username=:username AND videos_id=:video_id");
$stmt->bindParam(':username', $currUser);
$stmt->bindParam(':video_id', $video_id);
/*** execute the prepared statement ***/
$stmt->execute();
The username is stored in a session in this case.
Is there any way user A will be able to delete user B data with this code?
I was thinkinig to add a query to check if the current user is the same user who added the video in the database. If not he can't delete the data. But is this necessary or is this code safe enough?
Thanks in advance.
You'd better store a unique user id in the session. What if there are two people with the same username?
Edit: If the username is unique, it is quite safe. It is not possible to change the value of a session variable working the client side, unless you've made a terrible mistake in your PHP code. But if you're sure the session variable is always set correctly, you don't have to worry.