Javascript sweet alert - php

how write a code alert succes use "sweet alert" on login form , example my code
if($jum > 0){
$hasil = $row -> fetch();
$_SESSION['admin'] = $hasil;
echo '<script>alert("Login Berhasil");window.location="index.php"</script>';
}else{
echo '<script>alert("Login Gagal");history.go(-1);</script>';
}
}
if($jum > 0){
$hasil = $row -> fetch();
$_SESSION['admin'] = $hasil;
echo '<script>**contoh()**;window.location="index.php"</script>';
}else{
echo '<script>alert("Login Gagal");history.go(-1);</script>';
}
}
<script type="text/javascript">
function contoh() {
swal.fire({
title: "Berhasil!",
text: "Pop-up berhasil ditampilkan",
icon: "success",
button: true
});}</script>
if i write code like this, no pop up sweet alert appear

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 "

Codeigniter session with multi-dimensional array

Check user credentials from model and set userdata there and user logged in successfully but in view i want to show logged in username.But I can't pass logged in value in view .Always return count value 0 in view file.But I don't know why I can't get value when i call the set session data.Thanks in advance for your help.
My model code:
function auth($email, $password, $remember=false)
{
// make sure the username doesn't go into the query as false or 0
if(!$email)
{
return false;
}
$this->db->select('*');
// $this->db->where('active', 1);
$this->db->where('email', $email);
$this->db->where('password', sha1($password));
$this->db->limit(1);
$result = $this->db->get('guests');
$result = $result->row_array();
if (sizeof($result) > 0)
{
$admin = array();
$admin['front_user'] = array();
$admin['front_user']['id'] = $result['id'];
$admin['front_user']['firstname'] = $result['firstname'];
$admin['front_user']['lastname'] = $result['lastname'];
$admin['front_user']['email'] = $result['email'];
$admin['front_user']['mobile'] = $result['mobile'];
if($remember)
{
$loginCred =
json_encode(
array('username'=>$username, 'password'=>$password));
$loginCred = base64_encode($this->aes256Encrypt($loginCred));
//remember the user for 6 months
$this->generateCookie($loginCred, strtotime('+6 months'));
}
$this->session->set_userdata($admin);
return $admin['front_user'];
return true;
}
else
{
return false;
}
}
And my controller code:
function login(){
//echo '<pre>'; print_r($_POST);die;
$this->load->library('form_validation');
$this->form_validation->set_rules
('email', 'Email', 'trim|required|max_length[32]');
$this->form_validation->set_rules
('password', 'Password', 'required|min_length[4]');
if ($this->form_validation->run() == TRUE)
{
$email = $this->input->post('email');
$password = $this->input->post('password');
return $return = $this->login_model->auth
($email,$password,'','');
if($return){
echo 1;die;
}else{
echo 'Email or Password invalid';
}
}
else{
echo validation_errors();
}
}
And my view file:
<?php
if(count($this->front_user)>0):?>
<a href="#" class="dropdown-toggle" data-toggle="dropdown" >
<?php echo $this->front_user['firstname']?>
</a>
<a href="<?php echo site_url('front/account/logout')?>" >
<i class="fa fa-sign-out pull-left"></i>
<?php echo lang('logout')?>
</a>
<?php endif; ?>
<?php if(count($this->front_user)<1):?>
<a href="#" >
<?php echo lang('login')?>
</a>
<a
<?php echo lang('signup')?></a></li>
<?php endif;
?>
This is my primary view loading method in controller
function index()
{
$data['meta_description'] = $this->setting->meta_description;
$data['meta_keywords'] = $this->setting->meta_keywords;
$data['page_title'] = lang('home');
$data['banners'] = $this->homepage_model->get_banners();
$data['testimonials'] = $this->homepage_model->get_testimonials();
$data['room_types'] = $this->homepage_model->get_room_types();
$data['coupons'] = $this->homepage_model->get_coupons();
//$data['testimonials'] = $this->testimonial_model->get_all();
//echo '<pre>'; print_r($data['coupons']);die;
$this->render('homepage/homepage', $data);
}
And I send login credentials via ajax request and get value into that
view via ajax
$( "#signinForm" ).submit(function( event ) {
event.preventDefault();
var form = $(form).closest('form');
call_loader();
$.ajax({
url: SITE_URL+'/front/homepage/login',
type:'POST',
data:$("#signinForm").serialize(),
success:function(result){
//alert(result);return false;
console.log(result);
if(result==1)
{
toastr.success('You Logged In Successfully');
//location.reload();
window.location.reload()
}
else
{
remove_loader();
toastr.error(result);
//$('#err').html(result);
}
}
});
});
this is java script code.
If($this->session->has_userdata($array['front_user']){
echo $this->session->userdata($array['front_user']['first_name']);
}

redirect ajax call after checking username & password

I am trying to get my login request redirected to a session "logged_in" with php header location, if username and password is correct, my problem is that header("Location:secret.php"); won't do anything the only thing that will work is echo.. I am not sure why :/
Here is my code:
HTML
<html>
<head>
</head>
<body>
<div class="login_box">
<div class="user_logo"></div>
<div class="login_form">
<form>
<input id="username" type="text" placeholder="Username">
<input id="password" type="password" placeholder="Password">
<input id="login" type="button" value="Login">
</form>
</div>
<p id="result"></p>
</div>
<script src="script/jquery-2.1.4.min.js"></script>
<script src="script/ajax_script.js"></script>
</body>
</html>
Ajax script
$(document).ready(
function(){
$('#login').click(function(){
$.post("ajax.php",
{
username : $('#username').val(),
password : $('#password').val()
},
function(data){
if (data=="0") {
$('.login_box').addClass("overflow");
var $login_form = $('.login_form').addClass("error_shake");
$('.login_form input').addClass("error_border");
setTimeout(function() {
$login_form.removeClass("error_shake");
}, 300);
$('#result').html('Forkert brugernavn eller adgangskode!');
}
}
);
});
}
);
PHP
require('includes/db.php');
if ( isset($_POST['username']) && isset($_POST['password']) ) {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = $db->query($query); // udfører databaseopkald og sætter det ind i vores query
$rows = $result->num_rows; // hent antal rækker og sæt det ind i resultat
if($rows == 1){
$_SESSION['logged_in'] = TRUE;
while ($row = $result->fetch_assoc()) {
$_SESSION['user_id'] = $row['ID'];
}
header("Location:secret.php"); //THIS WON'T WORK
}
else{
echo "0";
}
}
Secret site to redirect to
<?php
session_start();
if ($_SESSION['logged_in'] != TRUE) {
header("Location: index");
exit();
}
?>
Top secret!!!
I hope that someone knows how to do this, or have some ideas.
Thanks!
Since you're doing an Ajax call, you cannot redirect this way. If you would want to, you could return a string from your php in the place where you redirect, with the path you want to redirect to and then in your javascript do something like location.href = "your_secret_url" to redirect.
(untested) Example:
PHP:
if($rows == 1){
$_SESSION['logged_in'] = TRUE;
while ($row = $result->fetch_assoc()) {
$_SESSION['user_id'] = $row['ID'];
}
// Yeah, we're logged in!
$result = array(
'result' => 1,
'location' => '/secret.php',
);
}
else{
// Nope.
$result = array(
'result' => 0,
);
}
// return the result
echo json_encode($result);
die();
JS:
$.post("ajax.php",
{
username : $('#username').val(),
password : $('#password').val()
},
function(data){
if (data.result == 0) {
$('.login_box').addClass("overflow");
var $login_form = $('.login_form').addClass("error_shake");
$('.login_form input').addClass("error_border");
setTimeout(function() {
$login_form.removeClass("error_shake");
}, 300);
$('#result').html('Forkert brugernavn eller adgangskode!');
} else if (data.result == 1) {
location.href = data.location;
}
}, "json" // get content which has been returned in json format
);
Edit possible duplicate: Call PHP function with AJAX, but redirect doesn't work
You are redirecting the ajax called page to secret.php. That won't affect the calling page from which you are running the ajax request.

Ajax/PHP not echoing after first post

I've made a settings page for users and the issue im having is that after you send the form once and say you get an error like "Please fill in all fields" and then you go to submit it again it won't echo out any more errors or success messages but it will update your password.
JS:
<script type="text/javascript">
$(document).ready(function() {
$("#changePassword").click(function(){
var userIdSettings = <?php echo $_SESSION['id']; ?>;
var currPass = $("#currentPass").val();
var newPass = $("#newPass").val();
var newPassRe = $("#newPassRe").val();
$.post("inc/ajax.php", {userIdSettings: userIdSettings, currPass: currPass, newPass: newPass, newPassRe: newPassRe}, function(data){
$(".message").html(data).delay(2000).fadeOut('slow', function(){
});
});
});
});
</script>
PHP:
if ($_POST['userIdSettings']) {
$userIdSettings = $_POST['userIdSettings'];
$currPass = $_POST['currPass'];
$newPass = md5($_POST['newPass']);
$newPassRe = md5($_POST['newPassRe']);
if (!empty($currPass) && !empty($newPass) && !empty($newPassRe)) {
$data = new db();
$data->dbConnect();
$data->dbSelect();
$currPass = md5($currPass);
$checkPass = mysql_query("SELECT * FROM users WHERE id = '$userIdSettings'") or die("Error: ".mysql_error());
$checkPass = mysql_fetch_assoc($checkPass);
if ($currPass == $checkPass['password']) {
if ($newPass == $newPassRe) {
mysql_query("UPDATE users SET password = '$newPassRe' WHERE id = '$userIdSettings'") or die("Error: ".mysql_error());
echo '<div class="messages green large"><span></span>Your password has been updated!</div>';
exit;
} else {
echo '<div class="messages red large"><span></span>Your new passwords dont match!</div>';
exit;
}
} else {
echo '<div class="messages red large"><span></span>Your current password is not correct!</div>';
exit;
}
} else {
echo '<div class="messages red large"><span></span>Please fill in all fields!</div>';
exit;
}
}
$(".message").html(data).show().delay(2000).fadeOut('slow', function(){});
Notice the .show()
You are printing the data to the page, then using the fadeOut method, which at the end result sets display:none. Then you are trying to output more data, but the display is still none, resulting in nothing being displayed on the page, even though the DOM element is being updated. If you add the show() method, this will ensure the CSS value of display is set to block; show the new text for the DOM element; and then fadeOut... slowly... after 2 seconds.

Print like count without page refresh

I have a like/unlike post on my website, and when I click the like button I would like the value of check2 to show beside like without me having to refresh the page to see it. Currently I'll click like and it inserts the data but only shows on a page refresh. I'm hopeless with this kind of stuff.
Here is the code in the order it executes.
Thanks for any help.
POST LIKE
echo "<div class='stream_option'><a id='likecontext_".$streamitem_data['streamitem_id']."' style='cursor:pointer;' onClick=\"likestatus(".$streamitem_data['streamitem_id'].",this.id);\">";
if($checklikes>0){
echo "Unlike";
}else{
echo "Like";
}
echo "</a> ";
$check2 = user_core::print_like_count($streamitem_data['streamitem_id']);
if($check2>0){
echo "(".$check2.")";
}
Ajax Function
function likestatus(postid,contextid){
var obj = document.getElementById(contextid);
if(obj.innerHTML=="Like"){
obj.innerHTML="Unlike";
}else{
obj.innerHTML="Like";
}
$.post("../include/like_do.php", { streamitem_id: postid} );
}
LIKE_DO
$check = user_core::check_liked($_SESSION['id'],$_POST['streamitem_id'],1);
user_core::do_like($_SESSION['id'],$_POST['streamitem_id'],1);
if($check==0){
?>
<?php
}else{
?>
<?php
}
}
else{
echo "<script>alert('Error liking post');</script>";
}
?>
USER_CORE
function check_liked($id,$streamid,$value){
$check = "SELECT feedback_id FROM streamdata_feedback WHERE feedback_streamid=$streamid AND feedback_userid=$id AND feedback_rating=$value";
$check1 = mysql_query($check);
$check2 = mysql_num_rows($check1);
return $check2;
}
function print_like_count($streamid){
$check = "SELECT feedback_id FROM streamdata_feedback WHERE feedback_streamid=$streamid AND feedback_rating=1";
$check1 = mysql_query($check);
$check2 = mysql_num_rows($check1);
if($check2>0){
echo "(".$check2.")";
}
}
What you're looking for is an AJAX submission using DHTML to change the value of the likes.
<script language="javascript">
$(".likeButton").click(function() {
$.post("likeProcessor.php", {
id: $(this).attr('id')
}, function(data) {
$("#likeIndicator" + $(this).attr('id')).html(data);
});
</script>
Then your likeProcessor script will simply return the number of likes for that item.
NOTE: This is pseudo-code to give you an idea of what needs to happen. For further info on jQuery and Ajax, RTM at http://www.w3schools.com/jquery/default.asp and http://www.w3schools.com/ajax/default.asp respectively.

Categories