codeigniter get data via ajax and json from db - javascript

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

Related

access the response Json data in 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;
----------------------------------------------------------------------^^^

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

How I return data from database separately (integers) using ajax

I want to return data from database using AJAX
here the AJAX code for retrieving the data but it can't give it saparataly.
$(document).ready(function(){
$('#bathroom-select').change(function(){
var bathroom_option1 =$(this).val();
console.log(bathroom_option1);
$.ajax({
type:'POST',
data:({bathroom_option1}),
success:function(data){
price1=parseInt(data);
console.log(price1);
var rows;
$.each(data, function (key, name) { //this will not work
console.log(item[i]);
});
}
});
});
});
here the database image where the data is stored.
anybody plz explain me i m new on the stackoverflow so if there is any mistake then sorry.
And thankyou for replying me the answers.
this is the server site processing using php
$con=mysqli_connect("localhost","root","","price");
if (isset($_POST['bathroom_option1'])) {
$query=mysqli_query($con,"select * from bathroom where number_of_bathrooms ='$_POST[bathroom_option1]'");
while ($row = mysqli_fetch_array($query)) {
echo json_encode($row['price'],JSON_NUMERIC_CHECK);
echo json_encode($row['hours'],JSON_NUMERIC_CHECK);
echo json_encode($row['minutes'],JSON_NUMERIC_CHECK);
}
}
Ok so try this maybe :
1/ Your ajax call :
$(document).ready(function(){
$('#bathroom-select').change(function(){
var bathroom_option1 =$(this).val();
console.log(bathroom_option1);
$.ajax({
type:'POST', // you send data with POST method
data:{ "bo1" : bathroom_option1}, //the data you send
dataType : "JSON", // what you will get as anwser data type
url : yourphp.php, // your .php where you send your data
success:function(response){
var data = response.data; // your anwser array with one row = one item with price, hours and minutes
// See why in my PHP, but here you can get the message and the type you send with "response.message" and "response.type", can be usefull if you want to do something different according to what happen in your .php
$.each(data, function (key, name) {
console.log(this); // one row
});
}
});
});
});
2/ Your .php :
$result = array();
$con=mysqli_connect("localhost","root","","price");
if (isset($_POST['bo1'])) { // you get your data with post method here, with the key you used in your call, here 'bo1'
$query=mysqli_query($con,"select * from bathroom where number_of_bathrooms ='$_POST['bo1']'");
while ($row = mysqli_fetch_array($query)) {
// You add each row in your $result['data'] array
$result['data'][] = array(
"price" => $row['price'],
"hours" => $row['hours'],
"minutes" => $row['minutes']
);
} // end while
} // end if
$result['message'] = "All is ok !";
$result['type'] = "success";
echo json_encode($result);
// You can send back what you want as message or type for example, if you have some test to do in your php and it fails send back $result['type'] = "warning" for example
Is this what you are looking for?
This probably because item is not defined try this
$.each(data, function () {
console.log($(this));
});

Jquery - GET url value and store in a variable

I would like to GET the value from my url and store it in a variable the to use it in my sql query as a where statement. My admin_id is good, but the $x is not working.
here is what I got.
The URL http://localhost/ict138final/admin/Aviewrecords.php?edit=2
The Query
$id=$_POST['admin_id'];
$x=$_POST['edit'];
$query=mysql_query("DELETE FROM passed_deliverable WHERE deliverable_id={$id} && user_id={$x} ");
function Delete() {
window.location.reload();
lol = $('#wee').text();
var bayotmarkyu = "<?php echo $_GET['edit']; ?>";
$.ajax({
type:'POST',
url:'Adeletedeliverable.php',
data: {admin_id:lol,edit:bayotmarkyu},
success: function(data) {
}
});
}
Try this way to assign admin_id & edit using $_POST because you send AJAX call using POST method.
//on Adeletedeliverable.php file
print_r($_POST); //only for debug before assign
$id=$_POST['admin_id'];
$x=$_POST['edit'];
$query=mysql_query("DELETE FROM passed_deliverable WHERE deliverable_id={$id} && user_id={$x} ");
die(json_encode(array('status'=>'success')));
//On javascript funciton(Aviewrecords.php),so just $_GET['edit'];
function Delete() {
window.location.reload();
lol = $('#wee').text();
var bayotmarkyu = "<?php echo $_GET['edit']; ?>";
$.ajax({
type:'POST', // see your ajax call method carefully
url:'Adeletedeliverable.php',
data: {admin_id:lol,edit:bayotmarkyu},
success: function(data) {
alert(data.status);
}
});
}
Your calling the "x" variable wrong.
Should be $x
and your get should be a post
U have to use $_GET instead of $_POST than.
$x=$_GET['edit'];

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