I have a <select> with only one option, i want to get the rest of the options from a database using PHP and then populate said <select> with the PHP result using AJAX.
Unfortunately my code is not working, im not surprised as im new to both AJAX and jQuery but i dont get any errors to guide myself through the issue.
The PHP works as expected because its used in another part of the site and i have no issues with it so my error must be in the AJAX (no big surprise here).
Below my HTML:
<select class="custom-select my-1 mr-sm-2" id="producto" name="producto" required>
<option disabled selected value>Elegir...</option>
</select>
Below my AJAX code:
<script type="text/javascript">
$(document).ready(function() {
$("#producto").click(function() {
$.ajax({
url: 'fetch_lista_productos_compra.php',
type: 'get',
success: function(data) {
$("#producto").append(data);
}
});
});
});
</script>
Below my PHP code:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/testground/php/db_key.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_query = mysqli_query($conn, "SELECT * FROM productos WHERE disponibilidad = 'disponible'");
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
echo <<<EOT
<option value="$titulo">$titulo</option>\n
EOT;
}
?>
As always any kind of help is greatly appreacited and thanks for your time.
IMPORTANT EDIT
<select> has a duplicated id, perhaps i should i have stated this from the start as i know think thats whats causing my issue.
The fact is that in this <form> the selects are created dynamically on user request. They click on Add product and a new select with the products avaiable is created, i know the id/name of said input must have [ ] (id="producto[]") for it to be converted into an array but i dont know how to make the AJAX deal with this dynamically created reapeated selects issue. I apologise for this belated aclaration i realise now it is of the utmost importance.
You have to edit your response from this:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/testground/php/db_key.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_query = mysqli_query($conn, "SELECT * FROM productos WHERE disponibilidad = 'disponible'");
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
echo <<<EOT
<option value="$titulo">$titulo</option>\n
EOT;
}
?>
To this:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/testground/php/db_key.php';
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_query = mysqli_query($conn, "SELECT * FROM productos WHERE disponibilidad = 'disponible'");
$response = '';
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
$response .= '<option value="' .$titulo . '">' . $titulo . '</option>'; //Concatenate your response
}
echo $response;
?>
But i suggest to use JSON to get a response and parse it on client side.
You can do this by pushing all values in to response array and use json_encode(). At the end you get straight response from the server with just a values, and append thous values whatever you need on client side.
Update
Also you append data to your existing select options. You can just add thous by editing this:
<script type="text/javascript">
$(document).ready(function() {
$("select#producto").focus(function() { //Change to on Focus event
$.ajax({
url: 'fetch_lista_productos_compra.php',
success: function(data) {
$("select#producto").html(data); //Change all html inside the select tag
}
});
});
});
</script>
Test result:
$('select#options').focus(function(){
alert("Hello this is a select trigger");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="options">
<option value="test">Test</option>
</select>
Please don't construct your html on the server, try to just send the raw data and then construct the html client-side, it's better that way and it leaves room for changing the view later without much coupling.
That said, instead of doing:
while ($row = mysqli_fetch_assoc($sql_query)) {
$titulo = $row['titulo'];
echo <<<EOT
<option value="$titulo">$titulo</option>\n
EOT;
}
just do
$rows = [];
while ($row = mysqli_fetch_assoc($sql_query)) {
$rows[] = $row;
}
//this is your best bet when sending data from PHP to JS,
//it sends the rows as JSON-like string,
//which you'll parse to an array in the client
echo json_encode($rows);
then in the client
$.ajax({
url: 'fetch_lista_productos_compra.php',
type: 'get',
success: (data /*json-like string*/) => {
const dataAsArray = JSON.parse(data);
$.each(dataAsArray, (index, row) => {
//now HERE you construct your html structure, which is so much easier using jQuery
let option = $('<option>');
option.val(row.titulo).text(row.titulo);
$("#producto").append(option);
});
}
});
Regarding your edit about several selects
I don't have access to your server of course so I'm using a mock service that returns JSON. IDs are dynamically generated and all data loading occurs asynchronously after you click on the button.
Try using your url and modify the success function according to your html.
$(document).ready(function() {
$('#add').click(() => {
//how many so far...?
let selectCount = $('select.producto').length;
const select = $('<select class="producto">');
select.attr('id', `producto${selectCount + 1}`);
//then we fetch from the server and populate select
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
type: 'get',
success: function(data) {
data.forEach((d) => {
const option = $('<option>');
option.val(d.id).text(d.title);
select.append(option);
});
}
});
document.body.appendChild(select[0]);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='add'>Add product</button><br>
<!--<select class="custom-select my-1 mr-sm-2" id="producto" name="producto" required>
<option disabled selected value>Elegir...</option>
</select>-->
HIH
As it turns out the code in the question was actually working properly, the problem was not the code itself but the fact that, as i stated (sadly on a later edit and not right from the start) in the question, there where more than one <select> using the same id, therefore everytime the AJAX was executed the result was appended to the first <select> only, and it was appended over and over again everytime i clicked it, my solution was unifiying both the AJAX that populated the <select> and the jQuery that created the said dynamic <select>'s all in one script thus solving all of my issues at once.
Below my jQuery/AJAX code:
<script type="text/javascript">
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 0;
$(add_button).click(function(e) {
e.preventDefault();
$.ajax({
url: '/testground/php/fetch_lista_productos_compra.php',
type: 'get',
success: function(data) {
if(x < max_fields) {
x++;
var html = '';
html += '<div class="form-group row" id="inputFormRow" style="margin-bottom: 0px;">';
html += '<label class="col-3 col-form-label font-weight-bold">Producto</label>';
html += '<div class="col-7">';
html += '<select class="custom-select my-1 mr-sm-2" id="producto" name="producto[]" required>';
html += '<option disabled selected value>Elegir...</option>';
html += data;
html += '</select>';
html += '</div>';
html += '<div class="col-1 my-auto" style="padding: 0px 0px 0px 0px;">';
html += '<button id="removeRow" type="button" class="btn btn-danger">X</button>';
html += '</div>';
html += '</div>';
$(wrapper).append(html);
}
}
});
});
$(document).on('click', '#removeRow', function () {
$(this).closest('#inputFormRow').remove(); x--;
});
});
</script>
I want to thank everyone that took the time to help me out with this Swati, Serghei Leonenco and Scaramouche, this community is truly amazing.
<script type="text/javascript">
$(document).ready(function() {
$("#producto").change(function() {
$.ajax({
url: 'fetch_lista_productos_compra.php',
type: 'get',
success: function(data) {
console.log(data)
// $("#producto").append(data);
}
});
});
});
</script>`enter code here`
try run this and check in your console that weather you are receiving the data from your php or not.
Related
I have a PHP script which Edit and Delete cars on my website. Now I want to make Edit and Delete buttons inside a dropdown, and I did but its adding dropdown just to the first car from the row, since the ID is the same for every dropdown. Now I know how to get the unique ID from every car from PHP but how can I achieve it in JavaScript. I will show you my code.
PHP:
$id = $row["id"];
<div class='dropdown'>
<button onclick='myFunction()' class='dropbtn'>Settings</button>
<div id='myDropdown".$id."'class='dropdown-content'>
".($featured!=1 ? "<a title='Make ".$title." Featured'href='forms/addfeatured.php?id=".$id."'>Make Featured</a>" : "<a title='Remove ".$title."' href='forms/removefeatured.php?id=".$id."'>Remove Featured</a>")."
<a title='Delete ".$title."' href='forms/deletecars.php?id=".$id."'>Delete</a>
</div>
JavaScript:
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
So how can I have different ID in javascript so I can open dropdowns for each entry?
Only use , No need to technically learn AJAX or JSON !
You Just need to use the simple functions which has been prepared for use and has been put in the libraries. And set a few parameters that they need.
The important thing is that, You should know PHP runs on the server machine, not your browser or your PC.
So the PHP variables too.. They are not in your machine to easily put them in a JS variable.
At his point we need to communicate with the server to send them(using AJAX function) in a proper format(using JSON function) for us to use.
So, Your question :
How to add ID from PHP script to JavaScript code?
has the easiest solution just with these functions:
(At your browser page):
$.ajax({ .. some parameters .. });
$(document).ready(function() {
$.ajax({
type: 'post', //Transfer Protocol
url: 'serving.php', //Address of Server Page
dataType: 'json', //Data Structure
data: {action: 'demo'},
success: function(output) {
$variables = output;
}
});
});
and
(At your PHP page on the server)
json_encode(.. some data ..);
$variables = array("Chevy", "BMW", "Ford");
echo json_encode($variables ); // Encoded variable array
Unfortunately your codes and description are not clear for me to help directly in your project.
But I attach a simple practical Example :(in Jquery)
// carSelection.html page
<!DOCTYPE html>
<html lang="en">
<head>
<script
src="https://ajax.googleapis.com/ajax/libs
/jquery/2.1.1/jquery.min.js"> //jquery CDN
</script>
</head>
<body>
<div style="margin:2em">
<form id="myForm">
<select id="selectNumber">
<option>Choose a car</option>
</select>
</form>
</div>
<script>
var $cars = '';
$(document).ready(function() {
$.ajax({
type: 'post',
url: 'carServs.php',
dataType: 'json',
data: {action: 'demo'},
success: function(output) {
$cars = output;
var option = '';
for (var i=0;i<$cars.length;i++){
option += '<option value="'+ $cars[i] +
'">' +
$cars[i] + '</option>';
}
$('#selectNumber').append(option);
}
});
});
</script>
</body>
</html>
And
// carServs.php page
<?php
// ...
$cars = array("Chevy", "BMW", "Ford");
echo json_encode($cars);
//...
?>
just remeber to attach the jquery CDN at your code, In the head section or just before ending the body tag </body>
And if you insist to have it in JavaScript, It's possible just with a few changes in syntax.
I have this code, where when I click on a value in my first drop list, I need to get new data from MySQL into my second drop list according to my selection.
I have this code here:
$('#sale_type').change(function() {
// get the form information
// this can be done in many ways but we are going to put the form
// data into a data object
var formData = {
'selectedValue' : $('#sale_type').val()
};
// send the data via Ajax
$.ajax({
type : 'POST', // the method we want to use to send the data
url : 'getTypeDetails.php', // the url where we want to
// send the data
data : formData, // the data object we created
dataType : 'json', // what type of data we want to get back
encode : true
})
// execute function when data has been sent and server
// code is processed
.done(function(data) {
// HERE ADD THE CODE THAT UPDATES THE OTHER DROPLIST
// I BELIEVE YOU WILL BE ABLE TO ACCESS THE DATA LIKE THIS
// data[0], data[1]... TO GET THE VALUE
});
});
});
And here is getTypeDetails.php:
<?php
require_once('../include/global.php');
$data = $_POST['selectedValue'];
// Connect to database
// Use the data to get the new information
$query = "SELECT * FROM purchases WHERE sale_type = :data";
// MySQL
$results = $conn->prepare($query);
$results->bindValue(":data", $data);
$exec = $results->execute();
$res = $results->fetchAll();
$data = array();
$i = 0;
foreach($res as $row){
$data[i] = $row['sale_details'];
$i++;
}
echo json_encode($data);
?>
the problem is that I can't get the $data[i] into my new drop list with an id=sale_details
So I don't know what to put here:
.done(function(data) {
// HERE ADD THE CODE THAT UPDATES THE OTHER DROPLIST
// I BELIEVE YOU WILL BE ABLE TO ACCESS THE DATA LIKE THIS
// data[0], data[1]... TO GET THE VALUE
});
EDIT
Those are my HTML drop lists:
<label for="sale_type" class="col-lg-1 control-label" style="float:right">النوع</label>
<select id="sale_type" name="sale_type" class="dropdown-header" style="float:right">
<option value="undefined">اختر</option>
<?php
foreach($fetchType as $ft){ ?>
<option value="<?php echo $ft['sale_type'] ?>"><?php echo $ft['sale_type'] ?></option>
<?php } ?>
</select>
<label for="sale_details" class="col-lg-1 control-label" style="float:right">الصنف</label>
<select id="sale_details" name="sale_details" class="dropdown-header" style="float:right">
</select>
It should be something like this:
.done(function(data) {
var secondDropdown = $("#second-dropdown");
secondDropdown.empty();
$.each(data, function(index, value) {
secondDropdown.append("<option>" + value + "</option>");
});
return;
}
Replace your js code with my code
<script>
$(document).ready(function() {
$('#sale_type').change(function() {
var formData = { 'selectedValue' : $( "#sale_type option:selected" ).val() };
console.log(formData);
$.ajax({
type: 'POST',
url: 'getTypeDetails.php',
data: formData,
success: function(data){
var obj = jQuery.parseJSON(data);
var secondDropdown = $("#sale_details");
secondDropdown.html('');
for (var prop in obj) {
secondDropdown.append("<option>" + obj[prop] + "</option>");
}
},
error: function(errorThrown){
alert(errorThrown);
}
});
return false;
});
});
</script>
and add jquery link
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
in your <head> tag
I'm working on a PHP application i want to submit form without refresh page. Actually, i want my php code to be written on the same page as the one containing html and jquery code.
In order to submit form using jquery i've written this code
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#selectrefuser").val();
$.post("php-opt.php", //Required URL of the page on server
{ // Data Sending With Request To Server
selectrefuser:vname,
},
function(response,status){ // Required Callback Function
//alert("*----Received Data----*\n\nResponse : " + response+"\n\nStatus : " + status);//"response" receives - whatever written in echo of above PHP script.
});
php_lat = <?php echo $resclient_alt; ?>;
php_long = <?php echo $resclient_long; ?>;
var chicago = new google.maps.LatLng(parseFloat(php_lat), parseFloat(php_long));
addMarker(chicago);
//return false;
//e.preventDefault();
//$("#monbutton:hidden").trigger('click');
});
});
and my php code is :
<?php
$resclient_alt = 1;
$resclient_long = 1;
if(isset($_POST['selectrefuser'])){
$client = $_POST['selectrefuser'];
echo $client;
$client_valide = mysql_real_escape_string($client);
$dbprotect = mysql_connect("localhost", "root", "") ;
$query_alt= "SELECT altitude FROM importation_client WHERE nom_client='$client_valide' ";
$query_resclient1_alt=mysql_query($query_alt, $dbprotect);
$row_ss_alt = mysql_fetch_row($query_resclient1_alt);
$resclient_alt = $row_ss_alt[0];
//echo $resclient_alt;
$query_gps= "SELECT longitude FROM importation_client WHERE nom_client='$client_valide' ";
$query_resclient1=mysql_query($query_gps, $dbprotect);
$row_ss_ad = mysql_fetch_row($query_resclient1);
$resclient_long = $row_ss_ad[0];
}
?>
My form is as below
<form id="form1" name="form1" method="post" >
<label>
<select name="selectrefuser" id="selectrefuser">
<?php
$array1_refuser = array();
while (list($key,$value) = each($array_facture_client_refuser)) {
$array1_refuser[$key] = $value;
?>
<option value="0" selected="selected"></option>
<option value="<?php echo $value["client"];?>"> <?php echo $value["client"];?></option>
<?php
}
?>
</select>
</label>
<button id="btn">Send Data</button>
</form>
My code does these actions:
select client get its GPS coordinates
recuperates them in php variable
use them as jquery variable
display marquer on map
So since i do this steps for many clients i don't want my page to refresh.
When i add return false or e.preventDefault the marquer is not displayed, when i remove it the page refresh i can get my marquer but i'll lost it when selecting another client.
is there a way to do this ?
EDIT
I've tried using this code, php_query.php is my current page , but the page still refresh.
$("#btn").click(function(){
var vname = $("#selectrefuser").val();
var data = 'start_date=' + vname;
var update_div = $('#update_div');
$.ajax({
type: 'GET',
url: 'php_query.php',
data: data,
success:function(html){
update_div.html(html);
}
});
Edit
When adding e.preventDfault , this code doesn't seem to work
$( "#monbutton" ).click(function() {
php_lat = <?php echo $resclient_alt; ?>;
php_long = <?php echo $resclient_long; ?>;
$('#myResults').html("je suis "+php_long);
var chicago = new google.maps.LatLng(parseFloat(php_lat), parseFloat(php_long));
addMarker(chicago);
});
This code recuperate this value var vname = $("#selectrefuser").val(); get result from sql query and return it to jquery .
It will refresh since you have not prvent default action of <button> in script
$("#btn").click(function(e){ //pass event
e.preventDefault(); //this will prevent from refresh
var vname = $("#selectrefuser").val();
var data = 'start_date=' + vname;
var update_div = $('#update_div');
$.ajax({
type: 'GET',
url: 'php_query.php',
data: data,
success:function(html){
update_div.html(html);
}
});
Updated
Actually, i want my php code to be written on the same page as the one containing html and jquery code
You can detect the ajax call on php using below snippet
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/* special code here */
}
This is the first time i've used AJAX and PHP. I've written a simple login page (below). As you can see, Ajax will send the username to getLocations.php on blur, which i coded with the help of this site and youtube (i'm leaving out the db connect bit, but it's there):
<!doctype html>
<html>
<head><title>Fetch JSON array Data</title>
<script src="http://10.28.1.90/DC_CRM_HOME2_USER_RIGHTS/js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#username").blur(function() {
var sendu = $("#username").val();
$.ajax({
type: "POST",
url: "getLocations.php",
data: "username="+sendu,
success: function(response){
$("#result").html(locations+string+jqXHR);
//populate select with response...but how?
var locations = response.name;
for (var i in locations)
{
var vertical = locations[0];
$('select').append("<option value=\""+vertical+"\">"+vertical+"</option>");
}
}
});
});
});
</script>
</head>
<body>
<form method="post" action="#" onsubmit="return false;">
<input type="username" id="username" name="username" placeholder="username" value="" /><br><p>
<input type="password" id="password" name="password" /><br><p>
<select name="foo" id="foo">
<option></option>
</select><br><p>
<input type="submit" id="button" value="Login" />
</form>
</body>
</html>
getLocations.php:
$name = $_REQUEST['username']; //from ajax request
$query = "select LOCATION ";
$query .= "FROM dc_MASTER.DC_CNSLR_ACCESS dca ";
$query .= "JOIN dc.MEMBERS m ON dca.id = m.id ";
$query .= "AND m.EMAIL = '$name' ";
$Sresult = mysqli_query($mysqli, $query);
if( ! $Sresult) {
die("Database query failed: $Sresult");
}
$result = array();
while( $row = mysqli_fetch_array($Sresult) )
$list = array_push($result, array('name' => $row[0]));
$c = json_encode(array("result" => $result));
echo $c;
?>
At this point, my array is "loaded" and i'm able to see the response in firebug:
{"result":[{"name":"Chenal"},{"name":"Heights"}]}
However, i can't seem to get my select options populated. I feel like i'm making this harder than it should be (and i've been staring at it for quite a while). Thanks for the help guys.
You have to loop through the JSON returned by the PHP:
Demo: http://jsfiddle.net/L7a68y26/
var response = {"result":[{"name":"Chenal"},{"name":"Heights"}]}
var r = response.result;
for (var i in r)
{
$('select').append("<option value=\""+r[i].name+"\">"+r[i].name+"</option>");
}
In context:
$.ajax({
type: "POST",
url: "getLocations.php",
data: "username="+sendu,
// Added this so jQuery knows what kind of data is being returned
dataType: 'json',
success: function(response){
var r = response.result;
for (var i in r)
{
$('select').append("<option value=\""+r[i].name+"\">"+r[i].name+"</option>");
}
}
});
1) You haven't told jquery that you're expecting a json response back, so it'll just treat it as plain text.
$.post(
dataType: 'json' // <<--you need this
With that, jquery will automatically parse/decode the JSON into a native JS data structure
2) Then it's a simple matter of looping:
success: function(data) {
$.each(data, function(i, opt) {
$('select').blahblah + opt.name + blahblah
})
On the efficiency side of things, while it's sometimes a good idea to pass around data AS data, but if all you're going to be doing with the data is stuffing it into a form field, you might be better off just building the HTML on the server and passing that around directly.
I'm tring to send and receive parameters with AJAX without any sucess
First I choose AREA and than the CITIES in this area.
Can you please tell me what do I do wrong?
Client side:
<script>
$(document).ready(function(){
$("#first").click(
function(){
var area_id=$("#area_id").val();
$.ajax({
type: "POST",
url: "recs.php",
data: "area_id="+area_id,
cache:false,
success:
function(data){
$("#second").html(data.message);
}
});
return false;
});
});
</script>
<form method="post" action="tosomewhere.php">
<select id="first" name="area_id">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="second" name="section"> </select>
</form>
Server Side:
$areaID = $_POST['area_id'];
$second_option = "";
$query2 = mysql_query("SELECT * FROM `cities` WHERE area_id = $areaID ORDER BY id ASC");
while($index = mysql_fetch_array($query2))
{
$id = $index['id'];
$name = $index['name'];
$second_option .= "<option value='$id'>$name</option>";
}
echo $second_option;
exit;
Thank you in advanced
After editing:
I changed the code to something even simpler:
Client side:
<script>
$(document).ready(function(){
$("#first").click(
function(){
var area_id=$("#area_id").val();
$.ajax({
type: "GET",
url: "recs.php",
data: "area_id="+area_id,
cache:false,
success:
function(data){
$("#second").html(data);
}
});
return false;
});
});
</script>
<form method="post" action="tosomewhere.php">
<select id="first" name="area_id">
<option value="1">1</option>
<option value="2">2</option>
</select>
<div id="second"></div>
</form>
Server side:
some text
I'm still not getting the string into
change
$("#second").html(data.message);
to
$("#second").html(data);
<script>
$(document).ready(function(){
$("#first").click(function(){
var area_id=$("#area_id").val();
$("#second").load('tosomewhere.php?area_id=' + area_id);
return false;
});
});
</script>
Changed the jquery a bit. Using GET.
Also the script has changed:
$areaID = (int) $_GET['area_id'];
$second_option = "";
$query2 = mysql_query("SELECT * FROM `cities` WHERE area_id = '$areaID' ORDER BY id ASC");
if (mysql_num_rows($query2) > 0){
while($index = mysql_fetch_array($query2)){
$second_option .= '<option value="'.$index['id'].'">'.$index['name'].'</option>';
}
echo $second_option;
} else {
echo 'No result!';
}
die();
Added (int) before $_GET as a pre-security measurement.
Add this parameter to the ajax function
dataType:'text'
You need to debug code where is actually fault whether you ajax call is actually initialize.
i: check whether value properly fetch in "area_id" js variable
alert(area_id);
ii: if it ok check whether data proper returned from server scriptinog
alert(data); or alert(data.message);
iii: for testing whether you receive data properly, just send out test script.
echo "sample text";
exit;
or try to send data in json format
die('{"message" : "sample text"}');
If all three steps working, then there should be fault in data access script.
If you are not getting output in ajax try using firebug to check what is actually happening in sending request and getting response.