Ajax Confusing http status - php

I have a register form and I want to show some messages in a div. I use Ajax for this. The confusing fact is that in the ajax block, it enters on 'error' branch and show http status 200. It is ok to do that? The submit event is on the form. Should I put on the button? How can I fix it to do what I want?
<form id="register" class="modall-content animate" action="register.php" method="post">
......
<div id = "error-reg"></div>
<div id = "success-reg"></div>
</form>
Php code is this
if(isset($_POST['btn-rg'])) {
..
if ($count == 0) {
if ($check == 1)
$query = "INSERT INTO ...";
elseif ($check == 2)
$query = "INSERT INTO ...";
else {
$query = "INSERT INTO ...";
}
if ($db->query($query)) {
$success .= "Success";
/*echo $success;*/
echo json_encode(array("success" => $success));
}
} else {
$message .= "Username already exists";
/*echo $message;*/
echo json_encode(array("message" => $message));
}
/*$response = array();
$response['success'] = $success;
$response['errors'] = $message;
echo(json_encode($response));*/
}
And my js
$("#register").on('submit',function (event) {
event.preventDefault();
var dataPost= $('#register').serialize();
$.ajax({
url: 'register.php',
type: 'post',
dataType : 'json',
data: dataPost,
success: function(data) {
if (response.success) {
$('#error-reg').hide();
$('#success-reg').html(response.success).css('color','green');
} else {
$('#error-reg').html(response.errors);
}
},
error: function (data) {
console.log(data);
}
});
});
When I make the submit this is what I get

In your register.php right at the top.
Keep this code, but comment it out.It will give you access to see and make sure what comes in.
// echo json_encode($_POST);
// exit;
You did see $_POST['btn-rg']??? ---> NO !!
Did you declare your HTML button as an input?
<input type='submit' name='btn-rg' value='Submit'>
Now take the folowng lines and put it in top of the if-statement. I want to be sure we get inside this statement. You should expect to see "hello world " again.
echo json_encode(array("message" => "hello world"));
exit;

Related

PHP - Make a submit button send info to database

Hello I am new at coding and I have a question I hope some of you guys with some experience can help me with.
I have a page with some text and a button "Confirm". When this button is clicked by me, I first want to redirect to "loading.php" and in the mysql database I want to recieve "confirmed" or "ok" anything like that. Then in my dashboard I want to manually press "Next" on the unique-userid to redirect to "page3.php"
I would need some help with this and a simple "template" on how the button would be programmed in my php.
Script in my PHP where I have the button.
$(document).ready(function() {
var allInputs = $(":input");
$('#SubmitConfirm').submit(function(e) {
e.preventDefault();
var confirm = $('#confirm').val();
if (confirm == null) {
return false;
} else {
}
$.ajax({
type: 'POST',
url: 'files/action.php?type=confirm',
data: $('#confirm').serialize(),
success: function(data) {
console.log(data);
var parsed_data = JSON.parse(data);
if (parsed_data.status == 'ok') {
//console.log(parsed_data);
location.href = "Loading.php"
} else {
return false;
}
//console.log(parsed_data.status);
}
})
});
});
And here is "confirm" in action.php
if($_GET['type'] == 'confirm'){
if($_POST['confirm'] == true){
$submit = $_POST['confirm'];
$uniqueid = $_POST['userid']; // unique userid
$query = mysqli_query($conn, "UPDATE customers SET confirm='$confirm', status=1, buzzed=0 WHERE uniqueid=$uniqueid");
if($query){
echo json_encode(array(
'status' => 'ok'
));
}else{
echo json_encode(array(
'status' => 'notok'
));
}
}
}
}
I have tried but I only got 404 error when I pressed the button
from dashboard.
$query = mysqli_query($conn, "SELECT * from customers");
if($query){
if(mysqli_num_rows($query) >= 1){
$array = mysqli_fetch_all($query,MYSQLI_ASSOC);
//print_r($array);
}
}
foreach($array as $value){
$user = $value['user'];
$confirm = $value['submit'];
$info = "
uniqueID : $user
Confirm: $confirm
echo "

Not redirecting to another page after successful ajax request complete

I am validating a sign In form through ajax. After successful validation the form is not redirecting to the required page.
Ajax Codes
function login_submit(){
var stat="";
$("#submit").val("Loging in...");
$.ajax({
type: "POST",
url: "php/login.php",
data: {
uname: $("#uname").val(),
pass : $("#pass").val()
},
success: function(result) {
if(result=="parent"){
window.location = "http://localhost:90/auction/augeo/admin/parent_admin/index";
}
else if(result == "sucess_normal"){
window.location.assign("../normal_admin");
}
else if(result == "deactivated account") {
window.location.assign("reactivate_account/");
}
else if(result == "banned account") {
window.location.assign("banned_account/");
}
else{
$("#submit").val("Login");
$("#error_msg").css({color: 'red'});
document.getElementById("error_msg").innerHTML= result;
stat = false;
}
}
});
if(!stat)
return false;
}
The php code
if(isset($_POST['uname']) && isset($_POST['pass'])){
$username = encode($_POST['uname']);
$password = encrypt(encode($_POST['pass']));
// check if entered username and password is in the database
$result = mysqli_query($conn,"SELECT * From admin_account where admin_account.username = '$username' AND admin_account.password = '$password' ");
if($row = mysqli_num_rows($result) == 1){
$found = mysqli_fetch_array($result);
if($found['state'] == 1){
$account_id = $found['account_id'];
setcookie("admin_id", $account_id, time() + (86400 * 30), "/");
$_SESSION['admin_id'] = $account_id;
$result1 = mysqli_query($conn,"SELECT role_id From admin where admin_id = '$account_id'");
$found1 = mysqli_fetch_array($result1);
$_SESSION['account_type'] = $found1['role_id'];
if($found1['role_id'] == "1"){
echo "parent";
//header("Location: http://localhost:90/auction/augeo/admin/parent_admin/index");
}else{
echo "sucess_normal";
}
}
elseif($found['state'] == 2){
echo "banned account";
}
else{
$_SESSION['deactivated_id'] = $found['account_id'];
echo "deactivated account";
}
}
else{
echo "Incorrect Username or Password";
}
}
I have tried all I could do but to no avail. I want to check if result=="parent" and if result=="parent" it should redirect to window.location = "http://localhost:90/auction/augeo/admin/parent_admin/index"; but instead it is echoing out parent.
You say "it is echoing out parent". But this should never happen with the AJAX code you supplied.
So I'm suspecting that you have a form that's running its own default submit, and that is what you're seeing.
You may want to check out this answer:
$('#idOfYourForm').submit(function() {
var $theForm = $(this);
// This is a button or field, right? NOT the form.
$("#submit").val("Logging in...");
$.post(
'php/login.php',
{
uname: $("#uname").val(),
pass : $("#pass").val()
}
).done(function(result) {
// check the result
alert("Server said: " + result);
});
// prevent submitting again
return false;
});
You get the button with
$("#submit")
This is ok, but if the button is defined as:
<input type="submit" id="submit" value="..." />
You'll get a subsequent submit of the form the button is defined in.
To avoid this, a far easier solution to the other suggested, is to not use a submit button at all. Instead, use a simple action button. These are two examples, the second of which is probably better because it is easier to design with bootstrap/HTML5/CSS...
<input type="button" id="submit" value="..." />
or better:
<button type="button" id="submit">...</button>
In case of slow server/network, you'll probably want to aid AJAX usability by disabling the button:
$("#submit").val("Logging in...").prop("disable", "disable");
This helps avoiding multiple submits when the server is slow and the user impatient.

How do we pass data in ajax? [duplicate]

This question already has answers here:
How can I get the data-id attribute?
(16 answers)
Closed 5 years ago.
I am new to Ajax and I am confused as to how we pass data in Ajax. I have an index.php file which displays some data, it has a link to delete the record, now the problem is, I am not able to figure out how to transfer the id value from index.php of the selected record to ajax file. Also, how should I go about once I have fetched the value in delete.php page where lies the code to delete records.
I have coded as below.
index.php
<div id="delMsg"></div>
<?php
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"select * from member");
$col=mysqli_num_fields($data);
echo "<table>";
while($row=mysqli_fetch_array($data))
{
echo "<tr>";
for($i=0;$i<$col;$i++)
{
echo "<td>".$row[$i]."</td>";
}
echo "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
echo"</tr>";
}
echo "</table>";
?>
ajax-file.js
$(document).ready(function(){
$(".del").click(function(event){
event.preventDefault();
$.ajax({
url:"delete.php",
method:"get",
data:{id:'ID'},
dataType:"html",
success:function(str){
$('#delMsg').html(str);
}
})
})
})
delete.php
<?php
$id=$_GET['id'];
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"delete from member where id='$id'");
if($data)
{
echo "success";
}
else
{
echo "error";
}
?>
Hopefully this conveys the idea of how an AJAX call works.
The first thing we want to do is setup our trigger, which in your case is a button with an onclick event.
<script
src="http://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<!-- <button id="delete">Delete Something</button> -->
<button id="delete" onclick="onClickHandler(5)">Delete Something</button>
<p id="message">AJAX</p>
<script>
/* Notice I removed the document ready */
function onClickHandler(id)
{
event.preventDefault();
$.ajax(
{
url:"delete.php",
method:"POST", /* In the real world you want to use a delete here */
data: { /* plugin your data */
id: id,
name: "Bob",
age: 25
},
dataType:"html",
success: function(success) {
// Handle the success message here!
if (success) {
$('#message').text("Your message was received!");
}
},
error: function(error) {
// Handle your errors here
$('#message').text("Something went wrong!");
}
});
};
</script>
Notice how my data is prepared in the data object. I leave it up to you to figure out how to grab data and set it in the right field. You could: $('#someId').value(); or pass it through a function. If this is a source of confusion I can clarify.
data: { /* plugin your data */
id: 1,
name: "Bob",
age: 25
},
Next, we need to setup our script.
delete.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Obviously validate the data.
// But this is how you access it.
// $_POST is a global array, so you can access it like so:
$id = $_POST['id'];
$name = $_POST['name'];
$age = $_POST['age'];
// Do your server side stuff...
$sql = "DELETE FROM member
WHERE id = '{$id}' AND name = '{$name}' AND age = '{$age}'";
// Do your SQL (delete) here
// $con = mysqli_connect("localhost","root","","ajaxtest");
// Use prepared statements http://bobby-tables.com/php
// $data = mysqli_query($con,"delete from member where id='$id'");
// if ($data) { // Your condition
// This is where you would check if the query passed
// and send back the appropriate message.
if ($id) {
echo json_encode($id);
}
else {
echo http_response_code(500);
}
}
else {
echo "You don't belong here!";
}
you should use what is called JSON ( Javascript Object Notation, I think). This will let you order your data better to do that you have to use, json_encode.
Now I am not exactly sure what you mean by this id value from index.php
But taking your index.php file, I would change it like this
//make sure the is no space here
<?php
//start output buffering
ob_start();
$html = ['<div id="delMsg"></div>'];
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"select * from member");
$col=mysqli_num_fields($data);
$html[] = "<table>";
while($row=mysqli_fetch_array($data))
{
$html[] = "<tr>";
for($i=0;$i<$col;$i++)
{
$html[] = "<td>".$row[$i]."</td>";
}
$html[] = "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
$html[] = "</tr>";
}
$html[] = "</table>";
$result = [
'html' => implode("\n", $html),
'debug' => ob_get_clean()
];
header("Content-type:application/json");
echo json_encode($result);
//?> ending tags are undesirable
Your JavaScript part will change too
$(document).ready(function(){
$(".del").click(function(event){
event.preventDefault();
$.ajax({
url:"delete.php",
method:"get",
data:{id:'ID'},
dataType:"html",
success:function(data){
$('#delMsg').html(data.html);
}
})
})
})
You can see now that instead of just returning HTML, We will be returning it like this data in the Javascript and $result in php
{
html : '<div id=" ...',
debug : ""
}
I added ob_start and ob_get_clean this can be helpful because you cannot just echo content when outputting JSON, so this will catch any echo or print_r type content and put that into the debug item in the return.
Just replace
echo "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
To
echo "<td><a onclick="deleteRow($row[0])">Delete</a></td>";
Javascript
function deleteRow(recordID)
{
event.preventDefault();
$.ajax({
type: "GET",
url: "delete.php",
data:{id: recordID}
}).done(function( result ) {
alert(result);
});
}
In your PHP I recommend you to use PDO which is more easy and protected from SQL injection attacks.
PHP:
$db = new PDO('mysql:host=localhost;dbname=yourDB','root','');
$query = $db->prepare("Delete From yourTableName Where ID=:ID");
$id=$_GET['id'];
$query->bindParam('ID', $id);
$query->execute();
if ($query->rowCount()) {
echo "success";
}
else
{
echo "fails";
}

AJAX Show error in the modal form without reloading the page

I have two modals form in index.php, one for login and one for register. From the login modal you access the register form. I want to show in the register modal form an error without reloading the page or to redirect to another page.
I use ajax, but after submit, the page redirects to a blank page register.php and shows 1.
In register form I have an empty div
<div id = "error-reg"></div>
The register.php it is the action for form and looks like
if ($count == 0) {
if ($check == 1)
$query = "INSERT INTO ..
elseif ($check == 2)
$query = "INSERT INTO ..
else {
$query = "INSERT INTO ..
}
if ($db->query($query)) {
echo "1";
} else {
echo "2";
}
} else {
echo "3";
}
In js I have
$("#btn-rg").on('submit',function (e) {
e.preventDefault();
var form=$(this);
$.ajax({
url : 'register.php',
type : 'POST',
data : $('#id02').serialize(),
success : function (msg) {
if(msg=="1") $('#error-reg').html('success');
},
error: function (msg) {
if(msg=="2") $('#error-reg').html('Error while registering.Please try again');
if(msg=="3") $('#error-reg').html('The username already exists.');
}
});
});
In php, you just echo a number and browser would interpret it as success.
You can change your js file:
$("#btn-rg").on('submit', function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
url: 'register.php',
type: 'POST',
data: $('#id02').serialize(),
success: function(msg) {
if (msg == "1") $('#error-reg').html('success');
if (msg == "2") $('#error-reg').html('Error while registering.Please try again');
if (msg == "3") $('#error-reg').html('The username already exists.');
}
});
});
Not sure it will work, you may can do that alternatively by adjusting your php file by throwing a http error code.
if ($count == 0) {
if ($check == 1)
$query = "INSERT INTO .."
else if ($check == 2)
$query = "INSERT INTO .."
else {
$query = "INSERT INTO .."
}
if ($db->query($query)) {
echo "1";
} else {
echo "2";
http_response_code(400);
}
} else {
echo "3";
http_response_code(400);
}

redirect to another html file using php

I currently want to redirect to another HTML file (i.e. dashboard.html) after the user has successfully. I know I can use header to solve this, but I am not sure where should I add it into my code.
if (mysqli_query($Link, $Query)) {
$lastID = mysqli_insert_id($Link);
$Query2 = "INSERT INTO $table_2 VALUES (NULL,
'".$lastID."')";
if (mysqli_query($Link, $Query2)) {
$message = "You've sucessfully created the account!";
echo json_encode(array('success'=>'true', 'action'=>'login','html'=>$message, 'console.log'=>$Query));
}
else {
$message = "Error occur in query2";
echo json_encode(array('action'=>'error','html'=>$message, 'console.log'=>$Query));
}
}
else {
$message = "Error in query1";
echo json_encode(array('action'=>'error','html'=>$message, 'console.log'=>$Query));
}
Cheers for your kindly help.
if (mysqli_query($Link, $Query)) {
$lastID = mysqli_insert_id($Link);
$Query2 = "INSERT INTO $table_2 VALUES (NULL,
'".$lastID."')";
if (mysqli_query($Link, $Query2)) {
$message = "You've sucessfully created the account!";
echo json_encode(array('success'=>'true', 'action'=>'login','html'=>$message, 'console.log'=>$Query));
}
else {
$message = "Error occur in query2";
echo json_encode(array('action'=>'error','html'=>$message, 'console.log'=>$Query));
}
}
else {
$message = "Error in query1";
echo json_encode(array('action'=>'error','html'=>$message, 'console.log'=>$Query));
}
jQuery
$.ajax( {
type: 'POST',
dataType: 'json',
data: postData,
url: 'n3228691.scm.tees.ac.uk/Yii/MACC/models/…';,
success: function(data) {
console.log(data);
if(data.action === "login"){
window.location="dashboard.html"; //succeed insert
}else{
alert('There was an error handling your registration!');
}
},
error: function(data) {
alert('There was an error handling your registration!');
}
});
I can add ...
header('Location: dashboard.html');
exit;
You can either add an <a> tag into the code built by PHP:
Click this link for new page
Or, you can use javascript/jQuery to trap a user click and redirect them to a new page:
<div id="redir">Click this link</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function(){
$('#redir').click(function(){
window.location.href = 'new_page.php'
});
});
</script>
Or, if headers have already been sent and the PHP header() method specified in joakkinen's answer won't work, you can echo this HTML:
echo '<meta HTTP-EQUIV="REFRESH" content="0; url=new_page.php">';
(the content=0 represent number of seconds delay before redirect)

Categories