Kindly help me with the ajax / jQuery to fetch all the objects of a array.
I am using the following code and it doesn't work
$(window).on("load", GetAllProperties);
function GetAllProperties() {
$.ajax({
url: 'userdetailfetch.php', //the script to call to get data
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
$('#ph').html(data[0]);
$('#email').html(data[1]);
$('#name').html(data[2]);
$('#fname').html(data[3]);
$('#date').html(data[4]);
$('#course').html(data[5]);
$('#branch').html(data[6]);
$('#sem').html(data[7]);
$('#roll').html(data[8]);
}
});
}
fetchuserdetail.php
<?php
$cnx = mysqli_connect("localhost", "root", "", "loginerp");
$result = mysqli_query($cnx, "SELECT * FROM user_info WHERE id='" . $_SESSION['sessuser'] . "'");
$data = array();
while($row = mysqli_fetch_array($result)) {
$data[] =$row;
}
echo json_encode($data);
?>
I want to display all the details when the page loads .
Thanks for your help.
Start session in fetchuserdetail.php file
session_start();
Correct the page name
url: 'fetchuserdetail.php',
Related
I created a form with two selects and my idea was when the first select is changed, a query is made to the database and the second select is updated with new information.
Since is the first time I'm doing this kind of things, I tried insert some data from that query in a H3 tag instead of using a select tag, but something is not working... The H3 tag starts empty and after changing the select box, the H3 tag remains empty.
This is my code:
<script>
$(document).ready(function(){
$("#show-form-button").click(function(){
$("#show-form-button").hide();
$("#bot-form").show();
});
$("#distrito").on('change', function() {
var selected = $(this).val();
makeAjaxRequest(selected);
});
});
function insertResults(json){
alert("cenas");
$("#teste").val(json["nome"]);
}
function makeAjaxRequest(placeID){
$.ajax({
type: "POST",
data: {placeId: placeID},
dataType: "json",
url: "http://localhost/Paulo%20Cristo%20LDA/insert.php",
success: function(json) {
insertResults(json);
}
});
}
</script>
And this is my PHP script:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "paulocristo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$placeId = $_GET["placeId"];
$query = "SELECT nome from local WHERE id =".$placeId ." AND tipo=0";
$result = $conn -> query($query) or die("Query failed");
if($result -> num_rows > 0)
{
while ($row = $result -> fetch_assoc())
{
echo $row['nome'];
echo json_encode($row);
}
}
?>
Any idea what can be wrong?
I think the problem must be with AJAX because when I run this code, the right information is being displayed in the browser.
Thanks for your patience and sorry for my bad english.
1) Remove echo $row['nome']; if you echo ANYTHING along with the JSON response, the full response will not be valid JSON and the success function will not be called
2) dont echo your JSON for each row like that, that's not valid either. –
Instead do this:
$response = [];
while ( $row = $result->fetch_assoc() ){
$response[] = $row;
}
echo json_encode($response);
3) you're checking $_GET['placeId'] but your ajax is using type: "POST". Change your php to $placeId = $_POST["placeId"];
Additionally, and an error function after your success function in your AJAX like the following to better see what is going wrong:
$.ajax({
type: "POST",
data: {placeId: placeID},
dataType: "json",
url: "http://localhost/Paulo%20Cristo%20LDA/insert.php",
success: function(json) {
insertResults(json);
},
error: function(xhr, status, error){
console.log(xhr);
}
});
4) Remember also that the response will be an array of rows not a single row so you'll need to update your function like so:
function insertResults(json){
alert("cenas");
$("#teste").val(json[0]["nome"]); // grab the 'nome' property from the first row in the response
}
In your PHP do this:
while($row = $result->fetch_assoc()){
$arr[] = $row;
}
echo json_encode($arr);
mysql_close($con);
Also don't forget to do mysql_close($con) at the end. Hope this helps you!
From what I see you are using val() on h3 change your function to the following and use html(), The .val() method is primarily used to get the values of form elements such as input
function insertResults(json){
alert("cenas");
$("#teste").html(json["nome"]);
}
I want to write select query in php to get data from database using variable from front-end. In other words I need to do something like this:
SELECT email FROM users WHERE token = '$token'
What I currently have, I have code which posts my variables to back end:
app.controller('customersCtrl', function($scope, $http,$templateCache) {
$scope.subscribe = function (gameId){
$scope.codeStatus = "";
$http({
url: "php/test.php",
method: "POST",
data: {
userId: JSON.parse(localStorage.getItem('loggedUserInfo')),
gameId: gameId,
token:JSON.parse(localStorage.getItem('token'))
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
cache: $templateCache
}).success(function(response) {
$scope.codeStatus = response.data;
console.log(response);
});
};
});
And here is my php code:
<?php
$lnk = mysql_connect('localhost', 'root', '')
or die ('Not connected : ' . mysql_error());
mysql_select_db('pitch', $lnk) or die ('Can\'t use db : ' . mysql_error());
$data = json_decode(file_get_contents("php://input"));
$token=$data->token;
$dump1 = mysql_query("SELECT email FROM users where token = '$token' ");
if(!$dump1) exit("Error - ".mysql_error());
$getList = array();
$outp = "";
while ($row = mysql_fetch_assoc($dump1)) {
$relations = array();
$getList[] = $row;
}
$output = json_encode(array('users' => $getList));
echo $output;
?>
The weirdest thing for me is that when I try to go to url localhost/php/test.php I get an Notice: Trying to get property of non-object in /Applications/XAMPP/xamppfiles/htdocs/php/test.php on line 8, which means I guess that $token is empty, but when I console.log(response) in angular it shows me my token in console which I think means that data from front-end was passed to back-end. Or my understanding is wrong?
Will be really thankful for help!
first thing is try to var_dump($_POST), or try to var_dump($data) on your test.php
I've got a php file containing.
<?php
$con=mysqli_connect("localhost", "user", "password", "stock");
if (mysqli_connect_errno()){
echo "failed to connect:" mysqli_connect_error();
}
$grabCars = mysqli_query($con, "SELECT * FROM CARS");
while ($row = mysqli_fetch_array($grabCars)){
$name = $row["Name"];
$color = $row["Color"];
$link = $row["Link"];
};
echo json_encode($name);
?>
ok can anyone tell me if there is anything wrong with this code. Any ideas on how this data would be displayed.
I could also do with some help at the other end what sort of jquery could would I use to read this data and how would it look, I'm very new to web design and don't know much jquery or how the ajax command would deal with this information.
Edit:
Current Jquery script
$.ajax({
url: "test.php"'
type: "post",
data: data,
datatype: "json",
success: function(result){
console.log(result["$name"]);
},
error: function(){
alert("error");
}
});
This is the code I've got to display some of the information in console, but I get nothing back, I get a data undefined message in console. Could really do with the help. Very new to json and jquery and php and webdesign as a whole. Thanks.
First of all, there shouldn't be ; after while loop.
$sampleArray = array();
while ($row = mysqli_fetch_array($grabCars)){
$name = $row["Name"];
$color = $row["Color"];
$link = $row["Link"];
array_push($sampleArray, array('name'=> $name, 'color' => $color, 'link'=>$link));
}
echo json_encode($sampleArray);
In your JQUERY/Javascript, something like this, in AJAX success:
response( $.map( data, function( item ) {
return {
name: item.name,
color: item.color,
link: item.link
}
}));
json_encode take one value parameter if you wanna encode multiple value you need to put them in an array
There is an example with your code
<?php
$con=mysqli_connect("localhost", "user", "password", "stock");
if (mysqli_connect_errno()){
echo "failed to connect:" mysqli_connect_error();
}
$grabCars = mysqli_query($con, "SELECT * FROM CARS");
$result = array();
$i = 0;
while ($row = mysqli_fetch_array($grabCars)){
$result[$i]['name'] = $row["Name"];
$result[$i]['color'] = $row["Color"];
$result[$i]['link'] = $row["Link"];
$i++;
}
echo json_encode($result);
?>
Background:
I have a page which dynamically pulls up a modal window, which displays extended information on a row (with multiple columns) through mySQL. I am having issues where my JSON code will not populate the information correctly so that it can be outputted. I have tried multiple nested arrays, while loops and for loops. However, I only need to return one full row of information from the database. After scratching my head, I am asking the help of all the SO experts. Any pointers are much appreciated.
Ajax Code For Div Population (Works)
var data_id = $(this).data('id');
$.ajax({
url: 'view_agency_info.php',
type: 'POST',
data: {id: data_id},
dataType: 'json',
success: function(data){
$('.view_modal_content').html(data.html); // LOAD THE DATA INTO THIS DIV
},
error: function(jqXHR, textStatus, errorThrown){
$('.view_modal_content').html(''); // LOAD THE DATA INTO THIS DIV
alert('Error Loading Information');
}
});
JSON Code To Pull Information and return HTML
<?php
$customer_id=$_SESSION['customer']['customer_id'];
$id = (int)$_POST['id'];
$query = "SELECT * FROM collections_list WHERE id={$id} && customer_id=$customer_id LIMIT 1"; //expecting one row
$result = mysql_query( $query );
//$message = mysql_fetch_assoc( $result ); //expecting just one row
$message=array();
while ($row = mysql_fetch_assoc($result)) {
$message[]=$row['agency_name'];
$message[]=$row['account_number'];
$message[]=$row['phone'];
}
$json = array();
$json['html'] = '<p><pre><code>id:'.$id.'.<br>Agency Name: '.$message[0].'<br>Account Number:'.$message[1]."<br>Phone:".$message[2].'</code></pre></p>'.'<br><br>test';
header('Content-Type: application/json');
echo json_encode( $json );
?>
Additional Question:
Is it possible to reference the headers in the array using " $message['agency_name'] "inside the html that gets returned?
After solving this problem, I will need to turn the outputted html into a structure to allow my users to view the information in a properly understandable format. I know how to do this in html, but I am unfamiliar with JSON... Is there a way to output the information without having to manually code the structure?
Thank you in advance.
$con = mysql_connect("localhost","user","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db(db_nname", $con);
$result = mysql_query("SELECT phone,agency_name FROM '''' ");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows['results'][] = $r;
}
print json_encode($rows);
?>
and in your html
<table id ="listtable"></table>
var listdiv = $("#listtable");
$.getJSON("whatever.php",function(json){
$.each(json.results,function(i,data){
listdiv.append("<tr><th>" + data.phone + "</th><th>" + data.agency_name + "</th></tr>");
});
});
and in the append use data. and whatever your fields are
data.agency_name
data.phone
etc....
I have jquery pop form . It takes one input from the user ,mapping_key , Once the user enters the mapping key ,i make an ajax call to check if there is a user in the database with such a key.
This is my call .
Javascript:
$.ajax({
url : base_url+'ns/config/functions.php',
type: 'POST',
data : {"mapping_key":mapping_key} ,
success: function(response) {
alert(response)
}
});
PHP:
$sql = "select first_name,last_name,user_email,company_name from registered_users where mapping_key = '$mapping_key'";
$res = mysql_query($sql);
$num_rows = mysql_num_rows($res);
if($num_rows == 0)
{
echo $num_rows;
}
else{
while($result = mysql_fetch_assoc($res))
{
print_r($result);
}
}
Now i want to loop through the returned array and add those returned values for displaying in another popup form.
Would appreciate any advice or help.
In your php, echo a json_encoded array:
$result = array();
while($row = mysql_fetch_assoc($res)) {
$result[] = $row;
}
echo json_encode($result);
In your javascript, set the $.ajax dataType property to 'json', then you will be able to loop the returned array:
$.ajax({
url : base_url+'ns/config/functions.php',
type: 'POST',
data : {"mapping_key":mapping_key} ,
dataType : 'json',
success: function(response) {
var i;
for (i in response) {
alert(response[i].yourcolumn);
}
}
});
change
data : {"mapping_key":mapping_key} ,
to
data: "mapping_key=" + mapping_key,
You have to take the posted mapping_key:
$mapping_key = $_POST['mapping_key'];
$sql = "select first_name,last_name,user_email,company_name from registered_users
where mapping_key = '$mapping_key'";
or this:
$sql = "select first_name,last_name,user_email,company_name from registered_users
where mapping_key = $_POST['mapping_key']";