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
Related
I have two functions. First contact function and second sendmail function. After submitting the form First it will submit the data and then sendmail function will send the email.
Both scenarios are working. I am getting some issues with my sendmail function. I mean I am getting the return value from sendmail function but my echo json_encode($response) not working.
I am getting the output on my network tab.
Message accepted{"error":"Data Inserted","error_no":"11"}
If I comment my sendmail function then it's working.
Ajax
$.ajax({
url:base_url+"/process.php",
type: "post",
data: e,
contentType: false,
cache:false,
processData:false,
dataType:"JSON",
success: function(response) {
//alert(response.error_no);
if (response.error_no == '1'){
$('#name').html(response.error);
}
//some more else
else if(response.error_no == 11){
window.location.href=base_url+"/thankyou";
}
else{
window.location.href=base_url+"/thankyou";
}
}
})
Process.php
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';
switch ($action) {
case 'contact_fun' : contact_fun($conn); break;
default : header('Location: index.php');
}
function contact_fun($conn){
//all validation code here
else {
$query="INSERT INTO `tbl_requestform` (name, email, mobileno,img) VALUES (?,?,?,?)";
if($stmt=$conn->prepare($query)) {
$stmt->bind_param("ssss", $name, $email, $mobno, $img);
$stmt->execute();
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
$errorMsg="Data Inserted";
$code="11";
$_SESSION['thankyouSession']="true";
}
else {
$code="11";
$errorMsg='Sorry, there was an error uploading your file.';
$_SESSION['thankyouSession']="true";
}
}
else {
$code="12";
$errorMsg='Poor Network Connection';
}
$sendmail=sendemail_to_admin($conn, $name, $email, $mobno, $img);
$stmt->close();
$conn->close();
}
$response['error']=$errorMsg;
$response['error_no']=$code;
echo json_encode($response);
}
function sendemail_to_admin($conn, $name, $email, $mobno, $img) {
//all my email code here
if (mail($to, $subject, $message, $headers)) {
echo "Message accepted";
return 1;
}
else {
echo "Error: Message not accepted";
}
}
So I have these codes wherein I want a notification to appear in every event. I want to check if the record exists, then a notification will appear, saying the college already exists. But that doesn't happen tho. I keep on inputting duplicate input, but the notification still says it's successful. Is there a mistake in my code?
add-college.php
<?php
function findDuplicate($code) {
try {
include($_SERVER['DOCUMENT_ROOT']."/config/db-config.php");
$sql = "SELECT * FROM colleges WHERE collegecode = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $code);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
return true;
}
else {
return false;
}
}
catch (Exception $e) {
return false;
}
}
try {
include($_SERVER['DOCUMENT_ROOT']."/config/db-config.php");
$code = $_POST['code'];
$name = $_POST['name'];
$result = array();
if (findDuplicate($code)) {
$result['message'] = 'duplicate';
}
else {
$sql = "INSERT INTO colleges(collegecode, collegename) VALUES(?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $code, $name);
if ($stmt->execute()) {
$result['message'] = 'success';
}
else {
$result['message'] = 'error';
}
}
echo json_encode($result);
}
catch (Exception $e) {
echo json_encode($result);
}
?>
script.js
$("#save-new").click(function() {
var form = $("#add-college");
var code = $("#code").val();
var name = $("#name").val();
$.ajax({
type: "POST",
data: {
code: code,
name: name
},
url: "../ajax/add-college.php",
dataType: "html",
success: function(data) {
if (data.message = "success") {
$.notify({
// options
message: 'College has been added.'
},{
// settings
type: 'success'
});
}
else if (data.message = "duplicate") {
$.notify({
// options
message: 'College already exists.'
},{
// settings
type: 'warning'
});
}
else {
$.notify({
// options
message: 'College cannot be added.'
},{
// settings
type: 'error'
});
}
$("#code").val("");
$("#name").val("");
$("#add-new").modal('hide');
showColleges();
}
});
});
data.message = "success" this is assignment operation, if you want to compare two string use == operator.
So, the correct statement would be for the if condition would be if(data.message == "success")
Similarly, if(data.message == "duplicate"). I am sure you are aware of all this!
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);
}
}
});
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)
After send my form data to php file its return if any error found. But its also return success before ajax redirect page. I want display error message only and if success, redirect another page.
ajax:
$("#msform").submit(function(){
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
dataType : 'json',
success: function(data){
if ( ! data.success) {
$(".help-block").fadeIn().html(data.error);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});
php:
include_once ("db.php");
global $dbh;
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
$error ="* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
$error ="* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
$error ="* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}
$data = array();
$data['error'] = $error;
$data['success'] = $success;
if (!empty($data)) {
echo json_encode($data);
}
Solved the problem, in this way:
Ajax:
$("#msform").submit(function(){
// collect input name
ver name = var catag=$('#name').val();
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
success: function(data){
if ( data != 'success') {
$(".help-block").fadeIn().html(data);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + name;
}
}
});
});
php:
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
echo "* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
echo "* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
echo "* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
echo 'success';
}
EDIT
Set your variables $success and $error
$success = "";
$error= "";
If you doesn't init them, you cannot use them and the .=operator is for concatenation not for set.
Then you should encode the response in php in JSON.
Something like
$response = json_encode(
array(
'success'=> true,
'route' => "mypage/info?user=$_SESSION['username']"
)
);
And return this, then access your response like you already do :
var success = response.success;
UPDATE
change this code to add an else statement :
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}else{
$success = 'error';
}
and this line :
else {
return 1;
}
to :
else {
$error = 'none';
}
and in your javascript :
$("#msform").submit(function(){
$.ajax({
type :"post",
url :"pagesubmit.php",
data : $("#msform").serialize(),
dataType : 'json',
success : function(data){
if(data.success == 'error') {
$(".help-block").fadeIn().html(data.error);
}else{
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});