AJAX: am I inserting data correctly? - php

I read many of the similar threads here to see what I'm doing wrong, but my AJAX call seems correct. What am I missing here? No alert is popping up, so I assume it's the JS side.
$("#SignupSubmit").click(function()
{
var fName = $("#txtSignFName").val();
var lName = $("#txtSignLName").val();
var email = $("#txtSignEmail").val();
var pw = $("#txtPW").val();
if( fName == "" || lName == "" || email == "" || pw == "" )
{
alert();
}
else
{
$.ajax({
type: "POST",
url: "actionPages/signUp.php",
dataType: 'json',
data: {
fName:fName,
lName:lName,
email:email,
pw:pw
},
success: function(response) {
alert(response);
}
});
}
});
And the PHP (is this correct?):
<?php
require "../connectionPages/localConnect.php";
$fName = $_POST["fName"];
$lName = $_POST["lName"];
$email = $_POST["email"];
$pw = $_POST["pw"];
if($fName == null || $lName == null || $email == null || $pw == null)
$message = "missing required data";
else
{
$SQL = "INSERT INTO `customer/User` (custFName,
custLName,
custEmail,
custPassword)
VALUES ('$fName', '$lName','$email', '$pw')";
$mysqli->query($SQL);
if($mysqli->affected_rows > 0)
{
$message = "Record successfully inserted <br><a href='..'>Back to Main Page</a>";
$SQL = $mysqli->insert_id; /* $SQL = "SELECT max(custID) as ID FROM `customer/User`"; */
$res = $mysqli->query($SQL) or trigger_error($mysqli->error."[$SQL]");
json_encode($res);
}
else {
$message = "Unable to insert record: " . $mysqli->error;
}
$mysqli->close();
}

First phase update the below code in the data part.
data: {
"fName":fName,
"lName":lName,
"email":email,
"pw":pw
},
And you are trying to get last inserted id. is it? if so use
$mysqli->insert_id;
instead of select query

Do this in AJAX
$.ajax({
type: "POST",
url: "actionPages/signUp.php",
dataType: 'json',
data: {
"fName":fName,
"lName":lName,
"email":email,
"pw":pw
},
success: function(response) {
var res=eval(response);
alert(res.id);
}
});
And in your PHP page. Do this:
if($mysqli->affected_rows > 0)
{
$message = "Record successfully inserted <br><a href='..'>Back to Main Page</a>";
$lastid = $mysqli->insert_id; /* $SQL = "SELECT max(custID) as ID FROM `customer/User`"; */
// $res = $mysqli->query($SQL) or trigger_error($mysqli->error."[$SQL]");
echo json_encode(array('id'=>$lastid));
}
I hope it helps

Related

PHP return AJAX call but code statement not able to recognize

i am totally lost, I used the AJAX below to post data to PHP and echo "1". However, the code couldnt get into the "if (result==1)" code block. It always go into the ELSE block I have attempted to alert(result). It shows 1 without any problem. Apologize for my bad explanation. Any help is deeply appreciated.
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: $form.serialize(),
success: function(result) {
// ... Process the result ...
//alert(result);
if (result=="1")
{
swal({
type: "success",
title: "Congratulation!",
text: "Please check your email inbox",
animation: "slide-from-top",
showConfirmButton: true
}, function(){
var username = $("#username").val();
var password = $("#password").val();
});
}
else
{
//alert(result);
swal({
type: "error",
title: "",
text: result,
animation: "slide-from-top",
showConfirmButton: true
});
}
}
});
My PHP Code is as below:
if($dum=="TRUE")
{
$password2 = $_POST['password2'];
$fullname = $_POST['fullname'];
$country = $_POST['id_country'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$agent = $_POST['agent'];
$term = $_POST['term'];
$sql = "INSERT INTO usercabinet (username, password, password2, fullname, country, mobile, email, agent, term, emailconfirm, identityconfirm, feeds)
VALUES ('$username', '$password', '$password2', '$fullname', '$country', '$mobile', '$email', '$agent', '$term', '0', '0', 'Welcome to Our New Cabinet')";
if ($conn->query($sql) === TRUE) {
// "New record created successfully, Success!!<br>";
$_SESSION['username'] = $username;
$_SESSION['fullname'] = $fullname;
$_SESSION['country'] = $country;
$_SESSION['mobile'] = $mobile;
$_SESSION['email'] = $country;
$_SESSION['term'] = $term;
$_SESSION['emailconfirm'] = 0;
$_SESSION['identityconfirm'] = 0;
$_SESSION['feeds'] = "Welcome to Cabinet";
echo "1";
}
What could be the possible reason of fail?
Try the following:
result = trim(result);
if(result == 1){
This will remove any trailing spaces from the string. Or you can make sure there is no space after or before <?php ?> tags. OR better yet, you can submit json response from PHP Like:
$result = ['status' => 'success'];
echo json_encode($result);
And in your js something like:
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: $form.serialize(),
dataType: 'json',
success: function(result)
{
if (result.status=="success")
}
});

Ajax data type JSON not working

I am trying to insert data using AJAX JSON but it's not working. I tried without JSON and it works, but an alert box shows with some HTML code.
HTML:
Short Break
AJAX:
$(document).ready(function() {
$('#sbreak').on('click', function() {
var name = $("SBreak").val();
$.ajax({
type: "POST",
dataType: 'json',
url: "brkrequest.php",
data: {
sname: name
}
cache: false,
success: function(server_response) {
if (server_response.status == '1') //if ajax_check_username.php return value "0"
{
alert("Inserted ");
} else if (server_response == '0') //if it returns "1"
{
alert("Already Inserted");
}
},
});
return false;
});
});
PHP: :
session_start();
date_default_timezone_set('Asia/Kolkata');
$sname=$_POST['sname'];
$sname= $_SESSION['myusername'];
$reqdate = date("Y-m-d H:i:s");
include("connection.php");
//Insert query
$query = sprintf("SELECT * FROM `breakqueue` WHERE (`sname` ='$sname')");
$result = mysql_query($query);
if(mysql_num_rows($result) > 0){
$data['status']= '1';//If there is a record match Already Inserted
}
else { // if there is no matching rows do following
$query = mysql_query("INSERT INTO `breakqueue`(`id`, `sname`, `btype`, `reqdate`, `apdate`, `status`) VALUES ('','$sname','Sbreak','$reqdate','','Pending')");
$data['status']= '0';//Record Insered
}
echo json_encode($data);
}
use it in php
header('Content-Type:application/json');
and write
success: function(server_response){
console.log(typeof server_response);
...
for finding response type,
if type of server_response isn't object
use it for convert it to object :
server_response = JSON.parse(server_response);
php Code:
session_start();
//Here added...
header('Content-Type:application/json');
date_default_timezone_set('Asia/Kolkata');
$sname=$_POST['sname'];
$sname= $_SESSION['myusername'];
$reqdate = date("Y-m-d H:i:s");
include("connection.php");
//Insert query
$query = sprintf("SELECT * FROM `breakqueue` WHERE (`sname` ='$sname')");
$result = mysql_query($query);
if(mysql_num_rows($result) > 0){
$data['status']= '1';//If there is a record match Already Inserted
}
else{ // if there is no matching rows do following
$query = mysql_query("INSERT INTO `breakqueue`(`id`, `sname`, `btype`, `reqdate`, `apdate`, `status`) VALUES ('','$sname','Sbreak','$reqdate','','Pending')");
$data['status']= '0';//Record Insered
}
echo json_encode($data);
}
Javascript Code:
$(document).ready(function()
{
$('#sbreak').on('click', function(){
var name = $("SBreak").val();
$.ajax({
type: "POST",
dataType:'json',
url: "brkrequest.php",
data: {sname: name}
cache: false,
success: function(server_response){
//TODO:REMOVE IT After seeing. alert or console.log for seeing type
alert(typeof server_response);
if(typeof server_response){
server_response = JSON.parse(server_response);
}
if(server_response.status == '1')//if ajax_check_username.php return value "0"
{
alert("Inserted ");
}
else if(server_response == '0')//if it returns "1"
{
alert("Already Inserted");
}
},
});
return false;

set php session on success of ajax

I have problem .i am making ajax call to a php file that will check credentials, if true i want to redirect to page , but if false i want to show error. I have little bit problem . Here is my code ajax Code.
function Login(val1, val2) {
alert(val1 + "\n" + val2);
$.ajax({
type: "POST",
url: "login.php",
data: 'username='+val1+'&password='+val2,
success: function(data) {
alert(data);
if(data=="true"){
window.location.replace('./admin/index.php');
}else
$("#Area").html(data);
}
});
and this is my php code.
<?php
require_once '/admin/DbHelper.php';
if (isset($_POST['password'])) {
$pass = $_POST['password'];
$name = $_POST['username'];
$query = "select * from user_login where userName='$name' and userPass='$pass'";
$result = mysqli_query($link, $query);
$row= mysqli_fetch_array($result);
if ($row > 0) {
$_SESSION['userName'] = $name;
echo "true"; } else {
echo '<label style="color:red"> Invalid User Name or Passowrd !</label>';
}
}
i can't understand where i should set session. please help me.

How to return simple text from php web service using ajax and jquery [duplicate]

This question already has answers here:
Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?
(13 answers)
Closed 7 years ago.
I want to do this simple log in task using php web service. I am just trying to authenticate username and password on the basis of text result I am echoing in my php.
PHP:
<?php
// Include confi.php
include_once('confi.php');
$found = false;
$email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : "";
$password = isset($_POST['password']) ? mysql_real_escape_string($_POST['password']) : "";
if(!empty($email) && !empty($password)){
$login=mysql_num_rows(mysql_query("select *
from `login`
where `email`='$email'
and `password`='$password'"));
$result =array();
if($login!=0)
{
echo "success";
}
else
{
echo "failed";
}
}
#mysql_close($conn);
/* Output header */
header('Content-type: text/plain');
?>
If the username and password match; it displays success.
Jquery
<script>
$(function () {
$("#logon").click(function () {
var email = $("#username").val();
var password = $("#pass").val();
var dataString = "email=" + email + "&password=" + password;
if ($.trim(email).length > 0 & $.trim(password).length > 0) {
$.ajax({
type: "POST",
url: "http://*****/login.php",
data:dataString,
crossDomain: true,
cache: false,
beforeSend: function () { $("#logon").html('Connecting...'); },
success: function (data) {
if (data == "success") {
alert(result+"You are in");
localStorage.login = "true";
localStorage.email = email;
window.location.href = "test.html";
}
else if (data == "failed") {
alert("Login error");
$("#logon").html('Login');
}
}
});
}
});
});
</script>
you are missing the json function you have to encode what ever you want to send to back to request
<?php
/*output the header here*/
header("Content-Type: application/json");
// Include confi.php
include_once('confi.php');
$response['Status'];// declare a variable to store msg
$found = false;
$email = isset($_POST['email']) ?
mysql_real_escape_string($_POST['email']) : "";
$password = isset($_POST['password']) ?
mysql_real_escape_string($_POST['password']) : "";
if(!empty($email) && !empty($password)){
$login=mysql_num_rows(mysql_query("select *
from `login`
where `email`='$email'
and `password`='$password'"));
$result =array();
if($login!=0)
{
$response['Status']=""success";
}
else
{
$response['Status']="failed";
}
}
#mysql_close($conn);
here make the change
$result= json_encode($message);
echo $result;
?>
in you jquery data to ajax function add
dataType:"json",
success: function (data) {
if (data.Status == "success") { //here check the condition
alert(result+"You are in");
localStorage.login = "true";
localStorage.email = email;
window.location.href = "test.html";
}
else if (data.Status== "failed") { //here check the condition
alert("Login error");
$("#logon").html('Login');
}
}

submit ajax form with condition

hi i am working on an authentification page , so my code is the following
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
if(result == 'true')
{
alert(result);
}
}});
});
});
i get the form , the login and password and i pass them to my php script .
<?php
//data connection file
//require "config.php";
require "connexion.php";
extract($_REQUEST);
$pass=crypt($password);
$sql = "select * from Compte where email='$email'";
$rsd = mysql_query($sql);
$msg = mysql_num_rows($rsd); //returns 0 if not already exist
$row = mysql_fetch_row($rsd);
if($msg == 0)
{
echo"false1";
}
else if($row[1] == crypt($password,$row[1]))
{
echo"true";
}
else
{
echo"false2";
}
?>
everything is goood , when i give the good email and password i get true otherwise i get false, that's not the problem , the problem is i am trying to redirect the user to another page called espace.php if the result is true so i've tried this .
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
if(result == 'true')
{
form.submit(true);
}
else form.submit(false);
}});
});
});
now even if the login and password are not correct the form is submitted , how could i manage to do that i mean , if the informations are correct i go to another page , otherwise i stay in the same page.
use json to get result from authanication page
<?php
//data connection file
//require "config.php";
require "connexion.php";
extract($_REQUEST);
$pass=crypt($password);
$sql = "select * from Compte where email='$email'";
$rsd = mysql_query($sql);
$msg = mysql_num_rows($rsd); //returns 0 if not already exist
$row = mysql_fetch_row($rsd);
$result = array();
if($msg == 0)
{
$result['error'] = "Fail";
}
else if($row[1] == crypt($password,$row[1]))
{
$result['success'] = "success";
}
else
{
$result['error'] = "try again";
}
echo json_encode($result); die;
?>
And in the ajax,, check what is the response.
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
var response = JSON.parse(result);
if(response.error){
//here provide a error msg to user.
alert(response.error);
}
if(response.success){
form.submit();
}
}});
});
});

Categories