Better approach for displaying two PHP variable switch jQuery Ajax - php

I'm getting two random values from a table. The values are in the same row.
<?php
$result = mysql_query("SELECT * FROM people ORDER BY RAND() LIMIT 1", $connection);
$row = mysql_fetch_array($result);
echo $row["name"];
echo $row["surname"];
?>
And I want to display these two values at different div's on my HTML page by using jQuery Ajax functions.
$(function()
{
$("#sentence-form").submit(function()
{
$.ajax(
{
type: "GET",
url: "newperson.php",
success: function(response)
{
$("#top-container").append(response); /* Both name and surname */
}
});
});
});
The problem is separating two values to display different in div's. I tried to use two Ajax calls and I send boolean data to PHP to use with an if statement. So one of the Ajax calls displays name and the other one displays surname. But because of randomization, it's a bit complicated to find surname of a name.
What is a better approach?

Yes: send the data in a data structure – probably JSON – so your client-side code knows which bit is which.
First, send the data with PHP's json_encode function:
echo json_encode(array(
'name' => $row['name'],
'surname' => $row['surname']
));
Then use your browser's ability to parse JSON:
$.ajax({
type: "GET",
url: "newperson.php",
dataType: 'json',
success: function (response) {
$("#name-container").append(response.name);
$("#surname-container").append(response.surname);
}
});
response is now a Javascript object (something like {name: 'John', surname: 'Smith'}), so you can access the two parts as normal object members.

Send the variables as a JSON array
<?php
$result = mysql_query("SELECT * FROM people ORDER BY RAND() LIMIT 1", $connection);
$row = mysql_fetch_array($result);
$output['name'] = $row["name"];
$output['surname'] = $row["surname"];
echo json_encode($output);
?>
And on the JavaScript code, access it as:
data.name and data.surname

Although I like lonesomeday's answer, and I think that that is the way to go, I will post the alternative:
Relevant PHP:
echo $row["name"].'||'.$row["surname"];
Relevant JavaScript code:
success: function (response) {
var parts = response.split('||');
$("#name-container").append(parts[0]); //name
$("#surname-container").append(parts[1]); //surname
}

Use this:
<?php
$result = mysql_query("SELECT * FROM people ORDER BY RAND() LIMIT 1", $connection);
$row = mysql_fetch_array($result);
echo $row["name"]."&".$row["surname"];
?>
$(function(){
$("#sentence-form").submit(function(){
$.ajax({
type : "GET",
url : "newperson.php",
success : function(response){
items=response.split('&')
$("#top-container").append(items[0]); /* name */
$('#bottom-container").append(items[1]); / /*s(u should be i)rname */
}
});
});
});

Related

How to send data back in AJAX in response from 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");
}
`

How to write this query with this id?

How can I add this data-id in query line
<li><a data-id="<?php echo $random_id;?>">Show</a></li>
In my case I can not add $random_id here. I have to use the data-id.
simply I need to select from posts where id is equal to data-id.
How can I write it down ?
$query = "select * from posts where id='???' ";
You cannot get this data-id attribute value in your php code directly. You have to use Jquery, Ajax to use this like:
var dataId = $('a').attr('data-id');
or
var dataId = $('a').data('id');
Now make an ajax() call and pass this value as an parameter in that call.
In order for you to make this happen - I believe - you have to use AJAX.
The code will look like this:
$.ajax({
url: 'your_script.php',
type: 'POST',
data: {var1: javascript_var_1, var2: javascript_var_2},
success: function(data) {
console.log("success");
}
});
Your PHP will look similar to this (without keeping in mind the JSON encode:
<?php
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$getvalue="SELECT id,name from table1 WHERE column1='$var1' and column2='$var2'";
$result=mysql_query($getvalue) or die(mysql_error());
while($row=mysql_fetch_array($result)){
extract($row);
echo $name;
}
?>
Then you can JSON encode the results and pretty much output them on the success. Your php script - however - must live on another php file.
Also, escape your data. Use prepared statements.

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
}
});
});
}

How can I use the data I get from my database using MySQLi, in Bootstrap typeahead?

I'm using jQuery ajax + MySQLi's prepared statements to get data from my database. The problem is that I don't know how to exactly format the data to use in Bootstrap's typeahead plugin.
This is the relevant code:
PHP:
$stmt = $mysqli->prepare("SELECT GAME_NAME FROM GAMES WHERE GAME_NAME LIKE ?");
$query = "%".$query."%";
$stmt->bind_param('s',$query);
$stmt->execute();
$stmt->store_result();
$count = $stmt->num_rows;
if($count > 0) {
$stmt->bind_result($result);
while($stmt->fetch()) {
echo json_encode($result);
}
What I get as AJAX response is all the names as a bunch of text:
'"game 1""game 2""blaablaa""some other game"....'
I think I have to have an array of names and I don't know how to get the stmt result as an array. The example I tried and works is (I use the array allCities as data-source):
<script type="text/javascript">
$(document).ready(function() {
var allCities = ['Baltimore', 'Boston', 'New York', 'Tampa Bay', 'Toronto', 'Chicago', 'Cleveland', 'Detroit', 'Kansas City', 'Minnesota', 'Los Angeles', 'Oakland', 'Seattle', 'Texas'].sort();
$('#city').typeahead({source: allCities, items:5});
});
</script>
Now if I only could get result in the same format as in the example, my problem should be solved, I think. Btw, I'm not sure about the json_encode() I used in the code. That's just something I gave a try. I appreciate any help. Thanks.
UPDATE, Ajax:
function handleSearch() {
var query = $.trim($('#search-field').val());
var itm = getSearchItem();
$.ajax({
type: "POST",
url: "..//functions/handleSearch.php",
dataType: "json",
data: "query="+query+"&itm="+itm,
success: function(resp) {
console.log("Server said (response):\n '" + resp + "'");
$('#search-field').typeahead({source: resp});
},
error: function(e) {
console.log("Server said (error):\n '" + e + "'");
}
});
another update:
In Network tab the response gives the result I want but in this format: Resistance: Fall of ManResident Evil 4John Woo Presents StrangleholdAge of Empires II: The Age of KingsResident Evil 2. So without any formatting. Console.log(resp) gives me nothing though. Although when I search for "resident evil 6", that means when I type in the EXACT NAME, console.log also works.
Basically you should create key=>value store array and then in the end you should output it with json_encode. What you are doing wrong in your code is you are trying to echo and json_encode on every result which should be done just in the end.
post the code that initializes ajax request.
For example this is shorthand for jquery ajax function
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
if data type specified json then callback function will receive an array like allCities in your example then you can pass it to your plugin. For example pseudo code:
$.ajax({
url: 'http://blabla',
dataType: 'json',
data: dataArray,
success: function(response) {
$('#city').typeahead({source: response, items:response.count()});
}
});

one JSON call returned with many?

My question is... How to make json have 1 call back with several objects.
I will use this example of 3 values to be returned... Here is the calclickM.php file, but I can not understand why it is not woking...
<?php
$choice = (isset($_POST['choice'])) ? date("Y-m-d",strtotime($_POST['choice'])) : date("Y-m-d");
$con = mysql_connect("localhost","root","xxxxxx");
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("inverters", $con);
$sql = "SELECT sum(power/1000) AS choice FROM feed WHERE date = '".$choice."' group by date"; $res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error());
$row = mysql_fetch_assoc($res);
$dayPowerP = array ('dayPowerP');
?>
<?php
$choice = (isset($_POST['choice'])) ? date("m",strtotime($_POST['choice'])) : date("m"); $con = mysql_connect("localhost","root","xxxxxx");
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("inverters", $con);
$sql = "SELECT sum(power/1000) AS choice FROM feed WHERE month(date) = '".$choice."'";
$res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error());
$row = mysql_fetch_assoc($res);
$monthPowerP = array ('monthPowerP');
?>
<?php
$choice = (isset($_POST['choice'])) ? date("Y",strtotime($_POST['choice'])) : date("Y"); $con = mysql_connect("localhost","root","xxxxxx");
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("inverters", $con);
$sql = "SELECT sum(power/1000) AS choice FROM feed WHERE year(date) = '".$choice."'";
$res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error());
$row = mysql_fetch_assoc($res);
$yearPowerP = array ('yearPowerP');
?>
<?php
$outarr['dayPowerP'] = $dayPowerP;
$outarr['monthPowerP'] = $monthPowerP;
$outarr['yearPowerP'] = $yearPowerP;
echo json_encode($outarr);
?>
Here is the Jquery I am using to post and the json
<script type="text/javascript">
$(document).ready(function () {
$('#datepicker').datepicker({maxDate: 0, dateFormat: 'yy-mm-dd', onSelect: function(dateText) {
var myDate = $(this).datepicker('getDate');
$('#apDiv1').html($.datepicker.formatDate('DD, d', myDate));
$('#apDiv5').html($.datepicker.formatDate('MM', myDate));
$('#apDiv7').html($.datepicker.formatDate('yy', myDate));
$.ajax({
type: "POST",
url: "calclickM.php",
data: {choice: dateText},
dataType: "json",
success: function(json_data) {
$('#apDiv2').html(json_data['dayPowerP']);
$('#apDiv6').html(json_data['monthPowerP']);
$('#apDiv8').html(json_data['yearPowerP']);
}
})
}});
});
Thanks,
Alan
At first the load method you are calling is making an AJAX GET request to your server. You probably support both POST and GET requests in your PHP script.
Secondly you have some errors in the your $.ajax calls. There are some unterminated strings, the data variable you are using as ('#apDiv9').html(data) isn't defined and if it was, it will be probably contain JSON data that you can't directly put in an HTML element.
Last, but not least, the second attempt won't make your code faster. A browser can only support a limited number of parallel ajax requests (1-2). You are still making the same number of requests and some of them need to wait for the others to complete. Re-design your code so that you return everything in a single call.
Not a solution to your immediate problem, but your code needs some serious refactoring. The level of repetition here hurts my eyes. The second code block, the one with the ajax-calls, could be changed to something like this:
var pages = [
{ url: "dayPower.php", div: "#apDiv4" },
{ url: "dayGraph", div: "#apDiv2" },
{ url: "monthPower.php", div: "#apDiv6" },
{ url: "monthGraph", div: "#apDiv9" },
{ url: "yearPower.php", div: "#apDiv8" },
{ url: "yearPower", div: "#apDiv10" }
};
for ( var i=0; i<pages.length; i++ ) {
$.ajax({
type: "POST",
url: pages[i].url,
data: { choice: dateText},
dataType: "json",
success: function(json_data )
(pages[i].div).html(data).show(); // Did you mean json_data here?
}
});
}
The case is similar with the first piece of code in your question.
Once again, I know it won't solve the actual problem, but it will make it easier to implement the solution when you (or someone else) finds it.
EDIT
On second thought, I can see at least one strange thing: in the success-function you call the parameter json_data, but you access a variable that you've called data. Did you intend to name them the same thing?
There is a way to do what you are asking, but you will need to handle the results yourself. Essentially all your Ajax calls have the same parameters, but different resultsets. So first, the client side code that does the magic:
$.post('datePacked.php', {choice: dateText}, function(data) {
$('#apDiv2').html(data['dayPower']);
$('#apDiv4').html(data['dayGraph']);
$('#apDiv6').html(data['monthPower']);
$('#apDiv9').html(data['monthGraph']);
$('#apDiv8').html(data['yearPower']);
$('#apDiv10').html(data['yearGraph']);
});
If you refactored your HTML so taht you actually match the div Ids with the result of your JSon response, you can simplify the call even further:
$.post('datePacked.php', {choice: dateText}, function(data) {
$.each(data, function(id, value) {
$('#'+id).html(value);
});
});
On the server side your new datePacked.php needs to return a JSON result that provides a hash of names to content. Essentially it will look something like this:
{ "dayPower" : "<p>My Content</p>", "dayGraph" : "<p>Day graph</p>", ... }
The ellipsis is there for you to fill in the remainder of the content. Choosing meaningful id names for your HTML elements is not only good practice, it can save you a lot of repitition if you take advantage of it. An example of that would be the second form of the client example. This is a case where the content has to be JSON for it to work--unless you want to split up a DOM returned by the server.
I’m not exactly sure what you’re asking, but here’s a couple of points:
$('#apDiv2').load('dayPower.php', {choice: dateText} does the same thing as $.ajax({type: "POST", url: "dayPower.php", data: { choice: dateText}. Both $.ajax and $.load make HTTP requests via JavaScript, which is what “AJAX” means.
Your second block of example code has some basic syntax errors. Here’s the first $.ajax call corrected:
$.ajax({
type: "POST",
url: "dayPower.php",
data: { choice: dateText},
dataType: "json",
success: function(json_data ) { // “{” added to start the function block
('#apDiv2').html(data).show();
}
}) // “})” added to end the object literal and function call
if you never need call any of this separately, why not just make one ajax call to a php file, package all your data into a multidimensional array, convert to json, and send back to the client.
Once you have this json, you can then break it up with js and figure out what goes where on your front end.
Depending on how much data you're getting it may take a while. If it's a huge query, then breaking it up into several little calls be actually be better. Its asynchronous so at least parts of your page will be loading. while other parts are gathering data.

Categories