Jquery ajax not submitting form to database - javascript

My jquery ajax is not submitting form to my php file. The success alert only alert blank on submit and it won't insert anything to my database. But my php file inserts to database without using ajax.
Here is my code, any idea or new way to do this
This is the AJAX CODE
$(document).ready(function(){
alert("mannn");
$("#adduser").submit(function(){
$.ajax({
type: "POST",
url: "adduser_processor.php",
data: $('#adduser').serialize(),
success: function(data){
alert(data);
}
Here is the php code to insert to database
if (isset($_POST['submit'])) {
//Check if the form is submitted
$fullname = $_POST['fullname'];
$username = $_POST['username'];
$gender = $_POST['gender'];
$about = $_POST['about'];
$number = $_POST['number'];
$password = $_POST['password'];
$timeadded = date("Y/m/d, \a\\t G.ia ( l)");
$address = $_POST['address'];
// Wanna Clean Values to prevent fro Hackers
$fullname = cleaninputs($fullname);
$username = cleaninputs($username);
$about = cleaninputs($about);
$number = cleaninputs($number);
$gender = cleaninputs($gender);
$password = cleaninputs($password);
$address = cleaninputs($address);
$checkuserq = "SELECT username FROM pos_staffs WHERE username = '$username'";
$exeq = mysqli_query($connection, $checkuserq);
$numrow = mysqli_num_rows($exeq);
if ($numrow > 0) {
$msg = "<li class='list-group-item list-group-item-danger'>Username ($username) Choosen by Another Staff</li>";
//echo $msg;
//header("location:addnewuser.php?msg=$msg");
} else {
$insertquery = "INSERT INTO pos_staffs(id,fullname,username,password,about,gender,address,date_joined)
VALUES('','$fullname','$username','$password','$about','$gender','$address','$timeadded')";
$insertq = mysqli_query($connection, $insertquery);
if ($insertq) {
//header("location:addnewuser.php?msg=$msg");
$msg = "New Staff ($fullname) has being added he can now Login";
echo $msg;
} else {
$msg = "Something Went Wrong";
echo $msg;
}
But i dont think my php file has an error because it insert normally without error.

Related

Success function in ajax not returning anything in console

Here is my code, and while running it's not giving anything in the console.
This is how I am trying to check the data. If the data correctly I want the mentioned console in success code. But if it is not then I want else code to run. But the if-else conditions are not working properly. I am including PHP code and ajax code which I have tried. Am I doing it right?
<?php
$host = "dpydaldermt01.******.com";
$username = "test";
$password = "Test";
$database_name = "test";
$conn = mysqli_connect($host, $username, $password, $database_name) or die("Connection failed: " . mysqli_error());
$sql = "select ID, user_email from ci_iwp_wp_users limit 10";
$result = mysqli_query($conn, $sql);
$users = array();
?>
<script>
(function($) {
<?php
while($row = mysqli_fetch_assoc($result)) {
$email = $row['user_email'];
?>
var mail = "<?php echo $email ?>";
$.ajax({
type:'POST',
url:'http://bluepages.ibm.com/BpHttpApisv3/wsapi?byInternetAddr='+mail,
dataType:'someData',
success: function(data) {
if(data === '# rc=0, count=0, message=Success') {
console.log(data);
}
}
});
<?php
$users[]=$row;
}
?>
});
</script>
<?php
echo json_encode($users);
?>
Just Remove dataType:'someData', from your code because it always request and response in json so you dont have to declare separately.

PHP With ajax if else not working and md5()?

when i execute my javascript this code why just else statement is working but not if,and when i use md5($_POST['password']) can't login?? but when not using md5 everything is ok
help me please :)
this is my database
this is my javascript
<script type="text/javascript">
$(document).ready(function() {
$("form#form_login").submit(function(event){
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
type:'POST',
url :'../assets/js/utama/login.data.php',
data:formData,
async:false,
cache:false,
contentType:false,
processData:false,
success:function(data){
if(data == "success")
{
window.location = '../index.php?hal=home';
}else{
alert('error');
}
}
});
});
return false;
});
</script>
this is my php file
<?php
session_start();
if(isset($_POST['email'])){
include "../../../konten/koneksi.php";
$email = $_POST['email'];
$pass = md5($_POST['password'])
$sql_login = "select * from user where email_user ='$email ' AND password_user='$pass'";
$run_login = mysql_query($sql_login);
$data = mysql_fetch_array($run_login);
if(isset($data['email_user'])){
$_SESSION['email_user'] = $data['email_user'];
$_SESSION['status'] = $data['status'];
}else{
echo "alert('errorr')";
}
}
?>
You need to echo "success" in your PHP script response.
semicolon(;) missing md5($_POST['password']);
$email = $_POST['email'];
$pass = md5($_POST['password']);
$sql_login = "select * from user where email_user ='$email' AND password_user='$pass'";
$run_login = mysql_query($sql_login);
$data = mysql_fetch_array($run_login);
if(isset($data['email_user'])){
$_SESSION['email_user'] = $data['email_user'];
$_SESSION['status'] = $data['status'];
echo "success";
}else{
echo "error";
}
Please make sure all "password_user" column contain the md5 string in Database. So you have to store md5 for a password at the time of user registration. You have one non-md5 entry in the database for user "reza". So for this user md5($_POST['password']) will not match in database.
And write echo 'success'; in IF statement in PHP script.
In your code, in your select query there is space after $email and also you need to echo success when your if condition is executed. Improvise your php code as below:
<?php
session_start();
if(isset($_POST['email'])){
include "../../../konten/koneksi.php";
$email = $_POST['email'];
$pass = md5($_POST['password']);
$sql_login = "select * from user where email_user ='".$email."' AND password_user='".$pass."'";
$run_login = mysql_query($sql_login);
$data = mysql_fetch_array($run_login);
if(isset($data['email_user'])){
$_SESSION['email_user'] = $data['email_user'];
$_SESSION['status'] = $data['status'];
echo "success";
}else{
echo "alert('errorr')";
}
}
?>
Hope this will help!
Yes It will always go in else part because you haven't eco success from php file then how can it will be go in success!!!??
change your php script to
<?php
session_start();
if(isset($_POST['email'])){
include "../../../konten/koneksi.php";
$email = $_POST['email'];
$pass = md5($_POST['password']);
$sql_login = "select * from user where email_user ='$email ' AND password_user='$pass'";
$run_login = mysql_query($sql_login);
$data = mysql_fetch_array($run_login);
if(isset($data['email_user'])){
$_SESSION['email_user'] = $data['email_user'];
$_SESSION['status'] = $data['status'];
echo "success";
}else{
echo "error";
}
}
?>
Also mark that don't use mysql* its deprecated and completely remove in PHP7. Use mysqli* or PDO instead

How to create a signup form with ajax, php and parsing json

first of all I'm new with jQuery and PHP. My aim is to create a signup form, passing data to my server on wamp. My query is working, a new record is created in the database, but I can't figure out why it is showing the error log of the ajax call instead of the success one.
Ajax call
$('#reg-button').click(function(event){
$.ajax({
url: 'http://localhost:80/project/signup.php',
type: 'POST',
dataType: 'json',
data: {
email:$("#email").val(),
username:$("#username").val(),
password:$("#password").val()
},
error: function() {
console.log("error");
},
success:function(data){
console.log("success");
var responseData = jQuery.parseJSON(data);
}
});
event.preventDefault();
});
PHP
$response = array();
if (isset($_POST['email']) && isset($_POST['username']) && isset($_POST['password'])){
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$query = "INSERT INTO user (email, username, password) VALUES ('$email', '$username', '$password')";
$result = mysqli_query($conn, $query);
if($result){
$row_cnt = mysqli_num_rows($result);
printf("Result set has %d rows.\n", $row_cnt);
mysqli_free_result($result);
$response['success'] = 1;
$response['message'] = "User registered";
echo json_encode($response);
} else {
$response['success'] = 0;
$response['message'] = 'Ops, user not registered';
echo json_encode($response);
}
} else {
$response['success'] = 0;
$response['message'] = 'Required fields are missing';
echo json_encode($response);
}
Could you help me with fixing these problems, giving me some tips or tutorials?

My pdo ajax code for search is not working

What I want to do is: when a user types their email, my ajax code will run and show the user pass in the password inputbox.
The problem is that while my ajax code is sending the email to search.php, my search.php isn't giving the data to my ajax to show.
I think the problem is in my search.php because when i go to search.php after i type an email in my index the search.php is just blank no data is showing.
Index (Form):
email <input type="text" id="query" name="myemail" class="search_textbox" /><br />
Your Password <input type="text" id="mypass" name="mypass" readonly="readonly" /><br />
<script>
$(document).ready(function(){
$('.search_textbox').on('blur', function(){
$('#query').change(updateTextboxes);
updateTextboxes()
})
$('.search_textbox').on('keydown', function(){
$('#query').change(updateTextboxes);
updateTextboxes()
})
$('#query').change(updateTextboxes);
var $mypass = $('#mypass');
function updateTextboxes(){
$.ajax({
url:"search.php",
type:"GET",
data: { term : $('#query').val() },
dataType:"JSON",
success: function(result) {
var ii = 1;
for (var i = 0; i < result.length; i++) {
$mypass.val(result[i].value).show().trigger('input');
ii++;
}
}
});
};
});
</script>
search.php
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_GET['term'])) {
$q = $_GET['term'];
$sql = "SELECT password FROM students WHERE email = :term";
$query = $dbc->prepare($sql);
$query->bindParam(':term', $q);
$results = $query->execute();
$data = array();
while ($row = $results->fetch()) {
$data[] = array(
'value' => $row['password']
);
}
header('Content-type: application/json');
echo json_encode($data);
}
?>
I noticed header('Content-type: application/json');. I don't think it is necessary. Remove the line and try again. I am not sure but I think php header is needed for a new page. Since you have echo json_encode($data); and in your AJAX call, you are already processing the return data as json, the header(...) is not needed.
EDIT
$q = $_GET['term'];
$sql = "SELECT password FROM students WHERE email = :term";
$query = $dbc->prepare($sql);
$query->bindParam(':term', $q);
if($query->execute() && $query->rowCount()){
echo json_encode($query->fetch(PDO::FETCH_ASSOC));
}
SCRIPT
function updateTextboxes(){
$.ajax({
url:"search.php",
type:"GET",
data: { term : $('#query').val() },
dataType:"JSON",
success: function(result) {
//check here if you have a result, if yes than...
$("#mypass").val(result.password);
}
}

Having trouble in sending the results from pdo to ajax

I want to do is if the user successfully registered the pdo will provide an information and send it to ajax and the ajax will message if the user is registered or not. It was working properly after i put this condition in my pdo and now it wont insert no more and ajax tells "error registering user!" all the time.
script:
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function (e) {
e.preventDefault();
var data = {};
data.name = $('#name').val();
data.age = $('#age').val();
data.gender = $('#gender').val();
data.address = $('#address').val();
data.image = $('#imgInp').val();
$.ajax({
type: "POST",
url: "user.php",
data: data,
cache: false,
success: function (response) {
if (Number(response) == 1)
{
alert("User successfully registered");
}
else
{
alert("Error registering user!");
}
}
});
return false;
});
});
</script>
user.php:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$name = #$_POST['name'];
$age = #$_POST['age'];
$address = #$_POST['address'];
$gender = #$_POST['gender'];
$imageName = #$_FILES['image']['name'];
$q = "INSERT INTO students(name, age, address, gender, imageName ) VALUES(:name, :age, :address, :gender, :image)";
$query = $dbc->prepare($q);
$query->bindParam(':name', $name);
$query->bindParam(':age', $age);
$query->bindParam(':address', $address);
$query->bindParam(':gender', $gender);
$query->bindParam(':image', $imageName);
$results = $query->execute();
$results ? echo "1"; : echo "2"; ;
?>
It seems that you have error in :
$results ? echo "1"; : echo "2"; ;
yours demo
try like this :
echo $results ? "1" : "2";
working demo
you can see here a tutorial.

Categories