Neel Thakkar Neel Thakkar - 4 months ago 156
Ajax Question

Ajax Redirect on new page and after display success message

I am working with ajax and php. I want to display message on another page after user successfully added using Ajax. I have tried so much. It's working when first display "Success" message on popup and afrer redirect on another page. But i want to first redirect on another page and after display message.

User Add Page:

<form action="<?php echo $action_link; ?>" method="post" id="form_user_profile" class="form-horizontal" novalidate="novalidate">

<input type="hidden" id="id" name="id" value="<?php echo $id; ?>">

<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">First Name
<span class="required" aria-required="true"> * </span>
</label>
<div class="col-md-4">
<div class="input-icon right">
<i class="fa"></i>
<input type="text" class="form-control" name="fname" value="<?php echo $user_db[0]['fname']; ?>">
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<input type="submit" class="btn green" name="submit" value="<?php echo $addupdate_msg; ?>">
</div>
</div>
</div>
</form>


Ajax in Validate

$("#form_user_profile").validate({
rules: {
fname: {
required: true
}
},
messages: {
fname: "Please enter first name"
},
submitHandler: function(form) {
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(response) {
if(response == 1){
bootbox.alert("User has been added successfully.", function() {
window.location.href= "<?php echo $user_list; ?>";
});
}
}
});
}
});


Action

if (isset($_REQUEST['submit']) && $_REQUEST['submit'] == "Add") {

$fname = mysqli_real_escape_string($obj->CONN, $_REQUEST['fname']);

$user->setfname($fname);
$insert = $user->insert();

ob_get_clean();

if($insert){
echo '1';
$_SESSION['msg'] = "New user has been added successfully.";
}else{
echo '0';
}

exit;
}

Answer

The success popup appears before the user is redirected because of the following code:

if(response == 1){
    bootbox.alert("User has been added successfully.", function() {
        window.location.href= "<?php echo $user_list; ?>";
    });
}

If you wish to show a message on the new page instead, just redirect the user

if(response == 1)window.location.href= "<?php echo $user_list; ?>";

On the new page where you send the customer after success, show the message with something like

$(function() {
    bootbox.alert(<?= $_SESSION['msg'] ?>);
});
Comments