guestbook ajax php jquery - php

Have been trying to make a guestbook with jquery, ajax and php, I have been able to reed and print out everything inside the database but for some reason I cant save what I write in the database and then print it out as a post in the guestbook, if someone could see what I am doing wrong I would appreciate it! (for now I only try to get the username inside the database)
this is the jquery:
$("#newPost").bind('click', function(){
var userName = $('#userName').val();
var message = $('#message').val();
$.ajax({
url: "server.php?action=newPost",
type: "POST",
data: {userName: userName},
success: function(data){
if(data == "true"){
alert(data);
$('#posts').prepend('<td>'+userName+'</td>');
$('#userName').val('');
}
else{
alert('Something went wrong while trying to save!');
}
},
error: function(xhr, error){
alert('Could not connect to server!');
}
});
});
this is the server.php file:
$db = mysqli_connect('localhost', 'username', 'password', 'my_database');
if(isset($GET_['action']) && $GET_['action'] == 'newPost'){
$userName = mysqli_real_escape_string($db, POST_['userName']);
if(mysqli_query($db, "INSERT INTO message (name) VALUES ('$userName')")){
echo "true";
}
else{
echo "false";
}
}
and tis is the html form:
<form action="#">
<p>Name:</p>
<textarea type="text" class="field" id="userName" rows="1" cols="20"></textarea><br/><br/>
<p>Meddelande:</p>
<textarea type="text" class="field" id="message" rows="3" cols="20"></textarea><br/><br/>
<input value="Send" class="button" type="button" id="newPost"></input><br/>
</form>

Try replacing $GET_ and POST_ with $_GET and $_POST
Also your field names are empty, add name="userName" and name="message" to your textarea HTML tags

You forgot the name in your textarea. So $userName is empty.

Related

showing toastr after checking if the password and user name is correct from database

as a practice i made a log in form and linked it with a MySQL database and am trying to show a toastr according to to the result that is if the username and password are correct or not so when the input fields are empty it's showing the error toaster but when i add any thing in the fields it always shows the success toastr i don't know how to fix that
here is my html code
<form class="sing_in_form " method="POST" action="#">
<input id="email" type="text" name="username" placeholder="Email">
<input id="password" type="text" name="password" placeholder="password">
<!--log in button-->
<button type="submit" id="btn" name="submit " value="LOGIN" class="btn-login">Sign In</button>
<p class="sign_up">Don't have account? Sign up</p>
</form>
php
if(isset($_POST['username'])){ //username from the form
$uname=$_POST['username'];//username from the form
$pass_word=$_POST['password'];
$sql="SELECT * FROM `loginform2` WHERE user='".$uname."' And Pass='".$pass_word."' limit 1";
$result= $con->query($sql);
}
and my js code
$(document).ready(function(){
$("#btn").click(function(){
var name = $("#email").val();
var password = $("#password").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'username='+ name + '&password='+ password;
if(name==''||password=='')
{
toastr.error("fill the feilds");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "login(2).php",
data: dataString,
cache: false,
success: function(){
toastr.success("logged in");
}
});
}
return false;
});
});
Do something like this.
Put if(mysqli_num_rows($result) ===1 {echo 1}; after $result= $con->query($sql);
And then edit your ajax request as
success: function(data){
if(data ==1){
toastr.success("logged in");
}else{
//error message goes here
}
}

login with ajax issue

I am trying to create on-page login.
without ajax it works very well. Here is my login.php;
if($_POST)
{
$username =$_POST["username"];
$password =$_POST["password"];
$query = $handler->query("SELECT * FROM members WHERE username='$username' && password='$password'",PDO::FETCH_ASSOC);
if ( $say = $query -> rowCount() ){
if( $say > 0 ){
session_start();
$_SESSION['session']=true;
$_SESSION['username']=$username;
$_SESSION['password']=$password;
echo "ok";
}else{
echo "Couldn't login.";
}
}else{
echo "Wrong username or password.";
}
}
Anyway, here is my java script code;
$(function(){
$("#loginbutton").click(function(){
var username = $("#username").val();
var password = $("#password").val();
if(username != "" && password != ""){
$.ajax("login.php",{
type : "POST",
data : "username="+username+"&password="+password,
success : function(data){
if(data == "ok"){
$("#message").html(data);
}else{
$("#fail").fadeIn();
}
}
});
}
});
});
Even though I put correct login information (when I get "ok" response from login.php, it always outputs $("#fail").fadeIn(); . instead of $("#message").html(data); I couldn't figure out where I am mistaken.
and here is login form:
<div id="login">
<form action="" onsubmit="return false;" method="post">
<input type="text" class="form-control" id="username" name="username" placeholder="Username" autocomplete="off"><br>
<input type="password" class="form-control" id="password" name="password" placeholder="Password" autocomplete="off"><br>
<input class="btn btn-success" type="submit" id="loginbutton" value="Login">
</form>
<div id="message"> </div>
<div id="fail" style="display: none;">failed.</div>
</div>
You are using type as post, but sending parameters as get.Change your ajax like this,
$.ajax("login.php",{
type : "POST",
data : {username:username,password:password},// only this line is changed.
success : function(data){
if(data == "ok"){
$("#message").html(data);
}else{
$("#fail").fadeIn();
}
}
});
Here is a quick example of using post with JQuery AJAX.
$(document).ready(function(){
$.post("login.php", {username:username, password:password}, function(data){
if(data == 'ok'){
$("#message").html(data);
}else{
alert(data);//alert the data you receive. It alerts you if there is any error in php file.
$("#fail").fadeIn();
}
});
});
Hope that was helpful!
Firstly, debug your code like this:
1) On button click you will put alert function inside javascript code. if it is working then move second step.
2) use alert function to print username and password if it comes inside your javascript code and correct as you put into input fields then move third step.
3) use serialize method in javascript.
I hope its help you to get your solution.

parser error in ajax php-login authentication in jquery mobile

Here is my javascript and php code for loging in jquery mobile but i got parser error for this request. please help me with this.
<script>
$("#login").click( function () {
//collect userName and password entered by users
var username = $("#username").val();
var password = $("#password").val();
//call the authenticate function
authenticate(username, password);
});
//authenticate function to make ajax call
function authenticate(username, password) {
$.ajax({url: "http://localhost/track/signinmobile.php",
data: '{"username": "' + username + '", "password" : "' + password + '"}',
dataType: "jsonp",
jsonpCallback: 'successCallback',
async: true,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
success: function (result) {
alert(result);
},
error: function (request,error) {
alert("this is"+ error);
},
successCallback:function(){
}
});
</script>
<div data-role="fieldcontain" class="ui-hide-label">
<form id="login" >
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username"/>
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password"/>
<input type="submit" name="login" id="login" value="Login"/>
</form>
</div>
Is there any error in my javascript code?
Here is my signinmobile.php and the data base connections are working.
<?php include"connection.php";
$email=$_GET['username'];
$password=$_GET['password'];
$user=mysql_query("SELECT * FROM users");
while($row=mysql_fetch_array($user))
{
if (($email==$row['email']) && ($password==$row['password']))
{
$response_array['status'] = 'success';
}
else {
$response_array['status'] = 'error';
}
}
header('Content-type: application/json');
echo json_encode($response_array);
?>
You are missing a } to close the authenticate function.
Besides that your form and the submit button have the same id. It is in general a bad idea to have two html tags with the same id and this means that your function is called after clicking on the form.
You should wrap your script inside a $(document).ready.
$(document).ready(function() {
// your script.
});
This will prevent your script from running before the elements are loaded.
You should also prevent the form from submitting by ending the click function with a return false; statement. This prevents the page refresh.
And I don't have experience with jsonp but it generates an error for me. I would suggest using normal json but I don't know your other plans with the script.
The data you send to the server is a string, you should use a javascript object. This is done by removing the quotes and the plus signs.
data: { username: username, password: password },

Ajax won't post form data to PHP script

I got a form with some data that needs to be sent and I want to do it with ajax. I got a function that respond on an onclick event of a button. When I click the button I got some post data in firebug but it just doesn't reach my PHP script. Does anyone know what's wrong?
JS:
function newItem() {
var dataSet = $("#createItem :input").serialize();
confirm(dataSet); //Below this code box is the output of this variable to check whether it is filled or not
var request = $.ajax({
type: "POST",
url: "/earnings.php",
data: dataSet,
dataType: "json"
});
request.done(function(){
$('.create_item').children(".row").slideUp('100', 'swing');
$('.create_item').children("h2").slideUp('100', 'swing');
confirm("succes");
});
request.fail(function(jqXHR, textStatus) {
confirm( "Request failed:" + textStatus );
});
}
dataSet result when the form is completly filled in:
id=123&date=13-09-2013&amount=5&total=6%2C05&customer=HP&invoicenumber=0232159&quarter=1&description=Test
The PHP:
<?php
include('includes/dbconn.php');
function clean_up($string){
$html = htmlspecialchars($string);
$string = mysql_real_escape_string($html);
return $string;
}
if($_POST){
$date = clean_up($_POST['date']);
$amount = clean_up($_POST['amount']);
$total = clean_up($_POST['total']);
$customer = clean_up($_POST['customer']);
$invoicenumber = clean_up($_POST['invoicenumber']);
$quarter = clean_up($_POST['quarter']);
$description = clean_up($_POST['description']);
$sql = ("INSERT INTO earnings (e_date, e_amount, e_total, e_customer, e_invoicenumber, e_quarter, e_description)
VALUES ($date, '$amount', '$total', '$customer', $invoicenumber, $quarter, '$description')");
echo $sql;
if($mysqli->query($sql) === true){
echo("Successfully added");
}else{
echo "<br /> \n" . $mysqli->error;
}
}
?>
The form works fine without the ajax but with it it just doesn't work.
Your help is appreciated!
Try this snippet code bro...
<form id="F_login">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button id="btn_login" type="submit">Login</button>
</form>
$("#btn_login").click(function(){
var parm = $("#F_login").serializeArray();
$.ajax({
type: 'POST',
url: '/earnings.php',
data: parm,
success: function (data,status,xhr) {
console.info("sukses");
},
error: function (error) {
console.info("Error post : "+error);
}
});
});
Reply me if you try this...
prevent your form submitting and use ajax like this:
<form id="createItem">
<input id="foo"/>
<input id="bar"/>
<input type="submit" value="New Item"/>
</form>
$('#createItem).on("submit",function(e){
e.preventDefault;
newItem();
});
Try this
<input type="text" id="foo"/>
<input type="text" id="bar"/>
<input type="button" id="btnSubmit" value="New Item"/>
<script type="text/javascript">
$(function() {
$("#btnSubmit").click(function(){
try
{
$.post("my php page address",
{
'foo':$("#foo").val().trim(),
'bar':$("#bar").val().trim()
}, function(data){
data=data.trim();
// alert(data);
// this data is data that the server sends back in case of ajax call you
//can send any type of data whether json or json array or any other type
//of data
});
}
catch(ex)
{
alert(ex);
}
});
});
</script>

Inserting values into database with php, ajax and jQuery

I'm struggling very hard to get this to work and I don't know what I'm doing wrong. I have a register page that I want to take the data inserted into the form and INSERT it to the database with jQuery and AJAX. I'm not very experienced with AJAX AND jQuery so be gentle! :P I will show you the files that I have...
sign_up.php
<?php
include 'connect.php';
include 'header.php';
echo '<h2>Register</h2>';
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
echo '<br/>';
echo '
<div class="container">
<form id="submit" method="post" action="">
<fieldset>
<legend> Enter Information </legend>
<br/>
<label for="user_name">Your username: </label>
<br/>
<input id="user_name" class="text" name="user_name" size="20" type="text">
<br/>
<br/>
<label for="user_pass">Your password: </label>
<br/>
<input id="user_pass" class="text" name="user_pass" size="20" type="password">
<br/>
<br/>
<label for="user_pass_check">Confirm password: </label>
<br/>
<input id="user_pass_check" class="text" name="user_pass_check" size="20" type="password">
<br/>
<br/>
<label for="user_email">Email: </label>
<br/>
<input id="user_email" class="text" name="user_email" size="20" type="email">
<br/>
<br/>
<button class="button positive" type="submit"> <img src="like.png" alt=""> Register </button>
</fieldset>
</form>
<div class="success" style="display: none;"> You are now a registered user!</div>
</div>';
}
else {
$errors = array();
//Checks the errors
if(isset($_POST['user_name']) == NULL)
{
//if the user name is larger than 30 characters
$errors[] = 'Please enter your username.';
}
//Checks the password
if(isset($_POST['user_pass']) == NULL)
{
$errors[] = 'Please enter your password.';
}
else
{
if($_POST['user_pass'] != $_POST['user_pass_check'])
{
$errors[] = 'The two passwords did not match.';
}
}
if(!empty($errors)) //Checks for empty fields
{
echo 'Please check that all the fields are filled in.<br /><br />';
echo '<ul>';
foreach($errors as $key => $value) //walk through the array so all the errors get displayed
{
echo '<li>' . $value . '</li>'; //this generates a list with errors
}
echo '</ul>';
}
}
?>
in my header.php (which I include in every page) I included addMembers.js
$(document).ready(function(){
$("form#submit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var user_name = $('#user_name').val();
var user_email = $('#user_email').val();
var user_pass= $('#user_pass').val();
//$user_name = $('#user_name').val();
//$user_email = $('#user_email').val();
//$password = $('#password').val();
alert(user_name);
$.ajax({
type: "POST",
url: "ajax.php",
data: "user_name="+ user_name +"&user_email="+ user_email +"$user_pass=" + user_pass,
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});
}
});
//alert("ji");
return false;
});
});
and then my ajax.php that gets the data and must insert it into the database but it doesn't! :(
<?php
include 'connect.php';
include 'header.php';
// CLIENT INFORMATION
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_pass = $_POST['user_pass'];
mysql_query("INSERT INTO
users(`user_name`, `user_pass`, `user_email` , `user_date` , `user_level`)
VALUES('$user_name', '$user_pass', '$user_email', NOW() , 0)" OR trigger_error(mysql_error()));
?>
PLEASE help...
Thanks a lot!
Joe
There are a bit of things not right here:
html:
Give a type="submit" to your button:
<button type="submit" class="...>...</button>
jQuery:
Don't use attr() to get a form value, but use val(). Also, note how you built your query string. You might also want to use serialize(), which shortens your code a bit:
$("form#submit").submit(function() {
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
success: function(){
$(this).hide();
$('div.success').fadeIn();
}
});
return false;
});
PHP:
You didn't show your ajax.php, what is it doing?
Why do you make a check in sign_up.php, if you're calling ajax?
Also, this piece of code:
if(!ctype_alnum($_POST['user_name']))
{
$errors[] = 'That user name is allready taken.';
}
is misleading, ctype_alnum() does check if username has only alphabetical characters or numbers, what's this thing about a username being already taken?
Mysql:
you dint' provide your INSERT query, so noone can tell if that's failing too or not
UPDATE:
Your query has more columns than values.
Also, what is htmlspecialchars() good to here? to avoid SQL injections you need to use mysql_real_escape_string(). Escaping html before entering the database is useless
Make sure you have an open connection when calling mysql_real_escape_string().
Should be:
mysql_query("INSERT INTO users
(`user_name`,`user_pass`,`user_email`,`user_date`,`user_level`)
VALUES ('$user_name','$password','$user_email','missingvalue','missingvalue')"
) OR trigger_error(mysql_error());
$.ajax({
type: "POST",
url: "ajax.php",
data: "user_name="+ user_name + "&user_email=" + user_email + "&password=" + password,
success: function(){
$('form#submit').hide(function(){$('div.success').fadeIn();});
}
});
show the ajax.php, besides earlyer comments like : ' $('#user_name').val();','ampersant before user_email'... seems ok...

Categories