Unexpected JSON token error occurs in jQuery when valid input is provided

I encountered an error that I'm struggling to pinpoint. The issue seems to be related to the presence of the ' symbol in the JSON data. After thoroughly checking, I am positive that the PHP function json_encode is not responsible for adding this symbol at the beginning.

Despite scouring through StackOverflow and various other platforms, I have yet to come across a solution tailored to this specific predicament.

SyntaxError: Unexpected token ' in JSON at position 0
    at parse (<anonymous>)
    at e.parseJSON (jquery-migrate.min.js:2)
    at fn (jquery.min.js:6)
    at k (jquery.min.js:6)
    at XMLHttpRequest.<anonymous> (jquery.min.js:6)

Shown below is the PHP script responsible for generating the JSON string.

$info = Embed\Embed::create($videoUrl);

$result = array();

$result['title'] = $info->title;
$result['desciption'] = $info->description;
$result['type'] = $info->type;
$result['tags'] = $info->tags;
$result['provider'] = $info->providerName;

echo json_encode($result,true);

Additionally, here's the jQuery code utilized for executing a post request.

$(document).ready(function () {

    $("#videoUrl").blur(function (event) {

        if ($(this).val() != '') {

            $.ajax({
                type: 'POST',
                url: '/url-here',
                dataType: 'json',
                data: {
                    "value": $(this).val()
                },
                success: function (msg) {
                    alert("Data Saved: " + msg);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log(errorThrown.message);
                }
            })
        }

    });

});

The Chrome console output provides a glimpse of the sample response received.

'{"title":"Inside of big gold mine in Africa. How it works. Documentary.","desciption":"Deepest mine in Africa.","type":"video","tags":["Megastructures","mine","gold","deepest mine","documentary","Deepest","how it works"],"provider":"YouTube"}

EDIT:

Upon request, I am sharing the entire PHP code snippet below.

public function getVideoDetails() {
   OW::getResponse()->clearHeaders();
   OW::getResponse()->setHeader('Content-Type', 'application/json; charset=utf-8');

   $videoUrl = $_POST['value'];

   $info = Embed\Embed::create($videoUrl);

   $result = array();

   $result['title'] = $info->title;
   $result['description'] = $info->description;
   $result['type'] = $info->type;
   $result['tags'] = $info->tags;
   //$result['image'] = $info->image;
   $result['provider'] = $info->providerName;

   echo json_encode($result, true);

   OW::getResponse() - > sendHeaders();
   exit;
}

Answer №1

One of the frequent causes for random letters appearing at the beginning of PHP responses is the presence of a character preceding the <?php tag in one of the connected PHP scripts.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding a class to the following DIV and smoothly transitioning the current one out can be achieved using a dynamic number of items in multiple instances

Is there a way to create a scalable CSS slideshow for text divs without using images? Here is the current HTML structure: <div class="mb-panel-container cf"> <div class="mb-panel-section mb-slider"> <div class="mb-panel active" ...

Utilizing Python to extract data from a JSON file

I have been working on reading a JSON file in Python and have run into an issue where some top values are being skipped. I am currently debugging to identify the root cause of this problem. Here is the code snippet: data = json.load(open('pre.txt&apo ...

Utilize Vue.js to send bound data to a click event

I am currently working with a v-for loop that iterates over data fetched from an API, setting the key as the ID of each object. My goal is to create a click event that captures the v-bind:key value of the clicked element. This will allow me to locate all t ...

JavaScript Summation Calculation

I am currently working on calculating the sum of three scores and displaying the total as "Total:". However, I am facing an issue in dynamically updating the total whenever a score value changes. Is there a way to utilize the "onchange" event to achieve th ...

How can I access the ng-template in a component?

How can I reference <ng-template #modal_Template> in my component.ts file? Previously, I triggered a modal using a button on my HTML file and included this code: <button type="button" class="btn btn-primary" (click)="openModal(modal_Template)"> ...

Controlling the Quantity of Selected Checkboxes with JavaScript

I am facing an issue with implementing multiple checkboxes with limits in JavaScript, as shown below. $(".checkbox-limit").on('change', function(evt) { var limit = parseInt($(this).parent().data("limit")); if($(this).siblings(':checked&ap ...

How can we display the Recent Updates from our LinkedIn profile on our website using iframe or javascript?

Currently, I am in the process of developing a .NET web application for our company's website. We already maintain an active LinkedIn profile where we regularly post updates. https://i.stack.imgur.com/T2ziX.png My main query at this point is whether ...

Preventing navigation without using the <Prompt> component in React Router DOM V6

I have recently discovered that in react-router-dom v5, it was possible to utilize the <Prompt> component to prompt the user before a page transition occurs, allowing them to prevent it. However, this feature has been removed in v6 with plans for a m ...

Uploading Multiple Files with Ajax and jQuery

I've been trying to implement an ajax multiple file upload form, but I'm facing issues with its functionality. Here is the HTML Code: <form method="post" id="postfrom" enctype="multipart/form-data"> <input type="file" name="file" i ...

What is the best way to send {...rest} properties to a text field in react material?

When using a material textfield inside a wrapper component and passing the remaining props as {...otherprops} in a JavaScript file, everything works fine. However, when attempting to do the same in TypeScript, an error occurs. const TextFieldWrapper = (pro ...

Retrieving JSON data from PHP using jQuery

I've been struggling with this issue for two whole days now, and I feel like I've hit a dead end in trying to solve it on my own. Here's the situation: I have two pages - one that contains a form with an address field that gets auto-filled ...

Adjusting the Aspect Ratio of an Embedded YouTube Video

<!DOCTYPE HTML> <head> <style> body { overflow: hidden; margin:0; } </style> </head> <body> <iframe id="video" src="https://www.youtube.com/embed/U4c9bBeUe4M?modestbranding=1&sh ...

Transferring specific form data through a POST request

I am attempting to transfer specific values from a form to PayPal once the form is submitted. Below is the code for my form: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form class="form-horizo ...

Shake up your background with a random twist

Seeking assistance with customizing the Aerial template from HTML5UP. I am interested in selecting a scrolling background randomly from a pool of images. Can someone guide me on how to achieve this? Presently, the background is defined within a code block ...

Steps for clearing input field with type=date in Protractor:

I am currently working with protractor version 4.0.4 and I'm encountering an issue where I cannot clear a date input field. It seems like Chrome is introducing some extra controls that are causing interference. You can find further details about Chro ...

Customizing the date format for each IService in ServiceStack, rather than applying it globally

In my content management system, I have decided not to use the native .NET (WCF) date formatting that is preferred. Instead, in my custom IService, I have set: JsConfig.DateHandler = DateHandler.ISO8601;" However, this decision appears to have caused the ...

Consolidate all data connected to the specified key from a JSON dataset

Looking at the json string presented below [{"_id":"9/17/2015","amt1":0,"amt2":13276.5},{"_id":"9/18/2015","amt1":8075,"amt2":6445.5}] The expected outcome is: [{"_id": ["9/17/2015", "9/18/2015"], "amt1": [0, 8075], "amt2": [13276.5, 6445.5]}] Is there ...

Several Divs Positioned on Different Pages with Backgrounds That "Scroll"

Currently utilizing: jQuery Mobile 1.4.5 I am interested in knowing if it is feasible to achieve the following, and if so, how to start working on it. At the moment, there are 4 page divs that utilize swipe for navigation between them with a horizontal t ...

Exploring AngularJS: Retrieving a list of filenames from a specified directory

In the public directory of my application, there is a folder named 'x'. I have the path name to the folder (/path/to/dir/x) but I am unsure of the names of the files within it. How can I retrieve the file names and provide URL links to them in an ...

Working with the WYSIWYG field in a custom module in Magento

My Magento Module includes a wysiwyg field where I encounter an issue with processing the image path. When using the "Insert image" button in the wysiwyg, it generates the following code: <img src="{{media url=" wysiwyg/slide.jpg"}}" alt=""/> The i ...