Having trouble in sending the results from pdo to ajax - javascript

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.

Related

How to handle PHP session variables on AJAX call?

When I try to get a Session variable into a php script called with AJAX to make a MySQL query it gives me ""
I've tried passing the id using a hidden_input filled with php at the loading of my web page and the function worked! but when I try to catch the session variable directly from the script called by the AJAX it stops working again :(
This is the code where I set my php variables, I call this script directly from a html form.
<?php
if(isset($_POST['empresa']))
{
if(isset($_POST['usuario']))
{
if(isset($_POST['password']))
{
$empresa = $_POST["empresa"];
$usuario = $_POST["usuario"];
$password = $_POST["password"];
$host = "localhost";
$bd = "nominet_Directorio_Web_Beta";
$us = "nominet_Marvin2";
$pas = "NominetBD2019!";
error_reporting(0);
$con = new mysqli($host, $us, $pas, $bd);
if($con->connect_errno)
{
echo "Error de conexión al servidor de base de datos...";
exit();
}
mysqli_set_charset('utf8');
$query = "SELECT `Tbl_Usuarios`.`Id`, `Tbl_Usuarios`.`Fk_Empresa`, `Tbl_Usuarios`.`Tipo_Usuario` FROM `Tbl_Usuarios` INNER JOIN `Tbl_Empresas` ON `Tbl_Usuarios`.`Fk_Empresa` = `Tbl_Empresas`.`Id` WHERE `Tbl_Usuarios`.`Usuario` = '" . $usuario . "' AND `Tbl_Usuarios`.`Password` = '" . $password . "' AND `Tbl_Empresas`.`Razon_Social` = '" . $empresa . "'";
//$query = "SELECT `Tbl_Administradores`.`Id` FROM `Tbl_Administradores` WHERE `Tbl_Administradores`.`Usuario` = '" . $usuario . "' AND `Tbl_Administradores`.`Password` = '" . $password . "'";
$resultado = mysqli_query($con, $query);
$res= mysqli_fetch_array($resultado);
if($res["Id"] > 0)
{
session_start();
$_SESSION["Id"] = $res["Id"];
$_SESSION["Empresa"] = $res["Fk_Empresa"];
$_SESSION["Usuario"] = $usuario;
$_SESSION["Tipo_Usuario"] = $res["Tipo_Usuario"];
header("Location: ../SISTEMA/");
}
else
{
header("Location: ../?error=0");
}
}
else
{
header("Location: ../?resp=error1");
}
}
else
{
header("Location: ../?error=2");
}
}
else
{
header("Location: ../?error=3");
}
?>
The code below it's my JavaSCript (JQuery) function where I call my php script.
function contactosGeneral(){
//var empresa = $('#hidden1').val();
var funcion = "contactosGeneral";
$.ajax({
url: "/PHP/PRUEBA.PHP",
type: "POST",
data: {funcion: funcion},
error: function(xhr){
window.location.href = "../REPORTES/?resp=0";
},
success: function(respuesta) {
var arreglo = JSON.parse(respuesta);
$('#p_contactos').html(arreglo[0]["resp"]);
}
});
}
this is my php script, here I call the DataBase.
<?php
$funcion = $_POST['funcion'];
switch($funcion){
case 'contactosGeneral':
break;
}
function contactosGeneral(){
require("../../ABRIR_CON.php");
//$empresa = $_POST['empresa'];
session_start();
$empresa = $_SESSION["Empresa"];
$sql = 'SELECT COUNT(`Tbl_Contactos`.`Id`) AS "resp" FROM `Tbl_Contactos` WHERE `Tbl_Contactos`.`Fk_Empresa` = ' . $empresa;
$query = mysqli_query($con, $sql);
$json = array();
while($row = mysqli_fetch_array($query))
{
$json[]=array('resp'=>$row['resp']);
}
$resources_JSON_array = json_encode($json);
echo $resources_JSON_array;
require("../../CERRAR_CON.php");
}
?>
I know there's a lot I can improve in my code, but i'm not here for that reason, just help my with my question. thanks :)
As #Barman said, I never called my php function contactosGeneral() into my switch(){} code :B

Jquery ajax not submitting form to database

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.

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);
}
}

Categories