Unable to read key value pair of Json_encode in javascript - javascript

I am having issues with reading Json_encode response in a java script.
The PHP file reads values from database and sends the results as Json_encode array to html.
<?php
include("connect.php");
try {
$conn = new PDO("mysql:host=$servername;dbname=mydb", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "Call print_awb (#output1,#output2,:input_awb_ref_id)";
if (isset($_POST)) {
$p_in_awb_ref_id =reset($_POST["var_p_in_awb_ref_id"]);
}
$stmt = $conn->prepare($sql);
$stmt->bindParam(':input_awb_ref_id',$p_in_awb_ref_id, PDO::PARAM_INT);
$stmt->execute();
$out_awb_ref_id = $conn->query("SELECT #output1")->fetch(PDO::FETCH_ASSOC);
$out_agent_id = $conn->query("SELECT #output2")->fetch(PDO::FETCH_ASSOC);
$output = array(
"out_awb_ref_id" => $out_awb_ref_id,
"out_agent_id" => $out_agent_id,
);
echo json_encode($output);
$stmt->closeCursor();
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
?>
The HTML CODE
<script type="text/javascript">
function get_parameters(){
var quote = ABCD1234;
quote.toString();
window.alert(quote);
$.ajax({
type: "POST",
url: "printawb.php",
data: {var_p_in_awb_ref_id:quote},
dataType: "text",
success: function (result) {
alert(result);
var a = result.out_awb_ref_id;
alert (a);
alert(result['out_awb_ref_id']);
alert(result['out_agent_id'])
},
error:function (jqXHR, status, err){
//Fail
layer_1.html(html);
}
});
return vars;
};
</script>
The response I have is
HVP000062
{"out_awb_ref_id":{"#output1":"MIR"},"out_agent_id":{"#output2":"rtPreston"}}
undefined
undefined
All Need is the values in the 2nd line of the result ie. "MIR" and "rtPreston"
I have tried couple of things:
1. changed the calling function type as 'JSON' but the response was 'Object' without values
2. Tried converting to jsonString
3. tried reading values using JSON.parse(jsonString);
4. result['out_ref_awb_id']
None of them work. Can someone help me how I can get values of these? I can then use them to populate on a html page.
Many thanks

Add this as a first line in the HEAD section of your HTML template
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
Then try this code:
<script type="text/javascript">
function get_parameters(){
var quote = ABCD1234;
quote.toString();
window.alert(quote);
$.ajax({
type: "POST",
url: "printawb.php",
data: {var_p_in_awb_ref_id:quote},
dataType: "text",
success: function (result) {
var data = jQuery.parseJSON(result);
var param1 = data.out_agent_id;
var param2 = data.out_awb_ref_id;
alert(param1["#output2"]);
alert(param2["#output1"])
},
error:function (jqXHR, status, err){
//Fail
layer_1.html(html);
}
});
return vars;
};
</script>

Related

How to use AJAX to call php file from javascript file

I want to call php file from javascript, and this php file will update id=1
like this way:
javascript:
if(lastTemp >= document.getElementById("TempSet").value){
var jsonData2 =$.ajax({
url: "setpp.php",
dataType: "json",
async: false
}).responseText;
var obj2 = JSON.parse(jsonData2);
console.log(obj2);
}
else {
}
php file:
<?php
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'use';
$DATABASE_PASS = 'pass';
$DATABASE_NAME = 'database';
// Try and connect using the info above.
$db = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS,
$DATABASE_NAME);
if (!$db){
die("Connection Failed: ". mysqli_connect_error());
}
$db_update = "UPDATE setpoint_control SET status='ON' WHERE id=1";
$result = mysqli_query($db, $db_update);
?>
<?php
$data = array();
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result)){
array_push($data, $row['status']);
}
}
echo json_encode($data);
?>
the code is executed and the status in database table is changed but I got error in console : SyntaxError: JSON.parse: unexpected character at line 4 column 2 of the JSON data
How can I solve this issue which I think I need to rewrite json_encode but I don't know how?
$.ajax({
type: 'post',
dataType: 'json',
cache: false,
url: 'setpp.php',
success: function (response) {
$.each(response, function(i, item) {
alert(item);
});
},
error: function () {
alert("error");
},
});
example php answer setpp.php
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
array_push($data, $row['status']);
}
die(json_encode($data));
} else {
$answer = array(
'No Records'
);
die(json_encode($answer));
}
I think the problem is the value returned by setpp.php.
remember to die(), otherwise the php answer will not be correct

ajax jquery errors on json return value from php script

I'm having problems with this ajax/jquery programming.
I've tried many different things but nothing has worked.
Ajax posts selItem to ajaxsql.php, this works!
The sql query in ajaxsql.php works, cause it outputs this if i call the script directly in the browser: [{"forumname":"SDE forum","user":"michael","txt":"Jeg hedder Michael!"}]
The problem is that the ajax function shows an alert box with Error[object Object]
forum.php script:
<script type="text/javascript">
function ForumChat(selItem) {
$.ajax({
type: "POST",
url: 'ajaxsql.php',
data: { selectedItem : selItem.value },
dataType: "json",
success: function(data) {
alert(data);
$('#txtarea').html(data);
},
error: function(data) {
alert('Error' + data);
}
});
}
</script>
ajaxsql.php script:
<?php
if(!isset($_SESSION))
{
session_start();
}
include('class.php');
//$sel = $_POST['selectedItem'];
$sel = "SDE forum";
$sql = " SELECT * FROM forum WHERE user = '".$_SESSION['currentuser']."' AND forumname = '".$sel."' ";
$result = mysqli_query($_SESSION['con'], $sql);
while($row = mysqli_fetch_array($result))
{
$forumname = $row['forumname'];
$user = $row['user'];
$txt = $row['text'];
$return[] = array("forumname" =>$forumname, "user" =>$user, "txt" =>$txt);
}
echo json_encode($return);
?>
because ajaxsql.php returns object ..
what you can do in your ajax is
success: function(response) {
$('#txtarea').html('');
$.each(response.data, function(){
console.log(this);
$('#txtarea').append(data);
});
},

How to pass multiple variables from a php file to ajax and use them?

I have read many answers on stack overflow but I can't find an apt answer. I want to send multiple variables from php file to a javascript file. I want to use those variables later separately. So please explain with a simple example of how to get the variables from php file and how to use them separately later.
This is my js.
<script>
function here(card_numb) {
alert("pk!");
$.ajax({
url: 'details.php',
type: "GET",
dataType: 'json',
data: ({
card_number: card_numb
}),
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.book_isued);
}
});
}
I'm getting the alert 'pk!'. But $.ajax ain't working.
This is details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = '".$card_number."'";
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if($row_numb == 0){
echo "<div class='bdiv1'>No such number found!</div>";
} else{
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
}
?>
Thank you!
somthing.js - ur jspage
<script>
function here(card_numb) {
$.ajax({
url: 'details.php',
type: 'GET',
dataType: 'json',
data: {
card_number: card_numb
},
success: function(data) {
console.log('card_number:'+data.card_number+'book_issued:'+data.isued_book);
}
});
}
success: function(result){
console.log('variable1:'+result.var1+'variable2:'+result.var2+'variable3:'+result.var3);
} });
details.php
<?php
if(isset($_GET['card_number'])){
$card_number = $_GET['card_number'];
$query = "Select * from users where card_number = ".$card_number;
$query_run = mysqli_query($link,$query);
$row_numb =#mysqli_num_rows($query_run);
if(!$query_run){
echo "<div class='bdiv1'>No such number found!</div>";
} else {
$row=mysqli_fetch_assoc($query_run);
$book1 = $row['user_name'];
$arr = array('isued_book' => $book1,'card_number' => $card_number);
echo json_encode($arr);
exit();
}
if the currect value get in $row you can get the result in console

Codeigniter ajax call error

I'm trying to make an ajax call to get result from my database, but i'm facing an error.
My javascript:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script language="Javascript">
setTimeout(makeAjaxCall, 1000);
function makeAjaxCall(){
$.ajax({
type: "post",
url: "call/update",
cache: false,
data: {action: 'getUpdate', term: '<?php echo $id;?>'},
success: function(json){
try{
var obj = jQuery.parseJSON(json);
alert( obj['STATUS'] + obj['results']);
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
}
</script>
And my controller's method:
public function update()
{
if (isset($_POST['action'])){
if ($_POST['action'] == 'getUpdate'){
pollNewData();
}
}
function pollNewData(){
$term = $_POST['term'];
$query = $this->db->query("SELECT * FROM users where guid <> '' and user_id = '$term'");
$res = $query->result();
echo json_encode(array('STATUS'=>200, 'results'=>$res));
}
}
i have this error on chrome debugs tool:
500 (Internal Server Error)
You have several issues. Below is the working code:
public function update()
{
if(!function_exists('pollNewData')){ // don't redeclare if already exists
function pollNewData($db){ // pass $db
$term = $_POST['term'];
$query = $db->query("SELECT * FROM users where guid <> '' and user_id = '$term'");
$res = $query->result();
echo json_encode(array('STATUS'=>200, 'results'=>$res));
}
}
if (isset($_POST['action'])){
if ($_POST['action'] == 'getUpdate'){
pollNewData($this->db); // pass $this->db
}
}
}
Changes:
Moved the function definition to before it is called - it must exist before calling.
The $this context is not set in the function, so pass the $db object as an argument.
When defining functions inside a class method, you must have a function_exists() check because on the second call, it will try to redeclare the function and produce a fatal error.
For future debugging you should turn errors on:
error_reporting(E_ALL);
ini_set('display_errors', '1');
Some suggestions:
url: "<?php echo base_url();?>call/update",
//pollNewData();
echo $this->pollNewData(); //call like this and echo it out to the ajax
//echo json_encode(array('STATUS'=>200, 'results'=>$res));
return json_encode(array('STATUS'=>200, 'results'=>$res)); //return it instead to the calling function

Ajax separate data which came from mysql

I am doing an ajax call like this:
function myCall() {
var request = $.ajax({
url: "ajax.php",
type: "GET",
dataType: "html"
});
request.done(function(data) {
$("image").attr('src',data);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
This is my ajax.php:
<?php
$connection = mysql_connect ("",
"", "");
mysql_select_db("");
// QUERY NEW ONE
$myquery = "SELECT * FROM mytable ORDER BY rand() LIMIT 1";
$result = mysql_query($myquery);
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
echo $currenturl,$currentnam, $currenturl,$currentimage;
}
mysql_close($connection);
?>
My data variable from the ajax call now contains all variables at once:
($currenturl,$currentnam, $currenturl,$currentimage)
How can I separate them so I can do something like:
request.done(function(data) {
$("id").attr('src',data1);
$("name").attr('src',data2);
$("url").attr('src',data3);
$("image").attr('src',data4);
});
jQuery :
$.ajax({
type:"POST",
url:"ajax.php",
dataType:"json",
success:function(response){
var url = response['url'];
var name = response['name'];
var image = response['image'];
// Now do with the three variables
// $("id").attr('src',data1);
// $("name").attr('src',data2);
// $("url").attr('src',data3);
// $("image").attr('src',data4);
},
error:function(response){
alert("error occurred");
}
});
From your code:
echo $currenturl,$currentnam, $currenturl,$currentimage;
Replace the above line with the code below:
$array = array('url'=>$currenturl, 'name'=>$currentname, 'image'=>$currentimage);
echo json_encode($array);
instead of string return an array i.e. use json type for returning value
i.e instead of
echo $currenturl,$currentnam, $currenturl,$currentimage;
use
echo json_encode array('current' => $currenturl,'currentnam' => $currentnam, 'currenturl' => $currenturl,'currentimage' => $currentimage);
and also write 'dataType' as 'json' in ajax

Categories