redirect to another html file using php - 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)

Related

Facing a issue in populating the status using ajax

I am trying to populate the error to the user using ajax, values are saving in a database properly in every query but when trying to show the same in the front end it is not reflecting the same to the end-user.I wanted to populate the status to the end-user using ajax.
Here is my AJAX code
$.ajax({
url:"controller/client-registration-Controller.php",
type:'POST',
contentType:false,
data:data,
dataType : 'json',
cache: false,
processData:false,
beforeSend: function(){
$('#insert').attr("disabled","disabled");
$('#fupForm').css("opacity",".5");
},
success: function(strMessage) {
$responseText=JSON.parse(strMessage);
if($responseText.status=='OK')
{
toastr.success(' Registered Successfully.', 'Success Alert', {timeOut: 5000});
//clear all fields
$('#fupForm').trigger("reset");
}
else if($responseText.status=='ERR'){
toastr.error('You Got Error', 'Something Went Wrong!', {timeOut: 5000});
}
}
});
}
});
});
</script>
Here is my PHP Code
if (mysqli_num_rows($query) > 0) {
header('Content-Type: application/json; charset=UTF-8');
$response['status'] = 'ERR';
$response['message'] = "Mobile is already exist";
return json_encode($response);
$res = " Mobile is already exist";
echo json_encode($res);
} elseif (mysqli_num_rows($query1) > 0) {
header('Content-Type: application/json; charset=UTF-8');
$response['status'] = 'ERR';
$response['message'] = "Email is already exist";
return json_encode($response);
$res = "Email is already exist";
echo json_encode($res);
} elseif (!mysqli_query($con, $sql)) {
$response['status'] = 'ERR';
$response['message'] = "Something Went Wrong";
return json_encode($response);
$res = "Something went wrong";
echo json_encode($res);
} else {
header('Content-Type: application/json; charset=UTF-8');
$response['status'] = 'OK';
$response['message'] = 'Inserted successfully';
echo json_encode($response);
return;
// $error="Registered Successfully";
// echo json_encode($error);
}
}
}}
I want to populate the status in the front end

Ajax Confusing http status

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;

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);
}

Ajax Error Reporting In PHP Not Using JSON

So I'm a bit confused.
I need to add an error handler to my AJAX depending on the result from PHP.
I was wondering if there was a way for me to add a variable like $success = error or $success = success in my PHP to trigger the AJAX functions.
I did some reading but everything I read involves JSON.
Here is my PHP with the $success variables where they should be, but I'm not sure where to start with the AJAX.
I'm not asking for a code to be written for me, but just some guidance.
if(isset($_POST['submit'])) {
require($_SERVER['DOCUMENT_ROOT']."/settings/functions.php");
$conn = getConnected("oversizeBoard");
if(empty($_POST['first_name'])) {
$success = "error";
echo "First Name Is Required.";
exit();
}
else {
$first_name = mysqli_real_escape_string($conn, $_POST['first_name']);
}
if(empty($_POST['last_name'])) {
$success = "error";
echo "Last Name Is Required.";
exit();
}
else {
$last_name = mysqli_real_escape_string($conn, $_POST['last_name']);
}
if(empty($_POST['email'])) {
$success = "error";
echo "Email Is Required.";
exit();
}
else {
$email = mysqli_real_escape_string($conn, $_POST['email']);
}
if(!empty($_POST['first_name']) && !empty($_POST['last_name']) && !empty($_POST['email'])) {
$checkEmail = mysqli_query($conn, "SELECT * FROM subscriptions WHERE email='$email'");
if(mysqli_num_rows($checkEmail) > 0){
$success = "error";
echo "You Are Already Subscribed!";
}
else {
if (!mysqli_query($conn,$checkEmail)) {
$subscribeQuery = "INSERT INTO subscriptions (first_name, last_name, email) VALUES ('$first_name', '$last_name', '$email')";
if (mysqli_query($conn, $subscribeQuery)) {
$success = "success";
echo "You Have Successfully Subscribed!";
}
else {
echo "Error: ".mysqli_error($conn);
}
}
}
mysqli_close($conn);
}
}
else {
echo "You Are not Authorized To View This Page.";
}
And the AJAX:
function submitForm() {
$.ajax({type:'POST', url: 'http://example.com/form/postSubscription.php', data:$('#subscription_form').serialize(),
error: function(response) { // if php variable is $success = "error"
notif({
msg: response,
type: "error",
position: "center"
});
},
success: function(response) { // if php variable is $success = "success"
notif({
msg: response,
type: "success",
position: "center"
});
}});
return false;
}
Do I need to use JSON to accomplish this or is there another way?
Rather than using echo "You Have Successfully Subscribed!"; etc, you probably want to create an output object/array up front, and then populate it with the data you want. Like this:
$data['text']= "You Have Successfully Subscribed!";
$data['success'] = "success";
Then you finish up with something like this:
header('Content-Type: application/json');
echo json_encode($data);
make sure you don't do any echo statements prior to the header or you'll get an error. Also, you don't want to do any echo statements other than the json_encode, or your json probably won't be parsed correctly.
On the client side, in your $.ajax, your success would work something like this:
$.ajax({ ...
success: function(response){
if(response.success=="success") {
$('#output').text(response.text);
}
}
});

AJAX return error on request but the php function works

I run an ajax request trought jQuery that calls a php function that works each time I call it, I don't mean that the written code should work because is right, but it works because I can see the output in the database. However request.fail(function(jqXHR, textStatus){alert('AJAX Error: '+ textStatus);}); return an error( parseerror) , this is my code:
$('#createtk').click(function(){
var tit=$('#title').val();
var prio=$('#priority').val();
var wsurl=$('#wsurl').val();
var dep=$('#dep').val();
var message=CKEDITOR.instances.message.getData().replace(/\s+/g,' ');
if(tit.replace(/\s+/g,'')!='' && prio.replace(/\s+/g,'')!='' && dep.replace(/\s+/g,'')!='' && wsurl.replace(/\s+/g,'')!='' && message.replace(/\s+/g,'')!=''){
var request= $.ajax({
type: 'POST',
url: '../php/function.php',
data: {act:'create_ticket',tit:tit,prio:prio,dep:dep,wsurl:wsurl,contp:$('#contype').val(),ftpus:$('#ftpus').val(),ftppass:$('#ftppass').val(),message:message},
dataType : 'json',
success : function (data) {
alert('1');
if(data[0]=='Created'){
alert('2');
window.location = "<?php echo dirname(curPageURL()); ?>";
}
else
alert(data[0]);
}
});
request.fail(function(jqXHR, textStatus){alert('AJAX Error: '+ textStatus);});
}
else
alert('Form Error - Empty Field');
});
and this is the php function( sorry for the presentation, I put this just for information as it works exe):
else if(isset($_POST['act']) && isset($_SESSION['name']) && $_POST['act']=='create_ticket'){ //controllare
$message=(preg_replace('/\s+/','',$_POST['message'])!='')? htmlentities(preg_replace('/\s+/',' ',$_POST['message']),ENT_QUOTES,'UTF-8'):exit();
$tit=(preg_replace('/\s+/','',$_POST['tit'])!='')? htmlentities(preg_replace('/\s+/',' ',$_POST['tit']),ENT_QUOTES,'UTF-8'):exit();
$dep=(is_numeric($_POST['dep']))? (int)$_POST['dep']:exit();
$prio=(is_numeric($_POST['prio']))? $_POST['prio']:exit();
$wsurl=(preg_replace('/\s+/','',$_POST['wsurl'])!='')? htmlentities(preg_replace('/\s+/',' ',$_POST['wsurl']),ENT_QUOTES,'UTF-8'):exit();
$contype=(is_numeric($_POST['contp']))? (int)$_POST['contp']:exit();
$ftppass=(preg_replace('/\s+/','',$_POST['ftppass'])!='')? htmlentities(preg_replace('/\s+/',' ',$_POST['ftppass']),ENT_QUOTES,'UTF-8'):'';
$ftpus=(preg_replace('/\s+/','',$_POST['ftpus'])!='')? htmlentities(preg_replace('/\s+/',' ',$_POST['ftpus']),ENT_QUOTES,'UTF-8'):'';
if(preg_replace('/\s+/','',$_POST['message'])!=''){
$mysqli = new mysqli($Hostname, $Username, $Password, $DatabaseName);
$stmt = $mysqli->stmt_init();
if($stmt){
$query = "INSERT INTO ".$SupportTicketsTable."(`department_id`,`user_id`,`title`,`priority`,`website`,`contype`,`ftp_user`,`ftp_password`,`created_time`,`last_reply`) VALUES (?,?,?,?,?,?,?,?,?,?)";
$prepared = $stmt->prepare($query);
if($prepared){
$date=date("Y-m-d H:i:s");
if($stmt->bind_param('iisissssss', $dep,$_SESSION['id'],$tit,$prio,$wsurl,$contype,$ftpus,$ftppass,$date,$date)){
if($stmt->execute()){
$tkid=$stmt->insert_id;
$ip=retrive_ip();
$refid=uniqid(hash('sha256',$tkid.$tit),true);
$query = "UPDATE ".$SupportTicketsTable." SET enc_id=? WHERE id=? ";
if($prepared = $stmt->prepare($query)){
if($stmt->bind_param('si', $refid,$tkid)){
if($stmt->execute()){
$query = "INSERT INTO ".$SupportMessagesTable."(`user_id`,`message`,`ticket_id`,`ip_address`,`created_time`) VALUES (?,?,?,?,?);";
if($prepared = $stmt->prepare($query)){
if($stmt->bind_param('isiss', $_SESSION['id'],$message,$tkid,$ip,$date)){
if($stmt->execute()){
$selopid=retrive_avaible_operator($Hostname, $Username, $Password, $DatabaseName, $SupportUserPerDepaTable, $SupportUserTable, $dep);
if(is_numeric($selopid)){
$query = "UPDATE ".$SupportTicketsTable." a ,".$SupportUserTable." b SET a.operator_id=?,a.ticket_status='1',b.assigned_tickets (b.assigned_tickets+1) WHERE a.id=? AND b.id=? ";
if($prepared = $stmt->prepare($query)){
if($stmt->bind_param('iii', $selopid,$tkid,$selopid)){
if($stmt->execute()){
echo json_encode(array(0=>'Created'));
}
else
echo json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo json_encode(array(0=>mysqli_stmt_error($stmt)));
}
echo json_encode(array(0=>$selopid));
}
else
echo json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo json_encode(array(0=>mysqli_stmt_error($stmt)));
}
else
echo json_encode(array(0=>mysqli_stmt_error($stmt)));
$mysqli->close();
}
else
echo json_encode(array(0=>'Empty Message'));
}
The function calls another php function (retrive_avaible_operator) that retrun a value and I wonder if this is the problem, Do AJAX/PHP elaborate this information as a final output?Thanks in advance
My god that is a lot of nested ifs. Have you considered using something called exceptions to generate your errors?
I cannot check the return value of your PHP script. However, jQuery expects a json return (as you are setting the dataType to that) and will fail if it gets anything else...including an empty string.

Categories