Get value from php function to javascript - javascript

I am stuck with getting an array from php function located in another file to a javascript. I used the below code but nothing is happening.
PHP code:
$sprd_array;
$spread = 0;
foreach ($data as $key => $value) {
$spread =(int) ($value->ask*100000) - ($value->bid * 100000);
$spread =(float) $spread / 10000;
$spread = round( $spread, 5, PHP_ROUND_HALF_UP);
$sprd_array[] = $spread;
}
for($i = 0;$i < sizeof($sprd_array); $i++){
//echo "spread: " . $sprd_array[$i] . "<br />";
}
return $sprd_array;
}
I want to get the array in another javascript file.
javascript code:
$.ajax({
url:'jsondecode.php',
complete: function (response) {
alert("done");
},
error: function () {
alert("error");
}
});
return false;

Do it like
$.ajax({
url:'jsondecode.php',
dataType : json,
success: function (data) {
console.log(data); // This is the data you want.
},
error: function () {
alert("error");
}
});

In PHP, use the function json_encode() to encode your objects / arrays to JSON Format. Note that setting the second argument to true will keep associative array indeces.
Also, your JavaScript code is not alright. You need to use success: instead of complete:. Then, you can easily convert the string back into an object using JSON.parse(yourJSONString);.

In php change "return $sprd_array;" to:
echo json_encode($sprd_array);

Related

Fetching a single record is outputting more than the records contents and json.parse not logging the correct data

I set up a new table called triggers. What I am doing is setting up a simple binary system that triggers things from showing or not showing. The code below is from an attempt I just made at doing this.
I'm running into two issues with the code below.
The echo json_encode is actually echoing onto the file's page. I have never had this happen before, so I'm unsure why it is doing so.
The echoed result is this:
{"specialPopStatus":{"setting":"1","0":"1"}}
The only number that should be showing up is 1. I don't understand where the trailing 0 and 1 are coming from.
The console.log results from the JSON.parse is [object Object]. I don't understand why, if at the very least, the 1, 0 and 1 isn't outputting.
Ultimately, all I am wanting is the setting result from the db for the single record I indicate by the name. Then I want to fetch this record via my ajax function. It will always be either 0 or 1.
What am I doing wrong?
PHP
try {
$con = getConfig('pdo');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$special_pop_sql = "
SELECT setting
FROM triggers
WHERE trigger_name = 'Special Pop'
LIMIT 1
";
if ($special_pop_stmt = $con->prepare($special_pop_sql)) {
$special_pop_stmt->execute();
$special_pop_row = $special_pop_stmt->fetch();
}
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
echo json_encode(['specialPopStatus' => $special_pop_row]);
JS
var status2 = 0;
function ajaxSpecialPopTrigger() {
$.ajax({
url: '/php/triggers.php',
datatype: 'json',
success: function (data) {
obj = JSON.parse(data);
specialPopStatus = obj.specialPopStatus;
status2 = specialPopStatus;
console.log(status2 + ' This is the status');
}
});
}
ajaxSpecialPopTrigger();
EDIT - New JS:
var status2 = 0;
function ajaxSpecialPopTrigger() {
$.ajax({
url: '/php/triggers.php',
datatype: 'json',
success: function (data) {
//obj = JSON.parse(data);
//Catalog Requests
specialPopStatus = data.specialPopStatus;
status2 = specialPopStatus;
console.log(status2 + ' This is the status');
}
});
}
ajaxSpecialPopTrigger();
The reason for the extra data in the json string is that you use
$special_pop_row = $special_pop_stmt->fetch();
the default of which is to return an assoc array AND a numeric array, notice the data value is 1 in both cases.
So fix that by doing this small mod
$special_pop_row = $special_pop_stmt->fetch(PDO::FETCH_ASSOC);
Also in the javascript because you have given
datatype: 'json',
as the paramter, you dont have to parse the json as jQuery will do that for you
So the javascript code be written
var status2 = 0;
function ajaxSpecialPopTrigger() {
$.ajax({
url: '/php/triggers.php',
datatype: 'json',
success: function (data) {
//obj = JSON.parse(data);
specialPopStatus = data.specialPopStatus;
//status2 = specialPopStatus;
console.log(specialPopStatus + ' This is the status');
}
});
}
ajaxSpecialPopTrigger();

variable undefined when get data from json_encode (Function PHP)

I want get value from php file, so I call json_encode function in my php script. but when i get value using javascript the result is undefined.
I am using codeigniter and javascript.
Javascript
var sisa = (persentasevco / 100) * (jumlahvco)
document.getElementById('periodetk').value = periodetk
var totalt = sisa * periodet
$.ajax({
url: '<?=base_url(\'lahan/convertString/\')?>' + totalt,
success: function (data) {
document.getElementById('persediaanvco').value = data.hasil
},
})
PHP
public function convertString($value){
$hasil = number_format($value,2,',','.');
echo json_encode($hasil);
}
I want send $hasil from php to javascript
If you are just sending a string (the output from number_format), you don't need to json_encode it.
PHP
public function convertString($value){
echo number_format($value,2,',','.'); // Echo directly
die(); // End script
}
JS
var sisa = (persentasevco / 100) * (jumlahvco)
document.getElementById('periodetk').value = periodetk
var totalt = sisa * periodet
$.ajax({
url: '<?=base_url(\'lahan/convertString/\')?>' + totalt,
success: function (data) {
document.getElementById('persediaanvco').value = data
},
})

pass php array to javascript using ajax

I try to get array from sql server using php , and parsing these array to javascript using ajax.
However , I have tried many solution by google , I can't get the array.
This is my php code:
<?php
include 'Connect.php';
$Store_int = $_GET['num'];
$sql = "SELECT * FROM `store` WHERE `Place_int` = " . $Store_int;
mysqli_select_db($link, "web");
$link->set_charset("utf8");
$result = mysqli_query($link, $sql);
$arr = array();
while ($row = mysqli_fetch_object($result)) {
$p = (string)$row->Name;
$arr[] = $p;
}
//print_r($arr);
$jsonArr = json_encode($arr, JSON_UNESCAPED_UNICODE);
echo $jsonArr;
mysqli_free_result($result);
mysqli_close($link);
?>
Array in php will encode and display:
["pen","pencil","apple","cat","dog"]
and the .js file
function getArr(store_int) {
var jsArray = new Array();
$.ajax({
url: "fromSQL_store.php",
data: {
num: $("#store_int").val()
},
type: "GET",
dataType: "json",
success: function (data) {
alert(num);
jsArray = JSON.parse(data.jsonArr);
}, error: function (data) {
alert("123");
}
});
//alert(jsArray.length);
return jsArray;
}
In .js , I will always get empty response(undefined) from php.
Because the ajax will answer "error" function..., and the error status is 200.
Your array will always return undfined as the AJAX call is async, your function returns jsArray before it is set. and You don't need JSON.parse() as you have defined dataType as json in your ajax call. Pass a function to your getArr() function and use your data in that function.
function getArr(store_int, outputFn){ // what do you use store_int for?
$.ajax({
url: "fromSQL_store.php",
data: {
num: $("#store_int").val()
},
type: "GET",
dataType: "json",
success: function(data) {
outputFn(data)
},error: function(data){
alert("123");
}
});
}
Then use it like
getArr('5', function (data) {
console.log(data)
})
Console output
Your problem lies here. You are attempting to access data.jsonArr which is always undefined. The JSON data sent is actually embodied by data variable.
success: function(data) {
alert(num);
jsArray = JSON.parse(data.jsonArr); // Replace by jsArray = data;
}
NOTE, You might also need to specify that the MIME media type that is being outputted is JSON. Putting this at the top of your PHP script should solve your problem.
<?php
header('Content-Type: application/json');

Cant get PHP variables using AJAX

I can't seem to figure out what's the problem. For my next little project I'm creating dynamic web page with database and etc. I need to get all the necessary variables from PHP file. But for some reason I cannot do it if I include another PHP file. (I need it for database queries).
main.php
include ('databaseQueries.php');
if (isset($_POST["points"])){
$points = json_decode($_POST["points"]);
if($_POST["execute"] == 1){
}
}
$advert= array(
'Hello' => 'Hello world!',
'bye' => 'Why bye?',
);
echo json_encode($advert, $another);
pageJs.js
$.ajax({
url : 'php/main.php',
type : 'POST',
dataType : 'json',
success : function (result) {
console.log(result);
},
error : function (err) {
console.log("Failed");
}
})
databaseQueries.php
$another = "another string";
If I remove the include and $another variable from json_encode. Everything works and I get object in console log. But if I leave the those two things, Ajax call fails.
What I'm doing wrong and how can I get both the $test array and $another variable?
Thank's in advance!
You are using json_encode incorrectly. From the documentation:
string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
You are trying to send $another to the function as the options parameter.
You could do something like this:
$ret = array($advert, $another);
echo json_encode($ret);
Unless I'm completely wrong, I can't see where you're sending anything TO your post
$.ajax({
url : 'php/main.php',
type : 'POST',
dataType : 'json'
// I would expect a data call here, something like:
data: $(form).serialize(), // OR { points: 3, execute: 1 }
success : function (result) {
console.log(result);
},
error : function (err) {
console.log("Failed");
}
})
I assume that you want to spit back some results with the format of result->key;
So Keeleon's answer above is good:
$ret = array($advert, $another);
echo json_encode($ret);
But you can also do:
//Adding everything to array, and asking json_encode to encode the array is the key. Json_encode encodes whatever is in the first argument passed to it.
$ret = array('advert'=>$advert, 'another'=>$another,'test'=>$test);
echo json_encode($ret);
Hopefully, this answers your questions.

response from php to javascript via json

I have this function in php
public function get_updated_session_value()
{
$sql = "SELECT IF(Session = 12345678 , 1,0) AS login FROM `psf_users` WHERE id = 236";
$var = $this->addDb($sql)->execute();
$Session = $var['login'];
return json_encode('2');
}
and the javascript code to fetch this value,
function check() {
$.ajax({
url : 'auctions.php',
type : 'get',
// dataType: 'json',
data : {page:'__request', module:'PSF_auctions', action:'get_updated_session_value'},
success: function(data) {
console.log(data);
}
});
}
also, this function runs every 5 seconds via
setInterval(check, 5000);
the problem is, console.log(data); prints nothing, i believe that means it is not getting any data (or json response) from the php function. am i missing something?
It can't work as you're returning the value. The difference between returning a value and emitting a response is that the latter writes a response on the HTTP stream whilst the first one merely returns the control to the parent with a specific value.
Sanjay has spotted it very well, and I'd recommend that you use a very simple function to wrap up your responses:
function emit_response( $status_code, $data ) {
http_response_code( $status_code ); // 200 is it's success. find more http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
die( json_encode( array(
"status_code" => $status_code,
"data" => $data )));
}
Then modify that echo (though it's fine as well) with
emit_response( 2 );
and since the response is valid JSON, JavaScript will love it; in your callback, you can simple do this:
success: function(res) {
var response = JSON.parse( res );
// response.data will be 2. :)
// ... rest of the code ...
Replace return with echo like this:
public function get_updated_session_value()
{
$sql="SELECT IF(Session = 12345678 , 1,0) as login FROM `psf_users` WHERE id=236";
$var= $this->addDb($sql)->execute();
$Session= $var['login'];
echo json_encode('2');
}

Categories

Resources