I am trying to send a post to a php script which will collect all the account information from the database using this...
var e = document.getElementById("lstAccounts");
var accountID = e.options[e.selectedIndex].value;
alert("Account ID:"+accountID);
$.post("php/getAccount.php", {ID: accountID}, function(data)
{
var accountInfo = data;
});
This posts into this...
<?php
$id = $_POST['ID'];
include('database_api.php');
$db = new DatabaseControl;
$db->open_connection();
$result = $db->db_query("SELECT * FROM tblAccount WHERE ID=$id");
$account_info = array();
//Get Basic Information
while($row = mysqli_fetch_array($result))
{
$account_info['Name'] = $row['Name'];
$account_info['CRN'] = $row['CRN'];
$account_info['ID'] = $row['ID'];
$account_info['Type'] = $row['Type'];
$account_info['Revenue'] = $row['Revenue'];
$account_info['Industry'] = $row['Industry'];
$account_info['Description'] = $row['Description'];
$account_info['Employees'] = $row['NoOfEmployees'];
$account_info['Billing'] = $row['BillingAddress'];
$account_info['Shipping'] = $row['ShippingAddress'];
}
//Get Details
$result = $db->db_query("SELECT tblDetails.ID, tblDetails.Label, tblDetails.Value FROM tblAccountDetails
INNER JOIN tblDetails ON tblDetails.ID = tblAccountDetails.DetailID
WHERE AccountID=$id");
//Get Basic Information
while($row = mysqli_fetch_array($result))
{
$account_info['Detail'.$row['ID']]['Label'] = $row['Label'];
$account_info['Detail'.$row['ID']]['Value'] = $row['Value'];
}
//Get Contact Information
//Get Invoices
//Get Payments
//Get Notes
//Get To-Do
//Events
//Send back to javascript
echo json_encode($account_info);
?>
I need the echoed json_encode to enter a javascript on the return data. How do I get that data into an array?
$.post("php/getAccount.php", {ID: accountID}, function(data)
{
//In here how do I decode data into a javascript array
});
The data is set at "{"Name":"A business name","CRN":null,"ID":"17","Type":"User","Revenue":null,"Industry":"Software & Internet","Description":null,"Employees":null,"Billing":"An Address","Shipping":"An Address","Detail75":{"Label":"Phone","Value":"a phone number"},"Detail76":{"Label":"Email","Value":"an email address"}}" on return
pass in json_encode()'ed data from your php, like:
...
while($row = mysqli_fetch_array($result))
{
$account_info['Detail'.$row['ID']]['Label'] = $row['Label'];
$account_info['Detail'.$row['ID']]['Value'] = $row['Value'];
}
echo json_encode($account_info);
in js part:
$.post("php/getAccount.php", {ID: accountID}, function(data) {
//parse the json response
var response = jQuery.parseJSON(data);
console.log(response); //you can use $.each to iterate the data
});
First Set the datatype as JSON
$.post("php/getAccount.php", {ID: accountID}, function(data)
{
// Confirm Response
console.log(data);
$.each(data, function(i, e){
console.log(e);
});
}, 'json');
Related
I am posting the PHP file (post.php) through jquery ajax. And I want to get the data from it in the form of a javascript variable. I successfully get the data in my console. But I don't know how can I use this variable. You can see my code below.
$.post(
"post.php",
{
region: region,
district: district
},
function(data) {
console.log(data);
}
);
my post.php page looks like this
#include('../../_partials/_dbConnect.php');
$region = $_POST['region'];
$district = $_POST['district'];
$sql = "SELECT * FROM table1 WHERE name_rg= '".$region."'";
$result = pg_query($db_connection, $sql);
while ($row = pg_fetch_row($result)) {
$cols = array($row[0],$row[1],$row[2],$row[3],$row[4],$row[5],$row[6],$row[7],$row[8],$row[9],$row[10],$row[11],$row[12],$row[13],$row[14],$row[15],$row[16],$row[17],$row[18],$row[19],$row[20],$row[21]);
}
<script>
var cols = [<?php echo '"'.implode('","', $cols).'"' ?>];
</script>
And the console.log(data) output like this,
<script>
var cols = ["94","32","361","0","118","159","0","243","702","1775","8","0","2","0","150","135","381","2","0","0","0","0"];
</script>
Your help is highly appreciated.
In your post.php, you can simply echo the array and jQuery should automatically convert it to an array as the response
// post.php
<?php
#include('../../_partials/_dbConnect.php');
$region = $_POST['region'];
$district = $_POST['district'];
$sql = "SELECT * FROM table1 WHERE name_rg= '".$region."'";
$result = pg_query($db_connection, $sql);
while ($row = pg_fetch_row($result)) {
$cols = array($row[0],$row[1],$row[2],$row[3],$row[4],$row[5],$row[6],$row[7],$row[8],$row[9],$row[10],$row[11],$row[12],$row[13],$row[14],$row[15],$row[16],$row[17],$row[18],$row[19],$row[20],$row[21]);
}
echo json_encode($cols);
?>
// Somewhere in your js
$.post(
"post.php",
{
region: region,
district: district
},
function(data) {
console.log(data[0]);
}
);
in javascript use JSON.parse()
$.post(
"post.php",
{
region: region,
district: district
},
function(data) {
data=JSON.parse(data);
}
);```
And here you go, u can play with it as you need
Happy learning!
when one record then show data when multiple record come then not show data other site.
ajaxx.php
<?php
include 'database.php';
session_start();
$post = $_POST;
$search = $post['search'];
$searchType = $post['searchType'];
if ($searchType == 'all')
{$sql = "SELECT DISTINCT title FROM hadees WHERE title LIKE '$search%' AND (type='Bukhari' OR type='Muslim') ";}
else
{$sql = "SELECT DISTINCT title FROM hadees WHERE title LIKE '$search%' AND type='$searchType' ";}
$result = mysqli_query($db,$sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$row['title'];
echo json_encode($row);
}
} else
{ echo "Not Found Result" ; }
?>
when data record is one then append the data successfully when multiple record come then not show data and append not work
javascript code
function searchh()
{
var type = $("input[name='type']:checked").val();
var searchhh = $( ".myButton option:selected" ).text();
debugger;
$.ajax({
url: 'ajaxx.php',
type: "POST",
data: {'searchType':type, 'search':searchhh},
success: function (data) {
var duce = jQuery.parseJSON(data);
alert(duce.title);
}
});
}
I think your issue is in the while loop. You don't want to encode each row one-by-one, but as a whole like this.
$myResults = [];
while($row = $result->fetch_assoc()) {
$row['title'];
$myResults[] = $row;
}
echo json_encode($myResults);
You are producing invalid JSON by using echo json_encode($row); within a loop.
Try to craft an array of rows, and then display it.
if($result->num_rows > 0)
{
$output = array();
while($row = $result->fetch_assoc())
{
output[] = $row;
}
if($searchType == 'all')
{
echo json_encode($output);
}
else
{
echo json_encode(current($output)); // print just one
}
}
I have a text field in which i am getting a string like that
say name / contact / address
and i get this value on button click function when i pass this value to php function via ajax. it returns nothing, i don't know what is wrong with my code.
here is the ajax function:
$("#load").click(function()
{
//alert("this comes in this");
var data1 = $("#country_id").val();
$.ajax({
alert("ajax start");
url: 'ajax_submit.php',
type: 'Post',
dataType: 'json',
data:{getRespondents:"getRespondents", data:data1},
success: function(e){
alert(e);
$("#rCategory").val(e.respondents[0]['category']);
$("#gender").val(e.respondents[0]['gender']);
$("#rAddress").val(e.respondents[0]['address']);
$("#rContact").val(e.respondents[0]['contact']);
alert("In this");
}
});
});
and in ajax_submit.php function is like that:
if($_POST["getRespondents"] == "getRespondents"){
$regionID= $_POST["data"];
$obj = new controller();
$result = $obj->getRespondents($regionID);
$json = array("respondents"=>$result);
echo json_encode($json);
exit();
}
In class function is written as:
function getRespondents($a){
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("demon", $connection); // Selecting Database
list($number1, $number2, $number3) = explode('/', $a);
//$sql = "SELECT r.id, r.name, r.contact, r.address from respondent as r ORDER BY r.name";
$sql = "SELECT * FROM respondent as r WHERE r.name = '".$number1."' and r.contact = '".$number2."' and r.address = '".$number3."' "
$rsd = mysql_query($sql);
$row= array();
$i=0;
while($rs = mysql_fetch_array($rsd)) {
$row[$i]["id"] = $rs ['id'];
$row[$i]["name"] = $rs ['name'];
$row[$i]["contact"] = $rs ['contact'];
$row[$i]["address"] = $rs ['address'];
$row[$i]["category"] = $rs ['category'];
$row[$i]["gender"] = $rs ['gender'];
$i++;
}
return $row;
}
I want to populate those values in given select boxes when user selects something from autocomplete function.
what are possible soultions to this problem? thanks
First of all why you use alert at the beginning of ajax? remove that alert because it might give you JavaScript error.
Hi I am developing an app in phonegap, where I am getting a particular value from server by connecting php file the value I need to pass is a string value 'pmnno'suppose whose value is '2' I need to get the value of '2' in column name 'personalnumber'.. So I am giving my code below
var jsonData;
$.ajax({
type: 'GET',
url: 'http://xxxx.com/app/get_pday1_number.php',
data: { pmnno: '2' },
dataType: 'html',
success: function (response) {
jsonData = response;
alert(jsonData);
}
});
php code
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["pone"]))
{
$pone = $_GET['pone'];
// get a product from products table
$result = mysql_query("SELECT *FROM pdaynew WHERE pone = $pone");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["pone"] = $result["pone"];
$product["personaldayone"] = $result["personaldayone"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
I am getting a success mesage that means connection is succesful but ineed the value of '2' in column 'personalnumber' for that where I need to add that code..If anyone knows pls help me...
Instead of using * use personaldayone:
$result = mysql_query("SELECT personaldayone FROM pdaynew WHERE pone = $pone");
My PHP web page is returning a JSON string. I wrote following function to get those data and display them on jQuery mobile listview.
function LoadJsonDataFunction()
{
$.getJSON("my_web_page.php", function(obj) {
$.each(obj, function(key, value){
$("ul").append("<li>"+value.fname+"</li>");
});
});
}
Here is my listview code:
<ul data-role=listview> </ul>
I have called to the function in the body tag
<body onload="LoadJsonDataFunction()">
but when I executing the program it displays "undefine" and no data.
then I change $.getJSON() request like this.then its working perfectly.
$.getJSON("some_page_returning_same_json_string.json",function(obj) { .....
let me know how can i fix this.
PS. Here is my php page output..
{
"employees":[
{
"fname": "sdsdsd",
"lname": "sdsd",
"phone": "sdsd",
"gender": "female",
"dob": "1990-03-11",
"address": "03",
"nic": "erer",
"email": "erererer",
"empid": "ererere",
"designation": "sdsds",
"qualifications": "dsds"
}
]
}
Here is my php code
<?php
header('Content-Type: application/json');
/*
Following code will list all the employees
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all employees from employees table
$result = mysql_query("SELECT * FROM emp_master") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// employees node
$response["employees"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$employee = array();
$employee["fname"] = $row["fname"];
$employee["lname"] = $row["lname"];
$employee["phone"] = $row["phone"];
$employee["gender"] = $row["gender"];
$employee["dob"] = $row["dob"];
$employee["address"] = $row["address"];
$employee["nic"] = $row["nic"];
$employee["email"] = $row["email"];
$employee["empid"] = $row["empid"];
$employee["designation"] = $row["designation"];
$employee["qualifications"] = $row["qualifications"];
//push single employee into final response array
array_push($response["employees"], $employee);
}
// success
// $response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no employees found
$response["success"] = 0;
$response["message"] = "No employees found";
// echo no users JSON
echo json_encode($response);
}
?>
Have you write correct header? If not write this as first line in your PHP:
header('Content-Type: application/json');
Change the line:
$.each(obj, function(key, value){
with
$.each(obj.employees, function(key, value){
The "employees" contains in "obj" and then it contains the array. "obj" does not contain the array you are looking.
This is the best exemple i used to begin JQM , you can check the link or use the code below
$('#ListPage').bind('pageinit', function(event) {
$.getJSON('some_php_or_json_file_link', function(data) {
$('#listView li').remove();
$.each(data.items, function(index, item) {
$('#listView').append('<li><span>' + item.json_label1 + '</span></li>');
});
$('#listView').listview('refresh');
});
});