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 "
Related
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.
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);
}
I'm creating a follow button, more or less like the twitter one.
You click the button, and you follow the user.
You click again, and you unfollow the user.
I have done this code
HTML
<div data-following="false" class='heart canal'><i class='fa fa-heart awesome'></i></div>
AJAX
$(document).ready(function() {
$(".heart.canal").click(function() {
if($(".heart").attr("data-following") == '0'){
$(".heart").attr('data-following', '1');
} else if($(".heart").attr("data-following") == '1'){
$(".heart").attr('data-following', '0');
}
var usuario = $(".left h4").attr("data-id");
var seguidor = $("#user_account_info .profile_ball").attr("data-id");
var seguir = $(".heart").attr("data-following");
$.ajax({
type: "POST",
url: "./include/php/follow.php",
data: { user: usuario, follower: seguidor, follow: seguir },
success: function(response) {
if(response == '0'){
$(".heart").addClass("like");
} else if(response == '1'){
$(".heart").removeClass("like");
}
}
});
return false;
});
});
PHP
<?php
$dsn = "mysql:host=localhost;dbname=tapehd;charset=utf8";
$usuario = "root";
$contraseƱa = "";
$conexion = new PDO($dsn, $usuario, $contraseƱa);
$resultado = null;
$sql = "";
$user = $_POST["user"];
$seguidor = $_POST["follower"];
$follow = $_POST["follow"];
if($follow == '0'){
$sql = "INSERT INTO seguidores(id_canal, id_seguidor) VALUES('$user', '$seguidor')";
} else if($follow == '1'){
$sql = "DELETE FROM seguidores WHERE id_canal = '$user' AND id_seguidor= '$seguidor'";
}
if($conexion){ $resultado = $conexion->query($sql); }
return $follow;
?>
The problem is, everytime I click the button, I only insert data in the database. I mean, I only create follows.
When I click twice, it doesnt remove the follow.
Is there anyway to insert data when data-following = true and remove it when data-following = false ?
UPDATED
I have changed the boolean false and true for 2 strings, 0 and 1. But it doesn't work anyway.
There are numerous problems here. For one, like #Mark said, you need to understand that when sending ajax requests to PHP, you are sending strings. Also, in your JS, you are binding a click function to the .heart.canal, but then the function changes all elements with that class rather than the actual clicked element. Lastly, once you send the right information to PHP you need to print your results in order to see it in ajax.
Try the following:
JS:
$(document).ready(function () {
$(".heart.canal").click(function () {
var $heart = $(this);
if ($heart.data("following")) {
$heart.data("following", false)
} else {
$heart.data("following", true);
}
var usuario = $(".left").find("h4").data("id");
var seguidor = $("#user_account_info").find(".profile_ball").data("id");
$.ajax({
type: "POST",
url: "follow.php",
data: {user: usuario, follower: seguidor, follow: $heart.data("following")},
success: function (result) {
if (result) {
console.log("true");
} else {
console.log("false");
}
}
});
return false;
});
});
PHP:
$user = (int)$_POST["user"];
$seguidor = (int)$_POST["follower"];
$follow = ($_POST["follow"] === 'true') ? true : false;
if ($follow) {
// insert
} else {
// delete
}
print $follow;
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();
}
}});
});
});
I apologise if this comes across as really stupid. I have searched but can't seem to find an answer. I hope I can explain what it is I am trying to do.
I want to be able to query a database and if there is a record in it to show the record in the span/div or show a not found error message if there isn't.
I have a jquery check up and running to check if a username is in the database, what I want to know is how easy it would be to ammend this to pull all the data and show it in the span/div on the original page.
This is the jquery I have:
$(document).ready(function () {
$('#username').keyup(username_check);
});
function username_check() {
var username = $('#username').val();
if (username == "" || username.length < 2) {
$('#username').css('border', '1px #D5D5D5');
$('#cross').hide();
$('#tick').hide();
} else {
jQuery.ajax({
type: "POST",
url: "check.php",
data: 'username=' + username,
cache: false,
success: function (response) {
if (response == 1) {
$('#username').css('border', '2px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
} else {
$('#username').css('border', '2px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
}
}
});
}
}
Can I do all this on the one page and query the db from the same page, instead of posting it to another page as I don't know how to get the results back to the calling page?
I hope I have explained what I want to do. Apologies if I haven't
Here is the PHP code:
$username = trim(strtolower($_POST['username'])); $username = mysql_escape_string($username); $query = "SELECT adbkid FROM person WHERE adbkid = '$username' LIMIT 1"; $result = mysql_query($query); $num = mysql_num_rows($result); echo $num; mysql_close()
You will normally send ajax requests to pages hosted on your server. So you can't directly access your database without going through your server. You'll need to write a function on your server that queries the database, and then call that function from javascript using ajax.
You can output a string in PHP and then set that text value to an element with jQuery ( $('#element').val(responseFromServer);
or $('#element').html(responseFromServer);
Instead of sending back "1" send back a json response something like:
/* record exists */
{status:1, html:'server generated message about record'}
/* doesn't exist */
{status:0}
This will allow you to still change css based on response data status value
Can use $.post ajax shorthand method:
$.post('check.php',{username: username}, function(response){
var upDateElement=$('#spanID');
if(response.status && response.status== 1){
$('#username').css('border', '2px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
upDateElement.html( response.html)
}else{
$('#username').css('border', '2px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
upDateElement.html('Message html for no record found')
}
},'json')
check.php
$data = array();
$data['exists'] = false;
if(!isset($_POST['username'])) {
echo json_encode($data);
exit();
}
$username = mysql_escape_string($_POST['username']);
$query = "SELECT adbkid FROM person WHERE adbkid = '$username' LIMIT 1";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if(count($row) == 1) {
$data = $row;
$data['exists'] = true;
}
return json_encode($data);
from your jQuery:
success: function(response) {
/**
* For instance, for a table with id, username, password and email you have
* data.exists = true/false;
* data.id = 1;
* data.username = 'foo';
* data.password = 'sample data password';
* data.email = 'foo#bar.com';
*/
if(response.exists === true) {
$('#username').val(response.username);
$('#email').val(response.email);
}
}