Home > database >  Uncaught SyntaxError: JSON.parse: unexpected character ierror after include php file
Uncaught SyntaxError: JSON.parse: unexpected character ierror after include php file

Time:05-22

Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data site:stackoverflow.com error is showing in firefox debug console.

I have a form in my website and on submit button this functions calls

$("#contact-form").on("submit",function(e)
  {
    var sendData = $(this).serialize();
    e.preventDefault();

    if ( checkSubmitInputs(this)  )
    {
      $.ajax({
        type: "POST",
        url: "js/ajaxsubmit.php",
        data: sendData,
        success: function(data)
        {
          $("#loading-img").css("display","none");
          // $(".response_msg").text(data);
          // document.getElementById('contact-form').style.display = 'none'
          // document.getElementById('success').style.display = 'block'
          



          data = JSON.parse(data);
          if(data.status){
            document.getElementById('contact-form').style.display = 'none';
            $("#error").text('');
            $("#success").text(data.msg); 
            document.getElementById('success').style.display = 'block';
            document.getElementById('scicon-c').style.display = 'block';
            document.getElementById('error').style.display = 'none';
            $("#contact-form").find("input[type=text], input[type=email], textarea").val("");
          }
          else {
            document.getElementById('contact-form').style.display = '';
            $("#success").text(''); 
            $("#error").text(data.msg); 
            document.getElementById('error').style.display = 'block'
            document.getElementById('success').style.display = 'none'
            document.getElementById('scicon-c').style.display = 'none'
          }
              
        }
      });
    } else{
        document.getElementsByClassName('error').style.display = 'block'
    }
  })

This line data = JSON.parse(data); shows above error as soon as i add include_once('mail.php'); in my ajaxsubmit.php file and without including it works perfectly.

Mail.php I am receiving mail too

<?php
error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require_once("vendor/autoload.php");

$mail = new PHPMailer(true);

//Enable SMTP debugging.
$mail->SMTPDebug = 3;
//Set PHPMailer to use SMTP.
$mail->isSMTP();
//Set SMTP host name                          
$mail->Host = "email-smtp.us-west-1.amazonaws.com";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
//Provide username and password     
$mail->Username = "ID";
$mail->Password = "Pass";
//Set TCP port to connect to
$mail->Port = 587;
$mail->setFrom('demo@example', 'demo@example');
error_reporting(E_ALL); // Error/Exception engine, always use E_ALL

ini_set('ignore_repeated_errors', TRUE); // always use TRUE

ini_set('display_errors', true); // Error/Exception display, use FALSE only in production environment or real server. Use TRUE in development environment

ini_set('log_errors', TRUE); // Error/Exception file logging engine.
ini_set('error_log', 'zeeErrors.log'); // Logging file path

function sendEmailToUser($con, $emailMsg, $Subject)
{

    global $mail;

    $msg = "";
    
    $subject = $Subject;
    
        $tempArray = explode(',', $emailMsg);
        $name = $tempArray[0];
        $mobile = $tempArray[1];
        $email = $tempArray[2];
        $mail->Subject = "Test.";
        $to = $email;
        $htmlTemplate = file_get_contents('ration.html', true);
    

    $mail->addAddress($to, $name);     //Add a recipient
    //$mail->addAddress('[email protected]');               //Name is optional
    //$mail->addCC('[email protected]');
    //$mail->addBCC('[email protected]');
    $mail->isHTML(true);


    $mail->Body = $msg;
    //$mail->AltBody = "This is the plain text version of the email content";

    try {
        $mail->send();
        echo "Message has been sent successfully";
        return true;
    } catch (Exception $e) {
        echo "Mailer Error: " . $mail->ErrorInfo;
        return false;
    }
}




?>

AjaxSubmit.php

<?php 
include_once('mail.php');
$response = array();

if((isset($_POST['name'])&& $_POST['name'] !='') && (isset($_POST['email'])&& $_POST['email'] !='') && (isset($_POST['phone'])&& $_POST['phone'] !=''))
{


//whether ip is from share internet
$ia = '';
if (!empty($_SERVER['HTTP_CLIENT_IP']))   
  {
    $ia = $_SERVER['HTTP_CLIENT_IP'];
  }
//whether ip is from proxy
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))  
  {
    $ia = $_SERVER['HTTP_X_FORWARDED_FOR'];
  }
//whether ip is from remote address
else
  {
    $ia = $_SERVER['REMOTE_ADDR'];
  }
  /*Get user ip address details with geoplugin.net*/
$geopluginURL='http://www.geoplugin.net/php.gp?ip='.$ia;
$addrDetailsArr = unserialize(file_get_contents($geopluginURL));
/*Get City name by return array*/
$city = $addrDetailsArr['geoplugin_city'];
/*Get Country name by return array*/
$country = $addrDetailsArr['geoplugin_countryName'];
$region = $addrDetailsArr['geoplugin_regionName'];

if(!$city){
   $city='Not Define';
}
if(!$country){
   $country='Not Define';
}
if(!$region){
   $region='Not Define';
}
  //file_put_contents('zee1.log', print_r($addrDetailsArr, TRUE));

  



    $yourName = $conn->real_escape_string($_POST['name']);
    $yourEmail = $conn->real_escape_string($_POST['email']);
    $yourPhone = $conn->real_escape_string($_POST['phone']);
    $city = $conn->real_escape_string($city);
    $country = $conn->real_escape_string($country);
    $region = $conn->real_escape_string($region);

    $checkSql = "SELECT name, email, contact from reg where email='".$yourEmail."' OR contact='".$yourPhone."'";

    $resultCheck = $conn->query($checkSql);
    if($resultCheck->num_rows > 0) {

        $response['status'] = false;
        $response['msg'] = "You have registered already with ".$yourEmail." OR ".$yourPhone."";;

    }else {
    
    $userLocation = $city.' '.$region.' '.$country;
    
        $sql="INSERT INTO reg (name, email, contact,IP_Address,City) VALUES ('".$yourName."','".$yourEmail."', '".$yourPhone."','".$ia."','".$userLocation."')";
        if(!$result = $conn->query($sql)){
            $response['status'] = false;
            $response['msg'] = 'There was an error running the query [' . $conn->error . ']';
            
        }
        else
        {
            $response['status'] = true;
            $response['msg'] = "Thank you $yourName. Welcome in SAAS Application. We will connect with you soon. :)";
            $msg = $yourName.','.$yourPhone.','.$yourEmail.','.$userLocation;
            if(sendEmailToUser($conn,$msg,'Reg')){
                //Email Sent
            }               
            
            
        }   
    }
    }
     else
    {
        $response['status'] = false;
        $response['msg'] = 'Please fill Name and Email';

    }

    echo json_encode($response);
?>

As i said everything is working if i don't add require in ajaxsubmit file. I am not good in php or JS so after reading so many answers i still can't figure out why i am not able to parse json at my form.

This is JSON Returned by AJAXsubmit

{
    "status": true,
    "msg": "Thank you Demo. Welcome in SAAS Application. We will connect with you soon. :)"
}

CodePudding user response:

Your problem is that mail.php has this code in it:

    try {
        $mail->send();
        echo "Message has been sent successfully";
        return true;
    } catch (Exception $e) {
        echo "Mailer Error: " . $mail->ErrorInfo;
        return false;
    }

which, regardless of the result, causes text to be echo'ed. As a result, your json response will look something like:

Message has been sent successfully
{
 ... normal json response
}

which will not parse successfully.

  • Related