Home Backend Development PHP Tutorial Some common mistakes when using ajax in PHP

Some common mistakes when using ajax in PHP

Feb 28, 2017 pm 02:53 PM

When PHP is used as the backend, when the front-end js uses ajax technology to transmit information to each other, errors often occur, which is a bit at a loss for novices. Summarize mistakes and experiences and review them at any time in the future.

The first problem is that when there are no errors on the front end, the page debugging also shows that there are no problems, but ajax cannot obtain the information sent by the back-end php file:

The front-end code is as follows:

$.ajax({
  url:'1.php',//目的php文件
  data:{"age":12,"name":'zh'},//传送的数据
  type:‘post',//方式post/get
  dataType:'json',//数据传送格式
  success:function(response)
  {
  console.log(response);
  },
  error:function(response)
  {
  console.log(response);
  console.log("错误");
  }
});
Copy after login

php back-end code is as follows:

$postAge = $_POST['age'];
$postName = $_POST['name'];
echo $postAge;
echo $postName;
Copy after login

After the page appears, the F12 debugging view is as follows:

PHP 中使用ajax时一些常见错误

The status code is OK, and the status is 200 , responseReady is 4, indicating that there is no problem in the process of sending html file information to php. And php also returned information. But why does the program go to error instead of success?

You need to be careful at this time! Because multiple echoes in the PHP backend do not organize the data into json format. In other words, php returns a string and not data in json format. Someone said to add json_encode()? This is not possible because the function of json_encode() is not clear. Baidu will take a closer look. json_encode() and json_decode() are a pair.

json_encode(json), organize json into json format data. In the above example, even if the PHP backend code is rewritten as: echo json_encode(postAge); and echojsonencode(postName);, it is incorrect. Because this only organizes a single postAge and postName into json format, but since there are two returns, there are two responses. You can also see one post and two responses on the browser debugging page. As a result, the two json format data returned to the front end are no longer json format data (I understand it as json pollution, which is convenient for understanding). That is to say, a single data is in json format, but multiple json format data are "randomly" combined together without being merged according to json format, which will cause "pollution". As a result, the overall data format is confusing and cannot be recognized. This situation can be seen at any time during data processing and transmission.

json_decode(json,true/false)The function is to organize json into an array or object (understood as a class). true means it is forced to be converted into an (associative) array, false means it will be converted into object form data by default.

Back to the example presented in this article.

Since the data sent back is no longer in json format, then it is a problem with dataType.

dataType tells the browser to check the transmitted data format. If it is not written, the browser will not check the data format. If it is written, it will be checked and must meet the format requirements. In this example, since it is written in json format, but the format returned is not json, the browser thinks that there is an error during the transmission process, so it chooses error instead of success.

The best way at this time is to modify the php code, change the content of echo to an array, and use the array letter form to organize the overall data into json format for transmission (json_encode) to avoid errors. .

Of course, you can also use another method, which is similar to a cheating method. Directly comment out (or not write) the dataType, so that the browser will not check the form of the data but instead based on the form of the data. Intelligent judgment is similar to muddling through.

The following is the W3school explanation of dataType:

PHP 中使用ajax时一些常见错误


##It is worth noting that in the back-end php file After multiple echo outputs, the data is indeed returned together. After the modification is correct, the data obtained by the front end is the data in the form of two data combined into one string. The data obtained in this example is 12zh.


Of course there are many details. For example, the PHP backend can only use echo or die(), and return cannot be used. This is because return is only used to return data on the server side, and echo It is to print data, print the data from the server side and give it to the front end. Return can only be made on the server side, or a single return on the front end. Not to mention the power of die(), it directly terminates the back-end PHP program and returns data.


For example, in $,ajax({}); each line is a parameter, and the parameters are separated by commas. Multiple data are within {}, separated by commas. etc.

Thank you for reading, I hope it can help you, thank you for your support of this site!

For more articles related to some common errors when using ajax in PHP, please pay attention to the PHP Chinese website!



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

See all articles