redirect after alert message not working - javascript

this is a snippet of a js file>
$('#btnYes').on('click', (function() {
var id = $('#myModal').data('id');
var usertype = $('#myModal').data('usert');
$.ajax({
url: '{site_url()}admin/deleteUserFromList',
type: 'POST',
data: {id: id, userT: usertype},
success: function(html){
$('[data-id='+id+']').parents('tr').remove();
$('#myModal').modal('hide');
alert('usuario borrado');
window.location.reload();
}
});
return false;
}));
as you can see there is an alert message after deleting a user from a list.
I want to refresh the page after ok on alert message is pressed so i added the line>
window.location.reload();
but it's not working, why is this? how can i fix it?
I've been trying to use alternative to this like
location.href = '....';
window.location = '/some/url';
but nothing seems to work!
this is in my admin.php, the code for deleting user from the database:
public function deleteUserFromList(){
if ((isset($_POST['id']) && (isset($_POST['userT'])))){
$rowId = $_POST['id'];
$userType = $_POST['userT'];
$result = array();
if($userType == 'front'){
$front = UserManager::getInstance()->getUser($rowId);
UserManager::getInstance()->deleteItem($front);
}else{
$back = UserBackManager::getInstance()->getUser($rowId);
UserBackManager::getInstance()->deleteItem($back);
}
$result["message"] = "Usuario eliminado";
echo json_encode($result);
}
}

In order to simulate redirect in your browser try to:
Javascript way:
window.location.replace("http://stackoverflow.com");
jQuery way:
var url = "http://stackoverflow.com";
$(location).attr('href',url);
Try this and let me know it it works for you or not.
EDIT:
Inside ajax success. Try to close modal window and try to replace method.
EDIT 2:
Put this part of code inside of your document ready block and check is it fired or not if it is fired it means your form is reloading correctly.
$( window ).unload(function() {
alert( "Bye now!" );
});

Elaborating on #charlietfl's comment, could you try something like this?
Return the count from the ajax script and insert it into your page:
$('#btnYes').on('click', (function() {
var id = $('#myModal').data('id');
var usertype = $('#myModal').data('usert');
$.ajax({
url: '{site_url()}admin/deleteUserFromList', // this returns the user count as data
type: 'POST',
data: {id: id, userT: usertype},
success: function(data){
$('[data-id='+id+']').parents('tr').remove();
$('#countDisplayElement').text(data); // insert new count into current page
$('#myModal').modal('hide');
alert('usuario borrado');
window.location.reload();
}
});
return false;
}));
That would eliminate the need to refresh the page entirely and be a bit more friendly to use.

Related

passing login data from ajax to php script

Here is my script in the html page:
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
var loginid=$('#loginid').val();
var password=$('#password').val();
alert("loginid="+loginid);
$.ajax({
type: "POST",
url: "../controller/login_check.php",
data: {loginid:loginid,password:password},
success: function(html) {
//alert(html);
$('#status').html(html);
}
});
});
});
</script>
I am trying to get the values from the html input boxes and then passing those values to the ajax code which passes it to the php script, which then validates the login id and password and echoes a message
The php script:
<?php
require_once('dbconfig.php');
//if (isset($_POST['signin'])) {
$loginid = $_POST['loginid'];
$password = $_POST['password'];
if ($operations->login($loginid, $password)) {
header("Location:../view/admin_home.php");
} else {
echo "wrong details";
}
//}
$conn = null;
?>
html div where message should be printed:
<div id="status"></div>
When I run the code in the browser no errors are shown, but the code does not work and neither the message is displayed nor is the validation done.
My contribution:
In ajax requests I suggest you to end the php script, you can use a simple die(); for this. After this, you must to print the response, you can use numeric or string pattern to expose this like: 'success' or 'fail', also: 1 or 0.
Here is the same example with a new solution:
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
var loginid = $('#loginid').val();
var password = $('#password').val();
e.preventDefault(); //for avoiding conflict with default form function
$.ajax({
type: "POST",
url: "../controller/login_check.php",
data: {loginid: loginid, password: password},
success: function(response) {
if (response == 'success') {
// if a successful response, redirect your client
window.location.href = '../view/admin_home.php';
} else {
// if login fails, put a message on screen
$('#status').html('Wrong credentials, try again.');
}
}
});
});
});
</script>
Don't forget to filter data in php, never trust in your user!
require_once('dbconfig.php');
// pre setting a response status as fail, this avoid you to use an
// else statement
$result = 'fail';
if (isset($_POST['signin'])) {
// Apply filter and sanitize data, if the loginid is an e-mail
// use the FILTER_SANITIZE_EMAIL else a simple string filter is ok.
$loginid = filter_input(INPUT_POST, 'loginid', FILTER_SANITIZE_EMAIL);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
if($operations->login($loginid,$password)){
// If everything is ok, you just override the response message
$result = 'success';
}
}
// Ath the end you simply close the connection, print the response and
// stops the PHP script
$conn = null;
print(result);
die();
i solved it by preventing it from performing the default function
i used e.preventDefault() it worked but i have a new problem now
the page to which the php script tries to redirect appears on the same login page how should i solve this now??
here is a screen shot of the same
Give this a try:
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: "../controller/login_check.php",
data: form.serialize()
}).done(function (html) {
$('#status').html(html);
});
});
});
</script>
You must redirect with javascript, you are not actually going to the php page, you are just retrieving whatever is printed.
window.open(page,'_self')
rather than
header(...)

AJAX take data from POST with PHP

i have a little problem with my script.
I want to give data to a php file with AJAX (POST).
I dont get any errors, but the php file doesn't show a change after AJAX "runs" it.
Here is my jquery / js code:
(#changeRank is a select box, I want to pass the value of the selected )
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});
});
});
PHP:
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
header('Location:/user/'.$user);
die();
When i run the script, javascript comes up with an alert "success" which means to me, that there aren't any problems.
I know, the post request for my data is missing, but this is only a test, so im planning to add this later...
I hope, you can help me,
Greets :)
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success: ' + JSON.stringify(msg)) },
error: function (err)
{ alert(err.responseText)}
});
});
});
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
echo json_encode($user);
This sample code will let echo the username back to the page. The alert should show this.
well your js is fine, but because you're not actually echoing out anything to your php script, you wont see any changes except your success alert. maybe var_dump your post variable to check if your data was passed from your js file correctly...
Just return 0 or 1 from your php like this
Your PHP :
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
{
$_SESSION["user"] = $user;
echo '1'; // success case
}
else
{
echo '0'; // failure case
}
Then in your script
success: function (msg)
if(msg==1)
{
window.location = "home.php"; // or your success action
}
else
{
alert('error);
}
So that you can get what you expect
If you want to see a result, in the current page, using data from your PHP then you need to do two things:
Actually send some from the PHP. Your current PHP redirects to another URL which might send data. You could use that or remove the Location header and echo some content out instead.
Write some JavaScript that does something with that data. The data will be put into the first argument of the success function (which you have named msg). If you want that data to appear in the page, then you have to put it somewhere in the page (e.g. with $('body').text(msg).

submitting form with parameter from a link in jquery

I am trying to save data in database in background through a link, and to give download functionality to that link in front end. but it gives an error.
my script is -
<script>
$(document).ready(function(){
$("#download").click(function(){
var me = $(this), data = me.data('params');
saveData(me);
});
function saveData(me){
$.ajax({
type: "POST",
url: "download_counter.php",
data: { client_id: "<? echo $client_id;?>", candidate_id: me }
});
}
});
</script>
this is the link (It looks fine)
<button name="download"></button>
download_counter.php looks like -
<?
if (isset($_POST['candidate_id'])) { // Form has been submitted.
$candidate_id = $_POST['candidate_id'];
$client_id= $_POST['client_id'];
$date = date("Y-m-d");
echo "client - ".$client_id;
echo "candidate - ".$candidate_id;
$query = "INSERT INTO `downloads`(`client_id`, `candidate_id`, `download_date`) VALUES ('".$client_id."', '".$candidate_id."', '".$date."')";
$result = mysql_query($query);
}
?>
when i click the link, it lets download the file but database do not updates.
Please help.
There is an error with passing parameter to function saveData, so your ajax request not occur:
$(document).ready(function(){
$("#download").click(function(){
var me = $(this), data = me.data('params');
saveData(data); // was me
});
Check jquery click event handler, which says
// say your selector and click handler is somewhat as in the example
$("some selector").click({param1: "Hello", param2: "World"}, some_function);
// then in the called function, grab the event object and use the parameters like this--
function some_function(event){
alert(event.data.param1);
alert(event.data.param2);
}
database is updating now, but it is not getting value of candidate_id.
i did this -
<script>
$(document).ready(function(){
$("#download").click(function(){
$("#count").hide();
var me = $(this), data = me.data('params');
saveData(data); // was me
});
function saveData(data){
$.ajax({
type: "POST",
url: "counter.php",
data: { client_id: "2", candidate_id: data.ca_id }
});
}
});
</script>
I think on click the data you are reading is a string and in the given format.
And you are passing that as data, but since it is not an valid id,
that value in the database is not updated.
Check this out

I can not click anything

I try to open and show my data in new browser page.
I open new page and show data. However I can not click, choose, or select anything.
My Javascript Code Below:
function CustomerId() {
var veri = {
Id: Id.GetValue(),
};
$.ajax({
url: "/Home/PanelGoster",
type: "POST",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(veri),
success: function (mydata) {
if (mydata.error6 == true) {
} else { // Success
var something = window.open(url, '_blank'); // It opens in blank page but i can not click nothing.
something.focus();
("#MusterilerGetir").html(mydata); // Problem Here
}
},
error: function () { }
});
return false;
}
What am I doing wrong?
On the row marked with "Problem here" you are missing the jQuery identifier at the start. Add a $ before ("#MusterilerGetir") and you should be fine.
$("#MusterilerGetir").html(mydata); // Problem Here
To summarize our discussion in the chat you can do the following to achieve what you need:
create a view with the html form you need to display
when a customer is selected open a new tab with an url to the previously created view and append a GET param of the customer id
in your controller, get the ID and load the required data to initialize the view, then show it.
I hope this helps.

CakePHP & JQuery, location.reload sometimes not working

Hi I am developing data deleting page with checkbox and button. After deletion, I'd like to display the message either the transaction is successful or not. Most of the time the message shows correctly, but sometimes the page reload doesn't happen and the message won't show until manually reloaded.
Now if it's not certain if the page is reloaded, is there any other way to show the message from the controller?
Here's the code:
(index.ctp)
<script type="text/javascript">
$(document).ready( function() {
$("#btn").click(function() {
var ids = '';
$('input[type="checkbox"]').each(function(){
if(this.checked){
ids = ids.concat(this.id).concat(',');
}else{
jAlert("Please choose items to delete");
}
});
if (ids != ''){
jConfirm('Delete?', 'Confirm',function(r){
if(r==true){
ht = $.ajax({
url: 'items/delete/'.concat(ids),
type: "POST",
contentType: "application/json; charset=utf-8",
});
location.reload(true);
}
});
}
});
});
</script>
(controller.php#function delete())
$this->Session->setFlash(__('Deleted!, true));
$this->redirect(array('action'=>'index'));
CakePHP's session flash is usually pretty reliable.
Perhaps your browser is not reliably doing a hard refresh with location.reload(true). Try window.location = window.location.href + "?nocache=" + new Date().getTime() to manually clear the cache and see if that helps at all.

Categories

Resources