Skip to main content

How to fix Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (

I need some help with this error:Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at Object.success However, on my webiste on every page I have the some contact form where on every page data need be sent to different email address, so all email addresses I save and get from database. Without jQuery code form is sent successfully, all data inserted into db, and in place of jQuery AJAX response I get valid JSON like:

[{"response":"success","content":"Thanks John Doe! Your message is successfully sent to owner of property Hotel Paris! You will get an answer soon!"}]

or if I try to use JSON_FORCE_OBJECT in this case I get valid JSON too, with content

{"0":{"response":"success","content":"Thanks John Doe! Your message is successfully sent to owner of property Hotel Paris! You will get an answer soon!"}}

but with jQuery and AJAX instead a displey a user successfull message I get in network response just empty [] or empty {} with JSON_FORCE_OBJECT. I was spent allready one month, reading complete google how to use json_encode in this case and somewhere for the some case like my case I was find that $jsonData=[]; need be declared before first if statement, so I think too that my PHP code is ok if sent email correctly on every page,insert data into db and in place of jQuery return valid JSON. So bellow it's my form:

<?php
include_once 'inc/form_process.php';
?>
<form  spellcheck="false" autocomplete="off" autocorrect="off" id='contact' class='form' name='contact' action='' method='POST'>
<h4 id="response" class="success"><!-- This will hold response from the server --></h4>
  <fieldset>
    <legend>Your data</legend>
        <div class="form-control halb InputIconBg"><input minlength="6" type="text" class="input username" name="fname" placeholder="Your name..." value="<?php echo Input::get('fname'); ?>"><i class="fas fa-user" aria-hidden="true"></i><span class="error"><?=$fname_error; ?></span></div><!-- end .form-control -->
        <div class="form-control halb InputIconBg"><input minlength="9" type="text" class="input phone" name="tel" placeholder="Your phone..." value="<?php echo Input::get('tel'); ?>"><i class="fas fa-phone-alt" aria-hidden="true"></i><span class="error"><?=$tel_error; ?></span></div><!-- end .form-control --> 
    </fieldset>
    <input type="submit" class="btn_submit" id="submit" name="submit" value="SEND"/>
</form>
<script src="/JS/validOwner.js"></script>

and this is php code

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// define variables and set to empty values
$fname = $tel = $email_address_id = "";
$fname_error = $tel_error = "";
$error = false;
//Load the config file
$dbHost = "localhost";
$dbUser = "secret";
$dbPassword = "secret";
$dbName = "booking";
$dbCharset = "utf8";
try{
    $dsn = "mysql:host=" . $dbHost . ";dbName=" . $dbName . ";charset=" . $dbCharset;
    $pdo = new PDO($dsn, $dbUser, $dbPassword);
    $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}catch(PDOException $e){
    echo "Error: " . $e->getMessage();
}     
use PHPMailer\PHPMailer\PHPMailer;
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';

if($_SERVER['REQUEST_METHOD'] == 'POST'){
    if(isset($_POST['submit'])){
        //print_r($_POST);
    $fname = $_POST['fname'];
    $tel = $_POST['tel'];

    if(empty($_POST['fname'])){
        $error=true;
        $fname_error = "Name can not be empty!";
    }else{
        $fname = $_POST['fname'];   
        if(!preg_match("/^[a-zšđčćžA-ZŠĐČĆŽ\s]*$/", $fname)){
            $fname_error = "Name can contain just letters and white space!";
        }
    }
    if(empty($_POST['tel'])) {
        $tel_error = "Phone can not be empty!";
    }else{
        $tel = $_POST['tel'];
        if(!preg_match('/^[\+]?[0-9]{9,15}$/', $tel)) {
            $tel_error = "Phone can contain from 9 to 15 numbers!";
        }
    }
    if($fname_error == '' && $tel_error == ''){
    // Instantiate a NEW email
    $mail = new PHPMailer(true);
    $mail->CharSet = "UTF-8";
    $mail->isSMTP();
    $mail->Host = 'secret.com';
    $mailOwner->SMTPAuth = true;
    //$mailOwner->SMTPDebug = 2;
    $mailOwner->Username = 'booking@secret.com';
    $mailOwner->Password = 'secret';
    $mailOwner->Port = 465; // 587
    $mailOwner->SMTPSecure = 'ssl'; // tls
    $mailOwner->WordWrap = 50;  
    $mailOwner->isHTML(true);
    $mailOwner->setFrom('booking@secret.com');
    $mailOwner->clearAddresses();
    $mailOwner->Subject = "New message from secret.com";
    
    $query_m = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM booking.owners_email INNER JOIN booking.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
    $dbstmt = $pdo->prepare($query_m);
    $dbstmt->bindParam(1,$pages_id);
    $dbstmt->execute();
    //var_dump($dbstmt);
    //get emails from db via pdo
    $emails = $dbstmt->fetchAll(PDO::FETCH_ASSOC);
    $jsonData=[];
    if(is_array($emails) && count($emails) > 0){
        foreach ($emails as $email){
        //var_dump($email['email_address']);
            $mail->addAddress($email['email_address']);
                $body = "<p>Dear {$email['owner_name']}, <br>" . "You just received a message from <a href='https://www.secret-booking.com'>secret-booking.com</a><br>The details of your message are below:</p><p><strong>From: </strong>" . ucwords($fname) . "<br><strong>Phone: </strong>" . $tel . "</p>";
                $mail->Body = $body;            
                if($mail->send()){
                    $mail = "INSERT INTO booking.contact_owner (fname, tel, email_address_id) VALUES (:fname, :tel, :email_address_id)";
                    $stmt = $pdo->prepare($mail);
                    $stmt->execute(['fname' => $fname, 'tel' => $tel, 'email_address_id' => $email['email_address_id']]);
                    
                if($error==false){
                    $data['response']="success";
                    $data['content']="Thanks ".ucwords($fname)."! Your message is successfully sent to owner of property {$email['owner_property']}!";
                    $jsonData[] = $data;
                }
                }//end if mail send 
                else{
                    $data['response'] = "error";
                    $data['content'] = "Something went wrong! Try again..." . $mail->ErrorInfo;
                    $jsonData[] = $data;
                }       
    }//end foreach for email addresses
}//end if for array of emails

//echo str_replace("[]", "{}", json_encode($jsonData));
//echo json_encode($jsonData, JSON_FORCE_OBJECT, true);
//exit;
//print_r($jsonData);
echo json_encode($jsonData);
    }//end if validation
}//end submit
}//end REQUEST METHOD = POST

And this is my jQuery code

"use strict";
jQuery(document).ready(function () {
  jQuery.validator.addMethod('validFname', function (value, element) {
    if (/^[a-zšđčćžA-ZŠĐČĆŽ ]+$/gi.test(value)) {
      return true;
    } else {
      return false;
    }
  });
  jQuery.validator.addMethod('validTel', function (value, element) {
    if (/^[\+]?[0-9]{9,15}$/gm.test(value)) {
      return true;
    } else {
      return false;
    }
  });

  jQuery("#contact").submit(function (event) {
    event.preventDefault();
  }).validate({
    rules: {
      fname: {
        required: true,
        validFname: true,
        minlength: 6
      },
      tel: {
        required: true,
        validTel: true,
        minlength: 9
      }
    },
    messages: {
      fname: {
        required: 'Name can not be empty!',
        validFname: 'Name can contain just letters!',
        minlength: 'Name must have minimum 6 letters'
      },
      tel: {
        required: 'Phone can not be empty!',
        validTel: 'Phone can contain max 15 numbers!',
        minlength: 'Phone must contain min 9 numbers!'
      }
    },
    submitHandler: function (form) {  
      var formData = jQuery("#contact").serialize();
      console.log(formData);
      jQuery.ajax({
        url: '/inc/form_process.php',
        type: 'post',
        data: formData,
        dataType: 'json',
        cache: false,
        success: function (data) {
          var decodedArray = JSON.parse(data);
          jQuery("#response").text(decodedArray[0]['content']);
          console.log(decodedArray[0].content);
         // debbuger;
        },
        error: function (jqXHR, textStatus, errorThrown){
           console.log(JSON.stringify(jqXHR));
           console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
        }
      }); //Code for AJAX Ends
      // Clear all data after submit
      var resetForm = document.getElementById('contact').reset();
      return false;
    } //submitHandler
  });
}); //document ready

Thanks in advance for any kind of your help and any help will be highly appreciated!



source https://stackoverflow.com/questions/67756431/how-to-fix-uncaught-syntaxerror-unexpected-end-of-json-input-at-json-parse-an

Comments

Popular posts from this blog

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

How to split a rinex file if I need 24 hours data

Trying to divide rinex file using the command gfzrnx but getting this error. While doing that getting this error msg 'gfzrnx' is not recognized as an internal or external command Trying to split rinex file using the command gfzrnx. also install'gfzrnx'. my doubt is I need to run this program in 'gfzrnx' or in 'cmdprompt'. I am expecting a rinex file with 24 hrs or 1 day data.I Have 48 hrs data in RINEX format. Please help me to solve this issue. source https://stackoverflow.com/questions/75385367/how-to-split-a-rinex-file-if-i-need-24-hours-data