Ajax возврат результата php

Как вернуть data из функции ajax?

Lynn

Суть работы с аяксом в том, что вы ничего тут не возвращаете. Это происходит потому, что ajax-запрос — асинхронный, а возврат результата выполнения функций возможен только для синхронного кода.

Чтобы работать с асинхронным кодом, вы должны разбить свой код на шаги, примерно так:

// шаг 1 - запрашиваем данные function step1 () < $.ajax(< success: function (data) < step2(data); // вызываем шаг 2 >>); > // шаг 2, работаем с полученными данными function step2 (data) < // data доступен здесь >

Для облегчения работы с асинхронным кодом, существует разные техники, например промисы

Для облегчения работы именно с Ajax, существуют хорошие библиотеки вроде Fetch

IonDen

raw1: я же говорю, вы никак не можете вернуть дата, в асинхронных задачах нет такого понятие как возврат данных. Вы создаете специальную функцию, вроде step2, где данные становятся доступны в какой-то момент в будущем.

Давайте дядя Сёма объяснит.
Ajax и javascript суть одно и тоже, но живут они с разной скоростью.
Все глобальные переменные javascript видны в ajax сразу и их можно изменять. И они таки изменятся везде, но не сразу. Но пока ajax их изменяет, javascript уже отработал и отдыхает.
Чтобы это не мешало — нужно попросить javascript подождать.
Например вот так:

var data_from_ajax= ""; $.ajax( < type: 'POST', url: 'ajax_do_it.php', dataType: 'json', beforeSend: function(data) < alert("Начинаю выполнение Ajax"); >, success: function(data) < alert("Запрос POST обработан и вернул данные!"); window.data_from_ajax=data['PHP_result_here']; >, error: function (xhr, ajaxOptions, thrownError) < alert("Ошибка с PHP"); >, complete: function(data) < >> ); /* Тут ничего нет, так как javascript обогнал ajax и переменная ещё не присвоена*/ console.log(data_from_ajax); setTimeout(function() < console.log(data_from_ajax); // Покажет данные из PHP /* Только здесь данные из PHP доступны */ >, 3000); /* И тут ничего нет, так как javascript обогнал ajax и переменная ещё не присвоена*/ console.log(data_from_ajax);

Но ждать 3 (или сколько вы там поставите) секунды скучно и не красиво. Это только для примера, так как нормальные пацаны так не делают. Используйте VUE и вот с ним будет красиво. Он и сам подождет и много чего поможет сделать с data_from_ajax (Ну или setInterval и проверку переменной на пустоту. )

Источник

How To Return JSON Response in PHP & MySQL using Ajax and jQuery

In this tutorial, I will share with you how to return JSON response in PHP & MySQL using Ajax & jQuery this is useful to display multiple types of data from server response and process it to our client-side using ajax and jquery. Don’t worry this method is easy we are going to use an array from the server and encode it with JSON format.

Basic Example

Let’s do the basics first we will create a new file called basic.php as you can see below code I created an associative array with first_name & last_name name keys. Then I use json_encode to encode the array into JSON format.

Then this is the result when executing it in the browser.

How To Response JSON in PHP & MySQL using jQuery & Ajax

AJAX Integration

For ajax integration we need to create a simple button in our index.html then a simple ajax function to communicate the above code basic.php.

Let’s code our button with HTML.

Then next is our javascript ajax code. We will create our function named basic() inside scripts.js. Here is the code below:

Then if we will click the button «Basic JSON Response» the result will be like this on the console.

How To Response JSON in PHP & MySQL using jQuery & Ajax

Next, we will parse the response JSON so that we can easily call it as JSON. See the code below.

As you can see we add a new line of code «response = JSON.parse(response);». Kindly see the console result after this code.

How To Response JSON in PHP

As you can see from the result above it is clickable now because we already parse it as JSON from a string.

Display by JSON Property

Now we will display the JSON by property like if you want to display the first_name value only. Here is the code update below:

As you can see below we add a new line of code «console.log(«First Name:» + response.first_name);» now in this code, we only access the first_name value.

Display JSON Property in HTML

Now we will display the specific property on your web page. We will update our HTML code below.

Then also our javascript code inside scripts.js. See below code updates.

As you can see above I add new line of code «$(«#json_first_name»).html(«First Name: » + response.first_name);». I call the ID selector «#json_first_name» and use html() function to display the first_name value from your server.

How To Response JSON in PHP

Now since you have the basic knowledge already of how to Response the JSON we will implement the dynamic data using PHP & MySQL with Ajax.

Display Dynamic Data Using Response JSON with PHP & MySQL

I will share with you the easy method to display the dynamic data from your server-side. In this example, we will display the employee in Edit Employee Modal using ajax and jquery.

Display Dynamic Data Using Response JSON with PHP & MySQL

Here is the HTML code inside index.html

Our HTML code for modal inside index.html

  

Edit Employee

Then our PHP code inside get.php as you can see below that I encode the $row variable array from the result query.

query($sql); // Fetch Associative array $row = $results->fetch_assoc(); // Free result set $results->free_result(); // Close the connection after using it $db->close(); // Encode array into json format echo json_encode($row); ?>

Then now we will add our javascript code get() function inside scripts.js.

function get() < $(document).delegate("[data-target='#edit-employee-modal']", "click", function() < var employeeId = $(this).attr('data-id'); // Ajax config $.ajax(< type: "GET", //we are using GET method to get data from server side url: 'get.php', // get the route value data: , //set data beforeSend: function () , success: function (response) >); >); >

Loop the JSON Response

Since you already know how to display your JSON response to your web page. Now I will give you an example of how to loop the JSON. Below are the screenshot example on listing the employees via ajax with JSON response.

Before we dive in I will show you first a basic code on how to do it. As you can see in the code below I use «$.each(response, function(key,value)

Kindly check the console result below of the above code.

Loop the JSON Response

So that’s the basic way on how to loop the JSON. So we will apply it in the advance by displaying the list of employees using the bootstrap list group as you can see the result below:

Lop the JSON Response

Now let do the code. First set up our HTML code inside index.html.

Then next our PHP Code inside all.php.

query($sql); // Fetch Associative array $row = $results->fetch_all(MYSQLI_ASSOC); // Free result set $results->free_result(); // Close the connection after using it $db->close(); // Encode array into json format echo json_encode($row); ?>

Then now let’s code the javascript for looping the employee’s result via ajax. You will find this code inside scripts.js with all() functions.

function all() < // Ajax config $.ajax(< type: "GET", //we are using GET method to get all record from the server url: 'all.php', // get the route value success: function (response) '; // Loop the parsed JSON $.each(response, function(key,value) < // Our employee list template html += ''; html += "

" + value.first_name +' '+ value.last_name + " (" + value.email + ")" + "

"; html += "

" + value.address + "

"; html += ""; html += ""; html += ''; >); html += '
'; > else < html += '
'; html += 'No records found!'; html += '
'; > // Insert the HTML Template and display all employee records $("#employees-list").html(html); > >); >

Now you have the foundation already about JSON Response from your server-side. I hope this article may help you. To see the action capability of this code just click the «Download» button below.

Thank you for reading. Happy Coding!

Источник

How To Return JSON Response in PHP & MySQL using Ajax and jQuery

In this tutorial, I will share with you how to return JSON response in PHP & MySQL using Ajax & jQuery this is useful to display multiple types of data from server response and process it to our client-side using ajax and jquery. Don’t worry this method is easy we are going to use an array from the server and encode it with JSON format.

Basic Example

Let’s do the basics first we will create a new file called basic.php as you can see below code I created an associative array with first_name & last_name name keys. Then I use json_encode to encode the array into JSON format.

Then this is the result when executing it in the browser.

How To Response JSON in PHP & MySQL using jQuery & Ajax

AJAX Integration

For ajax integration we need to create a simple button in our index.html then a simple ajax function to communicate the above code basic.php.

Let’s code our button with HTML.

Then next is our javascript ajax code. We will create our function named basic() inside scripts.js. Here is the code below:

Then if we will click the button «Basic JSON Response» the result will be like this on the console.

How To Response JSON in PHP & MySQL using jQuery & Ajax

Next, we will parse the response JSON so that we can easily call it as JSON. See the code below.

As you can see we add a new line of code «response = JSON.parse(response);». Kindly see the console result after this code.

How To Response JSON in PHP

As you can see from the result above it is clickable now because we already parse it as JSON from a string.

Display by JSON Property

Now we will display the JSON by property like if you want to display the first_name value only. Here is the code update below:

As you can see below we add a new line of code «console.log(«First Name:» + response.first_name);» now in this code, we only access the first_name value.

Display JSON Property in HTML

Now we will display the specific property on your web page. We will update our HTML code below.

Then also our javascript code inside scripts.js. See below code updates.

As you can see above I add new line of code «$(«#json_first_name»).html(«First Name: » + response.first_name);». I call the ID selector «#json_first_name» and use html() function to display the first_name value from your server.

How To Response JSON in PHP

Now since you have the basic knowledge already of how to Response the JSON we will implement the dynamic data using PHP & MySQL with Ajax.

Display Dynamic Data Using Response JSON with PHP & MySQL

I will share with you the easy method to display the dynamic data from your server-side. In this example, we will display the employee in Edit Employee Modal using ajax and jquery.

Display Dynamic Data Using Response JSON with PHP & MySQL

Here is the HTML code inside index.html

Our HTML code for modal inside index.html

  

Edit Employee

Then our PHP code inside get.php as you can see below that I encode the $row variable array from the result query.

query($sql); // Fetch Associative array $row = $results->fetch_assoc(); // Free result set $results->free_result(); // Close the connection after using it $db->close(); // Encode array into json format echo json_encode($row); ?>

Then now we will add our javascript code get() function inside scripts.js.

function get() < $(document).delegate("[data-target='#edit-employee-modal']", "click", function() < var employeeId = $(this).attr('data-id'); // Ajax config $.ajax(< type: "GET", //we are using GET method to get data from server side url: 'get.php', // get the route value data: , //set data beforeSend: function () , success: function (response) >); >); >

Loop the JSON Response

Since you already know how to display your JSON response to your web page. Now I will give you an example of how to loop the JSON. Below are the screenshot example on listing the employees via ajax with JSON response.

Before we dive in I will show you first a basic code on how to do it. As you can see in the code below I use «$.each(response, function(key,value)

Kindly check the console result below of the above code.

Loop the JSON Response

So that’s the basic way on how to loop the JSON. So we will apply it in the advance by displaying the list of employees using the bootstrap list group as you can see the result below:

Lop the JSON Response

Now let do the code. First set up our HTML code inside index.html.

Then next our PHP Code inside all.php.

query($sql); // Fetch Associative array $row = $results->fetch_all(MYSQLI_ASSOC); // Free result set $results->free_result(); // Close the connection after using it $db->close(); // Encode array into json format echo json_encode($row); ?>

Then now let’s code the javascript for looping the employee’s result via ajax. You will find this code inside scripts.js with all() functions.

function all() < // Ajax config $.ajax(< type: "GET", //we are using GET method to get all record from the server url: 'all.php', // get the route value success: function (response) '; // Loop the parsed JSON $.each(response, function(key,value) < // Our employee list template html += ''; html += "

" + value.first_name +' '+ value.last_name + " (" + value.email + ")" + "

"; html += "

" + value.address + "

"; html += ""; html += ""; html += ''; >); html += '
'; > else < html += '
'; html += 'No records found!'; html += '
'; > // Insert the HTML Template and display all employee records $("#employees-list").html(html); > >); >

Now you have the foundation already about JSON Response from your server-side. I hope this article may help you. To see the action capability of this code just click the «Download» button below.

Thank you for reading. Happy Coding!

Источник

Читайте также:  Css for image align center
Оцените статью