Unexpected display of Unicode text retrieved through ajax requests

In my setup, I have both an admin module and a front end module available.

Specifically, there is a category section that plays a key role in the functionality.

To create categories, I utilize AJAX to send data from a text box to PHP. It's important to note that both the admin and front end modules support utf-8 character encoding.

Typically, AJAX uses utf-8 encoding by default, which allows for successful saving of Unicode text in the database.

This Unicode text can be viewed in the database itself, as well as when listing items within both the admin and front end sections.

However,

An issue arises when attempting to edit existing data. When fetching this data using AJAX/JSON, instead of displaying the Unicode text properly, it returns as a series of question marks (????).

Oddly enough, during normal loading situations, the Unicode text displays correctly without any problems.

What could possibly be causing this discrepancy? Is there something I am overlooking?


Edit

var jax = createAjax();
jax.open("POST",path,true)  
jax.setRequestHeader('Content-type','application/x-www-form-urlencoded; charset=utf-8');
jax.onreadystatechange = afunction;

Provided above is the pertinent PHP code snippet:

$query = "select * from $box where id=$id";
if(! ($res = mysql_query($query)))die(mysql_error());
$rs = mysql_fetch_array($res,1);
$rs['status'] = 1;
header("Content-Type: text/html; charset=utf-8");
die(json_encode($rs));

I've made sure to use the same utf-8 encoding for both requests and responses, even experimenting with changing it to iso-85**-1 with no noticeable effect.

For visual reference, attached below are screenshots: Please open the images in a new window or tab for better viewing.

The first image showcases how the utf characters are displayed smoothly in the listings, while the second highlights the issue when editing via AJAX and JSON - resulting in the dreaded '???'.

Additionally, here's a glimpse of how the text appears within the database...

Answer №1

Utilize the following SQL query: SET NAMES 'utf8' COLLATE 'utf8_general_ci'

This solution proved to be effective in resolving the issue.

Remember to execute the above query after establishing the database connection.

I came across this information while working with the CodeIgniter framework. Utilizing CodeIgniter ensured that my code functioned correctly, whereas directly using mysql_query did not provide the expected outcome.

If you are using CodeIgniter, this setting is implemented by default; otherwise, ensure to include this line of code.

I refrain from accepting this as the definitive answer, as there may be other reasons or insights shared by fellow users. I am open to more comments and responses on this matter.

In any case, the issue has been resolved now.

Furthermore, verify that both the table collation and field are set to utf8.

Answer №2

Here are two options to fix the issue:

  1. Try opening your files in notepad, then save them with the utf-8 format instead of Ansi. This is especially important for the JSON file.
  2. Make sure that your response is forced to be utf-8 (for PHP users:
    <?php header('Content-type: text/html; charset=utf-8'); ?>

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

Reset all entered information in the form

Within a form, I have some inputs that are loaded in a special partial view, and I am able to successfully reset the form. However, when I reload this partial view using ajax with new data, the form reset button stops working altogether. I currently use j ...

What is the best way to close ngx-simple-modal in angular7 when clicking outside of the modal component?

Can anyone help me with closing the modal in my angular7 app when the user clicks outside of the modal component? I have been using the ngx-simple-modal plugin, and I tried implementing the following code: this.SimpleModalService.addModal(LinkPopupCompone ...

Activate function when list item is clicked

My goal is to execute a function when users click on the li elements in the snippet below without relying solely on onclick. For instance, clicking on the first li element (with a value of 1) should trigger a function where the value "1" is passed as an ar ...

The onhashchange function is limited in its ability to completely track changes in the hash

I set up an onhashchange event listener on the page in the following way: window.addEventListener('hashchange', () => console.log('hash change!')) This listener can detect hash changes that I manually enter: However, I am not see ...

There seems to be an issue with [object%20Object]/undefined within the

AuthenticationService.js import axios from 'axios'; const AUTH_API_BASE_URL = "http://localhost:8087/auth"; class AuthenticationService { login(user) { return axios.post(AUTH_API_BASE_URL + "/login", user); } getRo ...

Organizing AngularJS Data by Initial Letter with the <select></select> HTML Element

I'm trying to figure out how to filter an ng-repeat function based on the first letter of each option. For example, I want to filter a set of array or string so that only options starting with "A" or "B" are displayed. Can anyone help me with this? H ...

How can the outcome of the useQuery be integrated with the defaultValues in the useForm function?

Hey there amazing developers! I need some help with a query. When using useQuery, the imported values can be undefined which makes it tricky to apply them as defaultValues. Does anyone have a good solution for this? Maybe something like this would work. ...

Populating datagrid columns with database information post page load

I am currently facing an issue with a web page where loading additional data from an SQL query into a datagrid is significantly slowing down the performance. Despite ensuring that all necessary database indices are in place, the query now takes 3-4 seconds ...

Utilize Angular's $location to add or update the current URL parameter

I'm working on a function for handling multiple parameters in the URL when clicking an element. Specifically, I need to check if parameter pthree exists, update it to a new value without duplicating, and if it doesn't exist, append it to the curr ...

I'm having trouble figuring out how to access response headers with HttpClient in Angular 5. Can anyone

I recently developed an authentication service in Angular 5, where I utilize the HttpClient class to make a POST request to my backend server. The backend server then responds with a JWT bearer token. Here is a snippet of how my request looks: return thi ...

Learn how to connect a Firebase account that was created using a phone number

✅ I have successfully implemented the feature that allows users to update their profile with a mobile number using verifyPhoneNumber and update currentUser.updatePhoneNumber ❌ However, a problem arises when a new user attempts to sign in with a phone ...

Is the SharePoint Note Board an Effective Tool for Commenting?

I am currently experiencing an issue with SharePoint 2010 where comments posted to a note board web part are not visible to other viewers until they refresh. Does anyone have any suggestions on how to fix this problem? Is it possible to add this functional ...

Creating a table in React using an object with nested objects

I have 2 different types of JSON APIs and I want to showcase them in a table. The first type has the following structure: data1:[ { "id": 1, "name": "Leanne Graham", " ...

Rapid processing of JavaScript upon page load

I recently implemented a dark mode feature on my WordPress site. Here are the four modes I included: 1- Automatically based on user's system settings 2- Light mode 3- Semi-lit mode 4- Dark mode The implementation is in place and functioning perf ...

The Strong Password checker fails to identify the presence of a forward slash

Here is a regex I have for validating a strong password: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d!$\/%@]{6,20}$/ Criteria: Alphanumeric with special characters $/%@ At least 1 number At least 1 lowercase letter At least ...

The CKEditor value is set to the result of the dropdown selection

I need to implement a dropdown feature on my form where the options correspond to titles of content in my database. Once an option is selected, I want the corresponding content to display in a CKEditor field. I'm attempting to achieve something simil ...

Simply interested in extracting the JSON Class specifically, not all of the data

Looking for a way to extract only text from a specific class using $.getJSON and YQL. Currently, it retrieves all data and removes tags. Is there a method to achieve this? function filterData(data){ // remove unwanted elements // no body tags ...

What steps should I take to develop a one-page ASP.NET web application that sends data to a database?

So, I've been working with ASP.NET as a web developer for quite some time now, but I usually start with a prepackaged ASP.NET MVC site and extend it from there. However, at the moment, all I need to do is create a single-page ASP.NET page that submits ...

Neglecting the Outcome of Async/Await

I am facing an issue where I need to send different SMS messages to different recipients synchronously, but my current implementation using async/await is not producing the expected results. Below is the code snippet causing the problem: Upon querying fo ...

Leverage JSON data using props in React JS

Currently, my data is formatted in JSON and successfully populated into props known as foxFooterData. Upon inspecting the console.log result of foxFooterData.data, the following information is visible: https://i.sstatic.net/8htNG.png I am attempting to r ...