i do not get response message when i post data with ajax - php

1.here is my php code
<?php
session_start();
include_once('connection.php');
include_once('function.php');
if(isset($_POST['username']) && isset($_POST['password'])) {
$username = trim( $_POST['username'] );
$password = trim( $_POST['password'] );
if( empty($username) || empty($password)) {
$res = ['error' => true, 'message' => 'All fields are required.'];
echo json_encode($res);
}else {
$user = login($conn, $username, $password);
if(count($user) > 0) {
$_SESSION['id'] = $user['id'];
$_SESSION['name'] = $user['name'];
$_SESSION['username'] = $user['username'];
$res = ['error' => false, 'message' => 'User login successfully.'];
echo json_encode($res);
}else {
$res = ['error' => true, 'message' => 'Username or password is incorrect.'];
echo json_encode($res);
}
}
}
2.here is my html and script code
<?php
include_once('inc/connection.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>login</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
username: <input type="text" name="uesr" id='uesrname' /><br />
password: <input type="password" name="pass" id="password" /><br />
<button type="submit" name="submit" id="login">Login</button>
<script type="text/javascript">
$(document).on('click','#login',function(){
var username = $('#username').val();
var password =$('#password').val();
if( username == '' || password == ''){
//alert('all fields are required');
}else{
$.ajax({
url:'inc/ajax.login.php',
method:'POST',
data:{
username:username,
password:password
},
success:function($res){
console.log($res);
}
});
}
});
</script>
</body> </html>
List item

Use dataType and remove $ from success fucntion and try this
$.ajax({
url:'inc/ajax.login.php',
method:'POST',
dataType: 'json',
data:{
username:username,
password:password
},
success:function(res){
console.log(res);
}
});

Add die(); after you echo your json_encode.
Change your ajax codes to:
$.ajax({
url:'inc/ajax.login.php',
method:'POST',
dataType: 'json',
data:{
username:username,
password:password
},
success:function(res){
console.log(res);
}
});
IF You Don't use dataType: 'json', you can access your "res" by:
var res = JSON.parse(res);

Related

php with ajax in form input data update

Id how I post, I did not understand the logic.
Why doesn't it update? no error message, please help me!
i don't understand much of ajax. :(
. . . .
index.php
<?php
require "header.php";
$con= mysqli_connect("localhost","root","","propanel_001");
mysqli_set_charset($con, 'utf8');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
mysqli_close($con);
}
$gelen_id=#$_GET['id'];
$sql="SELECT * FROM tb_haber where id='$gelen_id'";
$result=mysqli_query($con,$sql);
$row=mysqli_fetch_assoc($result);
?>
<form id="my_form">
<label>Haber Başlığı</label>
<input value="<?php echo $row['haber_title'] ?>" type="text" name="haber_title">
<label>Haber İçeriği</label>
<textarea name="haber_desc" class="ckeditor text-justify"><?php echo $row['haber_desc'];?></textarea>
<button type="submit" name="btn_haber_update">UPDATE</button>
</form>
<script>
$(document).ready(function(){
$("form[id=my_form]").submit( function(up_haber) {
for (instance in CKEDITOR.instances) {
CKEDITOR.instances[instance].updateElement();
}
var form_data = new FormData(this);
SwalUp_Haber(form_data);
up_haber.preventDefault();
});
});
function SwalUp_Haber(form_data){
$.ajax({
url: "update-haber.php",
type: "POST",
data: form_data,
dataType: "json",
contentType: false,
cache: false,
processData: false,
})
.always(function(response_up_haber) {
swal({
title: response_up_haber.titles,
text: response_up_haber.message,
type: response_up_haber.status,
showConfirmButton: false,
timer:3000,
});
});
}
</script>
update-haber.php
<?php
header('Content-type: application/json; charset=UTF-8');
$response_up_haber = array();
$id_haber_up = $_GET['id'];
$haber_title = mysqli_real_escape_string($con, $_POST['haber_title']);
$haber_desc = mysqli_real_escape_string($con, $_POST['haber_desc']);
$query = "UPDATE tb_haber SET haber_title='$haber_title', haber_desc='$haber_desc' where id='$id_haber_up'";
$update=mysqli_query($con, $query);
if ($update>0) {
$response_up_haber['status'] = 'success';
$response_up_haber['titles'] = 'BAŞARILI';
$response_up_haber['message'] = 'Haber başarılı bir şekilde güncellendi..!';
}else{
$response_up_haber['status'] = 'error';
$response_up_haber['titles'] = 'HATA';
$response_up_haber['message'] = 'Bir sorun oluştu ...
<br>Lütfen bu durumu ProPANEL yetkililerine bildirin..!';
}
echo json_encode($response_up_haber);
?>

send data to a PHP file

i am trying to send data to a php file but its not working.
Here is my code:
App.js:
.controller('sign_up', function ($scope, $http) {
$scope.login = function () {
var request = $http({
method: "post",
url: "js/login.php",
data: {
email: $scope.email,
password: $scope.password
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
/* Successful HTTP post request or not */
request.success(function (data) {
if(data == '1'){
$scope.responseMessage = "Successfully Logged In";
}
else {
$scope.responseMessage = "Username or Password is incorrect";
}
});
}
});
index.html:
<div ng-controller='sign_up'>
<input class="form-control" type="text" ng-model="email" name="email"
placeholder="Enter Your Email">
<br>
<input class="form-control" type="password" ng-model="password"
name="password" placeholder="Enter Your Password"><br>
<button class="btn btn-success" ng-click="login()">Login</button><br>
<span>{{responseMessage}}</span>
</div>
login.php:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$email=$_POST['email']
$password=$_POST['password']
$email = $request->email;
$password = $request->password;
echo json_encode($email);
echo "email=".$email;
if($email == "two" && $password== "one"){
echo "1";
}
else {
echo "0";
}
?>
use $request = json_decode($postdata,TRUE);
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata,TRUE);
$email = $request->email;
$password = $request->password;
if($email == "two" && $password== "one"){
echo "1";
}
else {
echo "0";
}
?>
also change the content type to json
var request = $http({
method: "post",
url: "js/login.php",
data: {
email: $scope.email,
password: $scope.password
},
headers: { 'Content-Type': 'application/json' }
});

How to return output on the same page ajax php

I want to organize the selection query from index.php to action, so i can be able to call the file with ajax to show the data on the page.(index.php). So, the activity I want to do is to able to submit data of the form to the database and to display result on the same page(index.php) without refreshing the page. Help please
Here's my files
1.action.php
2.index.php
3.maker.js
//-----------------------action.php-----------------------------
<?php
include ("db_connect.php"); // Connecting to the database
$user = $_REQUEST['user'];
$text = $_REQUEST['text'];
$ParentId = $_REQUEST['ParentId'];
$action = $_REQUEST['action'];
if ($action=="add")
{
$query="INSERT into `comments` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())";
$result = mysqli_query($conn,$query);
}
if ($action=="delete")
{
$delete = "DELETE FROM `comments` WHERE id=$text";
$result = mysqli_query ($conn,$delete);
}
?>
//index.php
<div id="table_content"></div>
<script type="text/javascript" src="maker.js">
<?php
function ShowForm($AnswerCommentId)
{ ?>
<form id="myForm">
<input type="hidden" name="comment_on" id="comment_on" readonly="readonly" value="<?php print md5($_SERVER['PHP_SELF']); ?>" />
<input id="user" name="user" value="name" autocomplete="off" onfocus="if(this.value == 'name'){this.value = ''}" onblur="if(this.value == ''){this.value = 'name'}"/>
<textarea id='text' name='text' value="comment" onfocus="if(this.value == 'comment'){this.value = ''}" onblur="if(this.value == ''){this.value = 'comment'}" ></Textarea>
<input id="ParentId" name="ParentId" type="hidden" value="<?php echo($AnswerCommentId);?>"/>
<button type='button' OnClick=SendComment()>Comment</button>
</form>
<?php
}
$query="SELECT * FROM `comments` ORDER BY id ASC";
$result = mysqli_query($conn,$query);
if (isset($_REQUEST['AnswerId']))
{ $AnswerId = $_REQUEST['AnswerId']; }
else
{ $AnswerId = 0; }
$i=0;
while ($mytablerow = mysqli_fetch_row($result))
{
$mytable[$i] = $mytablerow;
$i++;
}
function tree($treeArray, $level, $pid = 0)
{
global $AnswerId;
if (! $treeArray)
{ return; }
foreach($treeArray as $item){
if ($item[1] == $pid)
{
?>
<div class="CommentWithReplyDiv" style="margin-left:<?php echo($level*60);?>px">
<div class="CommentDiv">
<pre class="Message"><?php echo($item[3]) ; ?></pre>
<div class="User"><?php echo($item[2]) ; ?></div>
<div class="Date"><?php echo($item[4]) ; ?></div>
<?php
if ($level<=4) { echo 'Reply'; }
echo 'Delete';
?> </div> <?php
if ($AnswerId == $item[0])
{
?><div id="InnerDiv"><?php ShowForm($AnswerId); ?></div>
<?php
}
?> </div> <?php
tree($treeArray, $level+1, $item[0]); // Recursion
}
}
}
tree($mytable, 0);
?>
//maker.js
function DeleteComment(number){
$.ajax({
type: "POST",
url: "action.php",
data: "user=1"+"&text="+number+"&ParentId=1"+"&action=delete",
success: function(html){
$("#table_content").html(html);
}
});
}
function AnswerComment (id){
$.ajax({
type: "POST",
url: "index.php",
data: "AnswerId="+id,
success: function(html){
$("#table_content").html(html);
}
});
}
function SendComment (){
var user1 = $("#user").val();
var text1 = $("#text").val();
var ParentId1 = $("#ParentId").val() + "";
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",
success: function(html){
$("#table_content").html(html);
clean_form();
}
});
return false;
}
So you are basically trying to make ajax based comment system, From what i see, your code organization is not clear based on there tasks, specifically your index.php file so here is what you can do to simplify things :
your action.php should hanlde all php database releted tasks
Move your html code to some other file (Create Template)
Here is the modified code that i have come up with (This is just for your reference, you should modify this accoring to you needs, and as Xorifelse suggested in comment you should always use prepared statements in production system because of security concerns):
Action.php
<?php
include ("db_connect.php"); // Connecting to the database
$action = $_REQUEST['action'];
if ($action=="add")
{
$user = $_REQUEST['user'];
$text = $_REQUEST['text'];
$ParentId = $_REQUEST['ParentId'];
$query="INSERT into `comments` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())";
$result = mysqli_query($conn,$query);
}
if ($action=="delete")
{
$text = $_REQUEST['text'];
$delete = "DELETE FROM `comments` WHERE id=$text";
$result = mysqli_query ($conn,$delete);
}
if ($action=="get")
{
$query="SELECT * FROM `comments` ORDER BY id ASC";
$result = mysqli_query($conn,$query);
if (isset($_REQUEST['AnswerId']))
{ $AnswerId = $_REQUEST['AnswerId']; }
else
{ $AnswerId = 0; }
$i=0;
$mytable = array();
while ($mytablerow = mysqli_fetch_row($result))
{
$mytable[$i] = $mytablerow;
$i++;
}
tree($mytable, 0, $AnswerId);
}
function tree($treeArray, $level, $ansId, $pid = 0)
{
$AnswerId = $ansId;
if (! $treeArray)
{ return; }
foreach($treeArray as $item){
if ($item[1] == $pid)
{
include('comments.template.php');
tree($treeArray, $level+1,$AnswerId, $item[0]); // Recursion
}
}
}
?>
index.php
<html>
<head>
<title>Test page</title>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script type="text/javascript" src="maker.js"></script>
</head>
<body onload="loadComments();">
<div id="table_content">
</div>
</body>
</html>
comments.template.php
<div class="CommentWithReplyDiv" style="margin-left:<?php echo($level*60); ?>px">
<div class="CommentDiv">
<pre class="Message"><?php echo($item[3]) ; ?></pre>
<div class="User"><?php echo($item[2]) ; ?></div>
<div class="Date"><?php echo($item[4]) ; ?></div>
<?php
if ($level<=4) {
echo 'Reply';
}
echo 'Delete';
?>
</div>
<?php if ($AnswerId == $item[0]) { ?>
<div id="InnerDiv"><?php include('commentForm.template.php'); ?></div>
<?php } ?>
commentForm.template.php
<form id="myForm">
<input type="hidden" name="comment_on" id="comment_on" readonly="readonly" value="<?php print md5($_SERVER['PHP_SELF']); ?>" />
<input id="user" name="user" value="name" autocomplete="off" onfocus="if(this.value == 'name'){this.value = ''}" onblur="if(this.value == ''){this.value = 'name'}"/>
<textarea id='text' name='text' value="comment" onfocus="if(this.value == 'comment'){this.value = ''}" onblur="if(this.value == ''){this.value = 'comment'}" ></Textarea>
<input id="ParentId" name="ParentId" type="hidden" value="<?php echo($AnswerId);?>"/>
<button type='button' OnClick="SendComment()">Comment</button>
</form>
marker.js
function DeleteComment(number){
$.ajax({
type: "POST",
url: "action.php",
data: "user=1"+"&text="+number+"&ParentId=1"+"&action=delete",
success: function(html){
$("#table_content").html(html);
loadComments();
}
});
}
function AnswerComment (id){
$.ajax({
type: "POST",
url: "action.php",
data: "AnswerId="+id+"&action=get",
success: function(html){
$("#table_content").html(html);
}
});
}
function SendComment (){
var user1 = $("#user").val();
var text1 = $("#text").val();
var ParentId1 = $("#ParentId").val() + "";
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",
success: function(html){
$("#table_content").html(html);
loadComments();
}
});
return false;
}
function loadComments (){
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "action=get",
success: function(html){
$("#table_content").html(html);
//clean_form();
}
});
return false;
}

ajax login error, can't check

I have problem, I can't check username and password, can you help me?
login.php:
<form class="login-form" method="post" name="loginform" action="">
<div class="title-section">
<h1><span>Login</span></h1>
</div>
<p>Welcome! Login in to your account</p>
<label for="user_login">Username or email address<span>*</span>
</label>
<input type="text" name="log" id="user_login">
<label for="user_pass">Password<span>*</span>
</label>
<input name="pwd" id="user_pass" type="password">
<div id="error"></div>
<button type="submit" name="submit-login" id="submit-login"> <i class="fa fa-arrow-circle-right"></i> Login </button>
</form>
model.php;
<?php
ob_start();
session_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
?>
<?php
global $pdo;
session_start();
if(isset($_POST['submit-login'])) {
$user_email = trim($_POST['log']);
$user_password = trim($_POST['pwd']);
try {
global $pdo;
$stmt = $pdo->prepare("SELECT * FROM user WHERE username=:email");
$stmt->execute(array(":email"=>$user_email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
if($row['user_password']==$password){
echo "ok"; // log in
echo $_SESSION['user_session'] = $row['id_user'];
}
else {
echo "email or password does not exist."; // wrong details
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
ajax.js
$(document).ready(function(){
$("#submit-login").click(function(){
username=$("#user_login").val();
password=$("#user_pass").val();
$.ajax({
type: "POST",
url: "admin/module/admin/model/acc_model.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='ok') {
window.location="profile.php";
}
else {
alert('Please, Error');
}
},
beforeSend:function() {
$("#error").html("<img src='http://www.chinesecio.com/templates/base/images/loading.gif' /> Loading...")
}
});
return false;
});
});
You should pass the data like this
$(document).ready(function(){
$("#submit-login").click(function(){
username=$("#user_login").val();
password=$("#user_pass").val();
$.ajax({
type: "POST",
url: "admin/module/admin/model/acc_model.php",
data: {
name : username,
pwd : password
},
success: function(html){
if(html=='ok') {
window.location="profile.php";
}
else {
alert('Please, Error');
}
},
beforeSend:function()
{
$("#error").html("<img src='http://www.chinesecio.com/templates/base/images/loading.gif' /> Loading...")
}
});
return false;
});
});
Also use parameter like below :
$user_email = trim($_POST['name']);
$user_password = trim($_POST['pwd']);
I think that when you are sending data from your ajax request you are using different variable names and in your model.php you are using your form elements name. Please check into that
data : {"name":username, "password ":password}

Ajax Login return modified headers error [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I am using wordpress as my base and made a custom login form.
ajax:
(function ( $ ) {
jQuery(document).ready(function() {
$("#login_form").submit(function(event){
//check the username exists or not from ajax
jQuery.ajax({
type: 'POST',
url: my_ajax.ajaxurl,
data: $('#login_form').serialize(),
cache: false,
//dataType: 'json',
success: function(result) {
var result=trim(result);
if( result == 'success' ){
window.location='/my-dashboard';
} else {
$('#message').html(result);
}
console.log(result);
}
});
return false;
});
});
function trim(str){
var str=str.replace(/^\s+|\s+$/,'');
return str;
}
}( jQuery ));
login form:
<p id="message" style="color:red;"></p>
<form method="post" action="" id="login_form">
<div align="center">
<div >
Email : <input name="email" type="text" id="email" value="" />
</div>
<div style="margin-top:5px" >
Password :
<input name="password" type="password" id="password" value="" />
</div>
<div class="buttondiv">
<input type="hidden" name="action" value="my_ajax_callback" />
<input type="hidden" name="func" value="check_login" />
<input name="submit" type="submit" id="submit" value="Login" style="margin-left:-10px; height:23px" /> <span id="msgbox" style="display:none"></span>
</div>
</div>
</form>
functions.php
// Ajax
add_action( 'wp_ajax_nopriv_my_ajax_callback', 'my_ajax_callback' );
add_action( 'wp_ajax_my_ajax_callback', 'my_ajax_callback' );
// Your Login function
function check_login( $params ){
require_once('lib/hash.php');
$session = new SC_Session;
// now you can use $session here
$message=array();
if(isset($_POST['email']) && !empty($_POST['email'])){
mysqli_real_escape_string($mysqli, $params['email']);
}else{
$message[]='Please enter email';
}
if(isset($_POST['password']) && !empty($_POST['password'])){
$password= mysqli_real_escape_string($mysqli, $params['password']);
}else{
$message[]='Please enter password';
}
$countError=count($message);
if($countError > 0){
for($i=0;$i<$countError;$i++){
echo ucwords($message[$i]).'<br/><br/>';
}
} else {
$hc=$mysqli->query("SELECT password FROM %table% email='".$email."' AND active=1");
while($hp = $hc->fetch_object()) {
$stored_hash = $hp->password;
}
$hasherd = new PasswordHash(8, false);
$check = $hasherd->CheckPassword($password, $stored_hash);
if($check) {
//now validating the username and password
$result=$mysqli->query("SELECT id, first_name, last_name, zip, email, password FROM %table% WHERE email='".$email."' AND active=1");
while($row = $result->fetch_object()) {
//if username exists
if($result->num_rows > 0)
{
$date = date('Y-m-d h:i:s');
$update_sql = $mysqli->query("UPDATE %table% SET last_login='".$date."'");
$firstname = $row->first_name;
$lastname = $row->last_name;
$zip = $row->zip;
$user_id = $row->id;
$sex = $row->sex;
$session->set_userdata( 'user_id', $user_id );
$session->set_userdata( 'email', $email );
$session->set_userdata( 'firstname', $firstname );
$session->set_userdata( 'lastname', $lastname );
$session->set_userdata( 'zip', $zip );
$session->set_userdata( 'sex', $sex );
}
}
echo ucwords('success');
//return $params;
} else{
echo ucwords('please enter correct user details');
}
}
}
/**
* Ajax Submit
*/
function my_ajax_callback() {
$response = call_user_func($_POST['func'], $_POST);
header( "Content-Type: application/json" );
echo json_encode($response);
exit;
}
The login currently works great, but whenever a error is thrown from $message it displays along with the header warnings.
Warning: Cannot modify header information - headers already sent by (output started at /%wordpresslocation%/wp-content/themes/%theme%/functions.php:77) in /%wordpresslocation%/wp-content/themes/%theme%/functions.php on line 86
null
ANSWER
I feel like an idiot, figured it out, I kept mixing php with javascript as I am proficient in php.
(function ( $ ) {
jQuery(document).ready(function() {
$('#message').slideUp();
$("#login_form").submit(function(event){
$('#message').slideUp();
//check the username exists or not from ajax
jQuery.ajax({
type: 'POST',
url: my_ajax.ajaxurl,
data: $('#login_form').serialize(),
dataType: 'json',
success: function(params) {
if( params == 'success' ){
$('#message').html(params).fadeIn();
document.location='/my-dashboard';
} else {
$('#message').html(params).fadeIn();
}
}
});
return false;
});
});
}( jQuery ));
and changed
echo ucwords('success');
//return $params;
} else{
echo ucwords('please enter correct user details');
}
to this
$params = 'success';
return $params;
}else{
$params = 'fail';
return $params;
and sent back the params
function check_login( $params ){
Thats because an error was printed (echo ucwords('please enter correct user details');)
Then, you try to set a header. That's not possible, headers always have to be set before anything else (that's how http works)
You will have to rewrite the parts that print text before the header is send. Also it doesn't send valid json so it wont work anyway

Categories