access the response Json data in javascript - javascript

I'm using a Json in my HTML to get data from Database but I can't access the data of returned Json here is my HTML function :
$.ajax({
type: "POST",
url: 'fetch.php',
dataType: 'json',
data: {func:"viewCert",tracking_code:tracking_code},
success: function (data) {
if (data!=null) {
document.getElementById("generation_date").textContent = data.certInfo.timestamp;
} else {
alert("Something's Wrong! Try Later");
window.location = "../views/failed.html";
}
}
});
and here is fetch.php function :
function viewCert($tracking_code) {
$connect = connection();
$connect->set_charset("utf8");
$sql = "SELECT timestamp FROM certificate WHERE tracking_code=?";
$result = $connect->prepare($sql);
$result->bind_param("s",$tracking_code);
$result->execute();
$res=$result->get_result();
while ($row=$res->fetch_object()) {
$output[]=$row;
}
echo json_encode(array('certInfo' => $output));
}
Sorry for this question I'm just new in HTML and Javascript , so anyone know why timestamp won't be set in 'generation_date' element?
any help will be much appreciated

In your PHP, $output seems to be an array. So in your javascript you need to access on the good index to get the data.
Try :
document.getElementById("generation_date").textContent = data.certInfo[0].timestamp;
----------------------------------------------------------------------^^^

Related

unable to parse xml data with AJAX + Wordpress

Ok, I am officially stumped. I have been trying to find why my calls for specific items in a PubMed xml data file are not working... I can execute this one with my current coding:
$test = (string)$id_json->PubmedArticle->MedlineCitation->PMID;
but if I try to get a variable that is in a deeper array, it does not return a value. I have even tested with console.log(data) and I get my PMID returning but not my other, deeper values in the XML file. For example;
$test = (string)$id_json->PubmedArticle->MedlineCitation->Article->Journal->ISSN;
returns nothing for data in console.log(data)
Here is my function in wordpress:
function get_abstract(){
$id = $_POST['abstractid'];
$pubmed_api_call = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&retmode=xml&rettype=abstract&id='.$id;
$id_wpget = wp_remote_get($pubmed_api_call, array('timeout' => 20));
if( is_wp_error( $id_wpget ) ) {
echo "Error Contacting PubMed, please refresh page and try again";
die();
}
$id_xml = wp_remote_retrieve_body($id_wpget);
$id_json = simplexml_load_string($id_xml);
$test = (string)$id_json->PubmedArticle->MedlineCitation->Article->Journal->ISSN;
if($test === ""){
echo "NOTHING";
die();
}
echo $test;
die();
}
and here is my javascript AJAX call:
jQuery(document).ready(function() {
jQuery('.reference_header').click(function(e) {
jQuery(this).find("i").toggleClass("arrow-down arrow-up");
jQuery(this).nextUntil('.reference_header').slideToggle('fast');
var abstractid = jQuery(this).data("id");
e.preventDefault();
jQuery.ajax({
url: get_abstract.ajaxurl,
type: 'POST',
dataType: 'json',
data: {
abstractid: jQuery(this).data("id"),
action: 'get_abstract'
},
success : function(data){
jQuery('.'+abstractid).html("TESTING: "+data);
console.log(data);
}
});
});
});
I cannot find out why it doesnt work... any help is greatly appreciated.
So I figured out the solution to the issue... you need to pass the string text as a json object to AJAX for it to read properly...
working code:
PHP:
echo json_encode(array("result" => "$test"));
die();
AJAX:
success : function(data){
jQuery('.'+abstractid).html("TESTING: "+data.result);
console.log(data.result);
}

Ajax JQuery post code with Php to query MySql database not working

I have an HTML form that runs a Javascript function on page load. In the Javascript function, a town name is sent via Ajax post call to Php function to get details from MySql database.
Ajax call in JavaScript function
var town = "Town name"; //depends on the previous execution in JS function
if (town != "undefined") {
jQuery.ajax({
type: "POST",
url: '../model/data_access/GetCity.php',
dataType: 'json',
data: {town: town},
success: function (obj) {
document.getElementById("selectedLocation").value = obj[0]["name"];
document.getElementById("placeDescriptionBox").value = obj[0]["description"];
}
});
}
GetCity.php
$town = $_POST['town'];
get_city($town);
function get_city($town)
{
$place = array();
$db_conn = DBConnection::get_database_connection();
$stmt = $db_conn->prepare("SELECT * FROM place WHERE name=?");
$stmt->bind_param("s", $town);
$stmt->execute();
if (!($result = $stmt->get_result())) {
echo "Error" . $stmt->error;
}
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$place[0] = new Place();
$place[0]->set_name($row["name"]);
$place[0]->set_description($row["description"]);
echo json_encode($place);
}
}
The data from database are not displayed in the HTML form. How can I solve this?
I'm new to Ajax JQuery so any help is much appreciated.
You are making a POST request:
type: "POST",
… but are trying to read the data from the query string:
$town = $_GET['town'];
jQuery will post data in the request body when you make a POST request, so it will appear in $_POST not $_GET.
Change type: "POST", to type: "GET", (or omit it entirely as GET is the default).
if you are checking whether the variable exist are not :
if (town != "undefined") {} should be if (typeof town !== "undefined") {}
Change $town = $_GET['town']; to $town = $_POST['town']; as you used type: "POST", in your ajax request.
Please pass the town name with url encoded with javascript function encodeURI and please debug the code whether your php code returns the town list or not
var town = "Town name"; //depends on the previous execution in JS function
if (town != "undefined") {
jQuery.ajax({
type: "POST",
url: '../model/data_access/GetCity.php',
dataType: 'json',
data: {town: town},
success: function (obj) {
console.log(obj);
document.getElementById("selectedLocation").value = obj[0]["name"];
document.getElementById("placeDescriptionBox").value = obj[0]["description"];
}
});
}

codeigniter get data via ajax and json from db

I have following problem:
View:
<script>
function show(id) {
$.ajax({
url: '<?php echo site_url('index.php/controller/show_id'); ?>',
dataType: 'json',
data:({id: id}),
type: "POST",
success: function (data) {
alert( data.user_id);
}
});
}
</script>
Controller:
function show_id(){
$id= $this->input->post('id');
$id_list = $this->id_model->show_id($id);
$data['id'] = $id_list;
if($data['id']){
echo json_encode( $data['id'] );
} else {
echo json_encode( array('error' => true) );
}
}
If I load the page, I got "undefined" as an alert.
If I change the JS to "alert(data);" I receive all content of the sql table.
How do I have to change the JS to get only "user.id" column?
please check type of data like that alert(typeof data); if its get string then you need to convert your response in object and you can convert your response in object like that --
var result = JSON.parse(data);
and you are getting a single row or multiple rows ????? if you are getting a single row then after convert in object you have to access data.user_id like that (after convert into object) --
var userId = result[0]['user_id];
please try this..
You are getting undefined because the index user_id is not found in data. you have too loop through the array first and then you can get value of data.user_id
see below.
success: function (data) {
var data = JSON.parse(data);
console.log(data);
for (var x in data){
console.log(data[x].user_id);
}
}

Jquery Ajax get not passing values

This is driving me crazy...
$(document).on("click",".load",function(b){
b.preventDefault();
$.get("/url/get.php",{
id: 123
},
function(a){
$("#result").html(a);
})
});
This loads the page as expected but when I do print_r($_GET) it shows it's empty...
Any ideas?
Backend:
if (isset($user) == false) {
session_start();
$path_to_root = "../";
require($path_to_root."require/loads.php");
$PDO = new PDO(DB_CONN, DB_USERNAME, DB_PASSWORD);
$user = new User($PDO);
}
$i = 0;
print_r($_GET);
Please, try this way, using done() function:
$(document).on("click",".load",function(b){
b.preventDefault();
$.get("/url/get.php",{
id: 123
}).done(
function(a){
$("#result").html(a);
})
});
As said in jquery docs that´s the way to send payload data with GET.
Anyway, you can also use ajax:
$.ajax({
url: "/url/get.php",
type: "get", //send it through get method
data:{id:123},
success: function(response) {
$("#result").html(a);
},
error: function(xhr) {
$("#result").html("ERROR");
}
});
Anyway, if you are still viewing those errors, the problem souhld be in your backend as #AmmarCSE commented.
Hope it helps
EDIT some text about the difference between jquery methods success() and done() :
jQuery ajax success callback function definition
please try this
$(document).on("click",".load",function(b){
b.preventDefault();
$.ajax({
method:'get',
url : '/url/get.php',
data : '{id:123}',
dataType: 'json', //json,html any you will return from backend
success:function(a){
$("#result").html(a);
}
})
});
Try using
$data = file_get_contents("php://input");
$r = json_decode($data);
instead of $_GET in you php file, then print $r

Using ajax to send a JS variable, but how can I use PHP variables afterwards to my main file?

How can I use some PHP variables from the ajax-send.php to the index.php file? I use AJAX as shown below. Do I have to replace AJAX with something else?
index.php
$.ajax({
type: 'POST',
url: 'ajax-send.php',
data: { one: hash },
success: function(data) {
}
});
ajax-send.php
$token = $_POST['one'];
echo "ok"
$toINDEX = "use this in index.php"
Try this
Ajax
$.ajax({
type: 'POST',
url: 'ajax-send.php',
data: { one: hash },
success: function(data) {
var response = data;
//alert(data);To see what you have received from the server
}
});
PHP
if(isset($_POST['one'])){
$token = $_POST['one'];
echo "ok";
$toINDEX = "use this in index.php";
die();
}
In PHP just echo variable or json_encode array. In JS do the following:
var result = $.ajax({
url: this.fileUrl,
type: "POST",
data: data,
async: false,
dataType: 'json'
}).responseText;
Your vaiable is fully accessable.
take the variables in php sessions
//On page 1(ajax-send.php)
session_start();
$_SESSION['token'] = $_POST['one'];
//On page 2(index.php)
session_start();
$var_value = $_SESSION['token'];
You can simply echo the variable and then access it via javascript inside the success function.
But a better approach would be to json_encode the data. The beauty of this is that it will help you to pass multiple values/variables in a single echo. So
PHP
.
..
if(<all is okay>)
{
$toINDEX = "use this in index.php"
$data['result'] = 'ok';
$data['msg'] = $toINDEX;
$data['some_other_value'] = 'blah blah';
// notice how I'm able to pass three values using this approach
}
else
{
$data['result'] = 'notok';
}
echo json_encode($data);
Javascript
$.ajax({
type: 'POST',
url: 'ajax-send.php',
data: { one: hash },
dataType:'json',
success: function(data) {
if(data.result == 'ok')
{
console.log(data.msg);
console.log(data.some_other_value);
}
else
{
// something went wrong
}
}
});
The important thing to note here is dataType:'json' which tells the function to expect the returned data in json format.
EDIT:
As per you comment, you could do this
$toINDEX = "use this in index.php";
// now use the variable here itself
mysql_query("SELECT * FROM table WHERE column = '$toINDEX'");
.
.
if(<all is okay>)
{
$data['result'] = 'ok';
$data['msg'] = 'anything you would like to show the user';
$data['some_other_value'] = 'blah blah';
// notice how I'm able to pass three values using this approach
}
else
{
$data['result'] = 'notok';
}
echo json_encode($data);

Categories

Resources