How to send a response in PHP

by | Jun 22, 2021 | PHP

Home » PHP » How to send a response in PHP

Introduction

Whatever we see on our website, it is either saved within HTML or being fetched from a table. The HTML has a script file attached with it which calls backend, where SQL codes are written. These SQL codes interact with database. In this article we will learn how to send a response in PHP. There are different ways to send response via PHP APIs, we will showcase the one that can be used in all types of CRUD operations here.

Syntax

// to send an array of data in respone
echo json_encode(<array variable>);
// to send a string
Echo ‘<Your string>’;
// to send error of SQL
echo json_encode(mysql_error());
or
echo $conn->error

How to send a response in PHP

As discussed in above use cases, we can send as below:

Error TypeExample
Stringecho ‘Operation successful’;
Array$dataArray[0] = ‘Insertion successful’;

echo json_encode($dataArray);

Objectecho json_encode(mysql_error());

 

Getting PHP response in frontend

As you have seen above that a response can be of different type, hence in UI you will have to handle the response accordingly.

In case it is a string, you can print it directly.

In case of array you need to print the value at given position, e.g. response[0].

In case of object you need to print the value after parsing it with the help of keys.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author