Ajax Error Reporting In PHP Not Using JSON - php

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

Related

After return the value from function then json_encode is not working

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

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;

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

check database connection after button is click

I am building a website that has a reservation. I use ajax to send information from forms into the another page which insert the information into my database. To make it even useful, I want to make a test connection into my database. After a user fills up all the fields required he will click the submit button and a test connection must check first before sending the data. And when the connection fails, it will tell the user that the connection is not set(maybe his internet connection is lost, or the server itself is failing). In that way, the website prevents prompting the user that their reservation data is sent, but actually NOT.
EDITED:
Here's my running and fixed code:
$("#esubmit2").click(function(){
var event2 = document.getElementsByName("eevent2")[0].value;
var engager2 = document.getElementsByName("eengager2")[0].value;
var contact2 = document.getElementsByName("econtact2")[0].value;
var eadd2 = document.getElementsByName("eeadd2")[0].value;
var venue2 = document.getElementsByName("evenue2")[0].value;
var datein2 = document.getElementsByName("edatein2")[0].value;
var message2 = document.getElementsByName("emessage2")[0].value;
var reg2 = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(event2 == "" || event2 == " "){
$("#eevent2").focus();
return false;
}
else if(engager2 == "" || engager2 == " "){
$("#eengager2").focus();
return false;
}
else if(contact2 == "" || contact2 == " "){
$("#econtact2").focus();
return false;
}
else if(venue2 == "Venue:"){
$("#evenue2").focus();
return false;
}
else if(datein2 == "" || datein2 == " "){
$("#edatein2").focus();
return false;
}
else if(message2 == "" || datein2 == " "){
$("#emessage2").focus();
return false;
}
else if(eadd2 != ""){
if(reg2.test(eadd2) == false){
$("#eeadd2").focus();
$("#eeadd2").css("backgroundColor","#800517");
$("#eeadd2").css("color","#FFFFFF");
return false;
}
else{
sendreserve_event2(); // call function sendreserve()
return false;
}
}
else{
sendreserve_event2(); // call function sendreserve()
return false;
}
})
function sendreserve_event2(){ // send informations to database
var data_string = $("form#eform2").serialize(); // IMPORTANT
$.ajax({
type: "POST",
url: "submitreserve_eventpc.php",
data: data_string,
success: function(json) {
if(json == 1){
$("#eevent2").val("");
$("#eengager2").val("");
$("#econtact2").val("");
$("#eeadd2").val("");
$("#evenue2").val("Venue:");
$("#edatein2").val("");
$("#emessage2").val("");
$("#eeadd2").css("backgroundColor","#FFFFFF");
$("#eeadd2").css("color","#555");
alert("Reservation Successful!!! \n\nPlease wait for your reservation code to be send to your e-mail account or contact number.\n\nThank you!");
return false;
}
else{
alert("Sorry for the inconvenience but the connection to our database failed.\nPlease check you internet connection or refresh you page.\n\nIf one of the above failed please report to our admin.\nThank You.");
return false;
}
}//end success function
}); //end ajax call
return false; // IMPORTANT
}
submitreserve_eventpc.php:
if($test){
mysql_query("INSERT INTO tblevent(eventName,engager,contactNumber,emailAdd,venue,checkinDate,message) VALUES('$event2','$engager2','$contact2','$eadd2','$venue2','$datein2','$message2')");
$ok = 1;
}
else{
$ok = 0;
}
echo json_encode($ok);
If there's any improvement that you see please edit. For now this met my needs :)
You should do something like this.
Your php.file
<?php
$con=mysql_connect('localhost','root','root');
if($con){
// do insertion data here into the database
$sql = "Insert into table query";
if($sql){
echo "Data inserted successfully";
}else{
echo "Sorry! some error occured ".mysql_error();
}
}else{
echo "Unable to connect to the server";
}
?>
You could try something like this.
function sendreserve_event2(){ // send informations to database
var data_string = $("form#eform2").serialize(); // IMPORTANT
$.ajax({
type: "POST",
url: "submitreserve_eventpc.php",
data: data_string
}).done(function(data) {
data = $.parseJSON(data);
message = data.message;
if (message == "success")
{
$("#eevent2").val("");
$("#eengager2").val("");
$("#econtact2").val("");
$("#eeadd2").val("");
$("#evenue2").val("Venue:");
$("#edatein2").val("");
$("#emessage2").text("");
$("#eeadd2").css("backgroundColor","#FFFFFF");
$("#eeadd2").css("color","#555");
$("#esubmit2").blur();
alert("Reservation Successful!!! \n\nPlease wait for your reservation code to be send to your e-mail account or contact number.\n\nThank you!");
} else {
console.log(message);
}
});
return false; // IMPORTANT
}
In your PHP file could be changed to what is below.
$myDatabase = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$myDatabase)
{
$message = 'Could not connect: ' . mysql_error();
} else {
$event2 = $_POST['eevent2'];
$engager2 = $_POST['eengager2'];
$contact2 = $_POST['econtact2'];
$eadd2 = $_POST['eeadd2'];
$venue2 = $_POST['evenue2'];
$datein2 = $_POST['edatein2'];
$message2 = $_POST['emessage2'];
mysql_query("INSERT INTO tblevent(eventName,engager,contactNumber,emailAdd,venue,checkinDate,message) VALUES('$event2','$engager2','$contact2','$eadd2','$venue2','$datein2','$message‌​2')");
$message = 'success';
}
$response = array('message' => $message);
echo json_encode($response); // This is the data that your AJAX function gets in .done

Ajax form request

I have a issue with my ajax form submission.I am dynamically submitting a form and using php at the server side to process it.This is the ajax success function.
$.ajax({
type: "POST",
url: "register.php",
data: "uname="+uname+"&eid="+eid+"&pwd="+pass+"&cpwd="+cpass+"&country="+coun+"&contact="+contact,
dataType: "html",
success: function(data){
if(data!="error")
{
//alert(data);
$("#user_status", window.parent.document).html("Welcome "+data+" | <a href='forum/logout.php'>Logout</a>");
if(window.parent.document.getElementById('post_user_name'))
$("#post_user_name", window.parent.document).html(msg);
parent.$.fancybox.close();
}
if(data=="error")
{
//alert(data);
$("#status").html("<span><center><font class='formright err_msg' style='width:176px;'>The user is already register with us.</font><center></span>");
return false;
}
Now if the user is valid he is logged in and f not there has to be an error like "Already exists".The valid part works fine but for invalid I return an error from the php file but still my error message doesn't show up and just error is printed on the screen.I am using fancybox for my forms(jquery fancybox)
PHP code is
if($_POST['pwd']==$_POST['cpwd'])
{
$username = $_POST['uname'];
$email = $_POST['eid'];
$password = md5($_POST['pwd']);
$cpassword = $_POST['cpwd'];
$contact_no = $_POST['contact'];
$country = $_POST['country'];
$cnt = $checkUser['cnt'];
if($cnt!=0)
{
echo "error";
//exit;
/*$_SESSION['error_msg'] = 'Email Address already exists';
redirect_to_link("index.html");*/
}
else
{
//echo "entered here";
$userArray = array();
//$user = return_post_value($_POST['uname']);
$userArray['uname'] = return_post_value($_POST['uname']);
$userArray['email'] = return_post_value($_POST['eid']);
$userArray['password'] = md5(return_post_value($_POST['pwd']));
$userArray['contact_no'] = return_post_value($_POST['contact']);
$userArray['country'] = return_post_value($_POST['country']);
//print_r($userArray);
//exit;
$userObj->addUserValue($userArray);
$_SESSION['username']= $userArray['uname'];
echo $userArray['uname'];
// return $user;
}
The echo $userArray['uname']; part works but echo "error" doesn't.Checked in Firebug response header,i can see the error word returned.
Can anyone throw some light on it?
Thanks
Use this to compare if($.trim(data)!="error")
And don't recheck for if($.trim(data)=="error")
use
if($.trim(data)!="error")
{
//
}
else{
//
}

Categories