How to send data back in AJAX in response from PHP? - php

I want to make dynamic select options based on database values.
I am getting id when user select an option, I get this id in ajax and then this id is passed in PHP. In PHP I run SQL query based on provided id. Now I want to send response back in AJAX and then I will append my next select option with the given response.
This is my AJAX, from this code I am passing selected_val in PHP.
`
$(document).ready(function() {
$(".sdpt").change(function(){
let deptid = $(this).val();
console.log(deptid);
$.ajax({
method: "POST",
url: "joins.php",
data: { selected_val: deptid },
success: function(response){
console.log(response);
}
});
});
});
`
In PHP, I am getting data (pro_name) from database and adding it in an array. I want to return this array in ajax and then I will use it there. Now it is return the whole PHP code in response. Please guide where I am doing mistake and what is the alternative.
`
if (isset($_POST['selected_val']) ) {
$value = $_POST['selected_val'];
$myq = new Database();
$result = $myq->sql("SELECT * FROM programs where dept_id=$value");
$arr = array();
while($row = mysqli_fetch_assoc($result)){
$arr[] = $row['pro_name'];
};
echo json_decode("Google");
}
`

Related

Multiple AJAX calls - 1st to fetch data and turn into JSON object & 2nd to update $_SESSION info

I have an ajax call which pulls data from the table and then transforms into a JSON object
Because I am also doing a lot with PHP as well I need to have a 2nd AJAX call
immediately after the first that will update $_SESSION info
I have tried putting
$_SESSION['company_id'] = $_POST['companyid'];
in the same file that handles the 1st AJAX call but it then doesn't process the data from the first call, hence I need to do the 2nd call
Here is my jQuery Code for the 1st and 2nd AJAX query
$(".showcompinfo").click(function(){
$("#comptable").hide();
$("#showcomptable").show();
var id = $(this).attr('id');
$("#comp_info").toggle();
var companyid = id;
var dataString = "companyid="+companyid;
$.ajax({ /* THEN THE AJAX CALL */
type: "POST",
url: "../inc/dataforms/complist.php",
data: dataString,
success: function(result){
var jsonObject = JSON.parse(result);
// here you can do your magic
var approved = jsonObject.customer_approved;
$("#showcompname").text(jsonObject.name);
// Get Reg Address Details - Check if any field is empty
var regoffice_2 = '';
var regoffice_3 = '';
var regoffice_city = '';
console.log(jsonObject.regoffice_city);
if(jsonObject.regoffice_2)
{
regoffice_2 = ', ' + jsonObject.regoffice_2;
};
if(jsonObject.regoffice_3)
{
regoffice_3 = ', ' + jsonObject.regoffice_3;
};
if(jsonObject.regoffice_city)
{
var regoffice_city = ', ' + jsonObject.regoffice_city;
};
var addlne1 = jsonObject.regoffice_1;
var regaddress = jsonObject.regoffice_1 + regoffice_2 + regoffice_3 + regoffice_city;
$("#addline1").val(jsonObject.regoffice_1);
$("#addline2").val(jsonObject.regoffice_2);
$("#addline3").val(jsonObject.regoffice_3);
$("#addcity").val(jsonObject.regoffice_city);
$("#addcounty").val(jsonObject.regoffice_county);
$("#countryselected").val(jsonObject.regoffice_country);
$("#countryselected").text(jsonObject.regoffice_country);
$("#addpostcode").val(jsonObject.regoffice_postcode);
console.log(regaddress);
if(approved == '1')
{
$("#approvedcust").text('Yes');
} else {
$("#approvedcust").text('Customer but Not Approved');
};
}
});
// 2nd Ajax
var companyid2 = jsonObject.company_id;
var dataString2 = "companyid="+companyid2;
$.ajax({ /* THEN THE AJAX CALL */
type: "POST",
url: "../inc/updatesession.php",
data: dataString2,
success: function(){
}
});
//
Here is the PHP code for complist.php
if(!empty($_POST['companyid']))
{
$companyid = $_POST['companyid'];
$query = mysqli_query($dbc,"SELECT * FROM `comp_companies` WHERE `company_id` = '$companyid'");
$result = mysqli_fetch_assoc($query);
if($result){
$newdata = json_encode($result);
}
}
print_r($newdata);
If anyone can help even consolidate this into 1 ajax query or help me get 2 calls
working correctly it would be much appreciated
** EDIT **
OK I now have it displaying the Company ID in the session variable however when the user clicks to view a different company info result the session company_id does not update
I have changed the complist.php to the following
if(!empty($_POST['companyid']))
{
unset($_SESSION['company_id']);
$companyid = $_POST['companyid'];
$query = mysqli_query($dbc,"SELECT * FROM `comp_companies` WHERE `company_id` = '$companyid'");
$result = mysqli_fetch_assoc($query);
if($result){
$_SESSION['company_id'] = $_POST['companyid'];
$newdata = json_encode($result);
}
}
print_r($newdata);
My thinking behind the above was that once the ajax call is made it immediately unsets the session variable company info
then once a result is found for the selected company it resets the session var company_id with the new value, however its not updating the session variable
Screenshots showing what I mean
Your code updates your session variable successfully. However, since you're making an AJAX call, only the code in the PHP script directly called by the AJAX ("complist.php" in this case) is executed on the server. None of the PHP code which originally used to create your page is run again - this is why you have to use JavaScript to populate the rest of your newly selected company details.
To update the ID on screen following the AJAX call, all you need to do is follow the pattern you've used to update the rest of the fields
Change your HTML so the element which contains the company ID has an ID which lets JavaScript identify it:
<span id="showcompname"></span><span id="showcompid"><?php echo $_SESSION['company_id'];?></span>
and then in the "success" callback of your AJAX code, write
$("#showcompid").text(jsonObject.company_id);
This is exactly the same concept as the other JavaScript code you've got e.g. to update the "showcompname" element.
Meanwhile, the value stored in your PHP session will be used next time you run the PHP code which updates the whole page (e.g. by refreshing the page).

Ajax returning all database records instead of queried results

I am working on a search box in PHP that will get results from a database. Since I want the search to be live, I'm using an Ajax script to get the results.
This is the javascript:
$(function() {
$('#search').keyup(function() {
var txt = $(this).val();
if (txt != '' && txt.length >= 6) {
$.ajax({
method: 'POST',
url: '{{ path_for('search.post') }}',
success: function(data) {
console.log(data);// Do stuff with data.
}
});
} else {
$('#search_results').html('');
}
});
});
path_for('search.post') calls a PHP function (using Slim 3). This function is:
$queryString = "SELECT displayName
FROM guests
INNER JOIN shows ON guests.showId = shows.showId
WHERE (displayName LIKE :search OR talk_title LIKE :search) AND shows.active = 1 AND guests.active = 1
ORDER BY gLastName";
$searchQuery = $this->c->db->prepare($queryString);
$searchText = '%'.$request->getParam('search').'%';
$searchQuery->bindValue(':search', $searchText, PDO::PARAM_STR);
$searchQuery->execute();
$results = $searchQuery->fetchAll(PDO::FETCH_ASSOC);
$jsonResults = json_encode($results);
echo $jsonResults;
If I run the PHP directly, I get a json string with the record(s) I searched for (usually one or two depending on what I search). However, if I let the Ajax run, I get back every single record in the database. I don't understand why this is.
If have tested that the ajax is calling the right PHP by changing to echo 'yes'. When I did this, I received the string 'yes' back.
Is there something I need to change in the Ajax call?
I just realised what the error is.
$request->getParam('search') only works when I run the PHP directly, but not with Ajax since the parameter is not being posted.
Once I changed the ajax call to this:
$.ajax({
method: 'POST',
url: '{{ path_for('search.post') }}',
data: {search:txt},
dataType: 'text',
success: function(data) {
console.log(data);// Do stuff with data.
}
});
it worked.

How to split data while loop data in php and pass to ajax html with different id's

I have db table of doctors nearly more than 100 doctors list in it, Here is my PHP code for doctors dc.php :
$conn= mysqli_connect('localhost', 'root', '', 'test');
$query = mysqli_query($conn, "select * from doctors");
while($result=mysqli_fetch_array($query)){
$dc_name = $result['name'];
$dc_img = $result['image'];
$dc_email = $result['email'];
echo $dc_name."||".$dc_img."||".$dc_email;
}
I want echo all doctors another main page index which already fixed large layout with bootstrap,html,css by using ajax calling on click
Here is my code for ajax
$(function(){
$(".divscrolla").on("click", function(){
$.ajax({
url:'db.php',
type:'POST',
data:{"data":$(this).val()},
success:function(data){
var splitted = data.split("||");
$("#result_name").html.splitted[0];
$("#result_img").html.splitted[1];
$("#result_email").html.splitted[2];
}
});
});
Here I want display all 100 records by AJAX
But here I am getting only first element only, but I have more 100 records in database.
How can I solve by simplifying this?
Did you try
$resultArray = $result->fetch_all(MYSQLI_ASSOC);
$jsonstring = json_encode($resultArray);
echo $jsonstring;
And then in the AJAX code don't split, let the json format help you. By setting the data type to json dataType: "json",
$(function(){
$(".divscrolla").on("click", function(){
$.ajax({
dataType : "json",
url:'db.php',
type:'POST',
data:{"data":$(this).val()},
success:function(data){
//consume the data in a assoc array manner
//data[0]['name'] for first entry's name
}
});
});
}

Increment MySQL value on click with +1

What I have
An url like this: http://localhost:8888/website/?key=ABC
A MySQL table with many rows, one with a key called ABC. I have a button that I want users to click (upvote) the MySQL row corresponding to key=ABC.
In my scripts.js I have this (incomplete?) Ajax code:
function increment() {
$.ajax({
type: 'POST',
url: '../js/ajax.php',
success: function(data) {
alert("function saved: " + data);
}
});
}
And my ajax.php looks like this:
<?php
if (isset($_GET['key']) {
$rowKEYtest = $_GET['key'];
$sql2 = "UPDATE database SET Score = Score + 1 WHERE UniqueKey = '$rowKEYtest'";
$conn->query($sql2);
} else {
echo "lol";
}
?>
It's not updating. I have no idea what to do.
Please have a look in your code, There is 2 mistakes.
1. In your ajax call you are using type: 'POST', you should use GET.
2. You are nor parsing your 'key' param in ajax call.
Actually you are using POST method in ajax but in ajax.php trying to get the value with GET method. second thing you are not passing any param in ajax call.
Hope this will help.

jquery ajax don't get more than one value from php script

I try to use jQuery ajax call to retrive some data via php script.
Script take from mysql table all values of column 'rezhour' what also based on $_GET variable.
Then he print all finded values via json_encode() function
PHP:
<?php
header('Content-type: application/json');
$fromdate = $_GET['fromdate'];
$getrezhiredh = mysql_query("
SELECT rezhour FROM rezhiredhours
WHERE rezdate = '".$fromdate."' ORDER BY rezhour
");
$i=0;
$data = array();
while($row = mysql_fetch_array($getrezhiredh)){
$data['hours'][$i] = $row['rezhour'];
$i++;
}
$result = array(
$data
);
print json_encode($result);
?>
When script is called from browser adress bar all is fine and in we have correct result as below:
[{"hours":["2","9","13","14"]}]
Each digit in result above corresponds selected table row.
The problem is when i want to do the same via ajax.
jQuery:
<script>
var date = jQuery('input').val()
jQuery.ajax({
type: "GET",
dataType: "html",
data: "fromdate="+date,
url: "script.php",
success: function (data) {
console.log(data);
},
});
</script>
Now all is fine only when mysql query return result with one row and this looks in console like this:
[{"hours":["1"]}]
When mysql query return result with more than one row console show this:
[[]]
For me is really weird that jquery ajax call have problem to print correct result when we have more than one rows with selected data.
What i must do to have the same result in AJAX?
EDIT:
I found an important clue. The problem is WHERE clause in MYSQL query. When u remove from query this clause, php script return data from entire table and now ajax can print into console all selected values from specifed column.
The problem is i must use WHERE clause to load only data from before selected date at the website. Any idea how to do this?
If you want to return json data ,must use dataType:json. Valid data format is data :{key:value},...
var date = jQuery('input').val();
jQuery.ajax({
type: "GET",
dataType: "json",
data: {fromdate : date },
url: "script.php",
success: function (data) {
console.log(data);
},
});

Categories