Having trouble with error code JSON Parse error: Struggling to understand JSON formatting

I am encountering a frustrating issue with a JSON parse error. I can't seem to determine whether the web service is faulty or if there's an issue with my fetch code. When testing the web service on Postman, it returns two objects. However, whenever I try to login using this web service, it consistently gives me a parse error. https://i.stack.imgur.com/YxABw.png

https://i.stack.imgur.com/am7qJ.png

Within my React Native function to loginUser, there may be an error present:

UserLoginFunction = () =>{
 const { UserContact }  = this.state ;
 const { UserPassword }  = this.state ;
 if(this.state.UserContact == ""){
   ToastAndroid.show('Please Enter Contact Number Correctly',ToastAndroid.SHORT)
 }
 else if (this.state.UserPassword == ""){
   ToastAndroid.show('Please Enter Password Correctly',ToastAndroid.SHORT)
 }
 else{

fetch(urls.localhosturl + urls.login, { 
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
 
    user_contact: UserContact,
    user_password: UserPassword,
    //user_name: UserName,
 
  })
 
})
      
      .then((response) => response.json())
      .then((responseJson) => {

        console.log(responseJson)
         if(responseJson === 'Data Matched')
          {
            AsyncStorage.setItem("userContact", JSON.stringify(UserContact));
            this.props.navigation.navigate('Home',{user_contact:UserContact,});

        }
        else{
          ToastAndroid.show(responseJson,ToastAndroid.SHORT);
          
        }

      }).catch((error) => {
        console.error(error);
      });
 
    }
  }

The PHP webservice code snippet is as follows:

<?php

include 'config.php';
$con = mysqli_connect($host_name, $host_user, $host_password, $database_name);

$json = file_get_contents('php://input');
$obj = json_decode($json, true);

$user_contact = $obj['user_contact'];
$user_password = $obj['user_password'];

$Sql_Query = "select * from user_information where user_contact = '$user_contact' and user_password = '$user_password' ";
$check = mysqli_fetch_array(mysqli_query($con, $Sql_Query));

if (isset($check)) {
    $SuccessLoginMsg = 'Data Matched';
    $SuccessLoginJson = json_encode($SuccessLoginMsg);
    echo $SuccessLoginJson;
} else {
    $InvalidMSG = 'Invalid Username or Password Please Try Again';
    $InvalidMSGJSon = json_encode($InvalidMSG);
    echo $InvalidMSGJSon;
}

$result = $con->query($Sql_Query);
$array = $result->fetch_assoc();
$json = json_encode($array, true);

echo $json;

mysqli_close($con);

Answer №1

It appears that the PHP service is relying on the standard output for JSON data.

The issue seems to be with the line:

echo $SuccessLoginJson;

You might consider hiding this message, saving it to a log file, or directing it to standard error instead. By doing so, you'll avoid confusing your client with unexpected results from the web service.

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

Retrieve content from a PHP tag using AJAX

How can I use AJAX to fetch images from a database and display them in a div with the id "test" when a button with the class "addCart" is clicked? I need to get the IDs of products from my database and show them in the AJAX code. $(document).ready(func ...

Ways to guarantee that the factory promise is fulfilled prior to the execution of the

So far, I have always found valuable help by studying existing answers on stackoverflow, but now I've hit a roadblock. I'm currently working on an app that utilizes a directive to generate calendar month boxes. <app2directive class="column_5 ...

Sign Up and Access

Encountering an error while trying to register? Oops! Something went wrong. Please try again later. This issue is new to me, despite my frequent use of it in the past. Any thoughts on how to resolve this? Config.php <?php /* Database credentials. A ...

Steps to Show New Blog Entries on WordPress Homepage Only After Clicking a Link

When a specific tab is clicked on the WordPress blog home page, the following process should be initiated. The content should be displayed using AJAX for a smoother user experience. For instance, in the blog homepage, there are three tabs titled "They Li ...

CodeIgniter does not support the foreach function

I am encountering an issue with the foreach function where the resulting data is not displaying all information from the database. The table in question is named "view_kebutuhan_perjal". Code snippet from Model: function getPerjal() { $query= ...

Email confirmation section

I'm in the process of setting up a subscription newsletter page, and everything seems to be working correctly except for the part where I need users to enter their email address twice. The second email field is meant for confirmation purposes, but I&a ...

Having difficulty interpreting the json data retrieved from the specified url

<html> <body> <script src='http://code.jquery.com/jquery-1.10.2.min.js'></script> <script> $(document).ready(function () { $.ajax({ type: 'GET& ...

What is the best way to recursively analyze JSON and locate a particular object?

Check out my JSON file here! Below are the C# classes generated from the JSON: public class SiteNode { public string url; public string[] param; public string serviceid; public bool is_enabled; public string icon; public string no ...

How can I iterate through a JavaScript object in a recursive manner?

I am endeavoring to design a function that will generate an output like the following when given an object: <div> reason : ok status : 0 AiStatistics : null CurrentSeasonArenaStatistics : null <div> Player <div> CampaignProgr ...

Is there a constraint on JSON data?

Is there a limit to the amount of data that JSON with AJAX can handle in outgoing and returning parameters? I am trying to send and receive a file with 10,000 lines as a string from the server. How can I accomplish this task? Can a single parameter manage ...

Is there a way to reveal the hidden HTML element within Zend_Form_Element_Select for printing?

Currently, I am working on creating a form manually with extensive JavaScript. On the server side, I rely on Zend_Form classes for input validation and more. I am wondering if there is a method to render a specific element like Zend_Form_Element_Select wi ...

Obtaining JSON values with a designated key name from a intricate hierarchy within postgresql

I am seeking assistance with extracting all element values with the key '$type' from a highly nested JSON structure stored in a PostgreSQL json field. This structure includes arrays within arrays to multiple levels of depth. Can someone provide m ...

Difficulty in finding an element on a webpage

Inspecting an HTML Element While using Selenium WebDriver, I am attempting to find and clear a textbox element shown in the image using the following code: driver.findElement(By.name("X")).clear(); or driver.findElement(By.cssSelector("input[name=X][ty ...

What is the best way to split a JSON array in a Hive table into batches based on a specified batch size?

Suppose we have a hive table structured as follows: id entities 1 [{"a": "a1", "b": "b1"}, {"a": "a2", "b": "b2"}, {"a": "a3", "b": "b ...

Can you identify the issue in this code?

I am facing an issue with using this code to save values in a table when the page loads. The function that searches for values is written in PHP, and I need to use these values in my script. Unfortunately, the current approach I am trying doesn’t seem ...

Transform Json data into a C# collection

I am encountering an issue while trying to deserialize JSON into a collection of C# objects. The error message I am receiving is as follows: {"Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'Sys ...

The transfer of character data from PHP to jQuery is not successful

Working with HTML files In this scenario, the values for the sub combobox are being retrieved through a PHP select query and these values are in character format. I have successfully tested passing integer values. <select name="sub" id="sub"> ...

Automatically collapse JUNIT 5 reports for easy management

While running my JUNIT 5 tests, I noticed that the report collapses automatically between parameterized test executions: https://i.stack.imgur.com/zD1zh.png For instance, when the first Device test is in progress, the report expands. However, once it com ...

Combining two columns to generate a query for account creation flow

There are two tables: one for client credit (payments) and another for debit (withdrawals). The payments table looks like this: id client date amount 1 ana 2012-01-01 5000 2 ana 2012-02-01 10000 ...

Utilizing a modular perspective in JavaScript to load JSON files as a view

I've been working on implementing a modular view approach for retrieving data from a JSON file in my JavaScript code, but I'm facing some issues. The snippet of code where I am trying to load the JSON file is contained within a separate JS file a ...