variable undefined when get data from json_encode (Function PHP) - javascript

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

Related

JSON array to and from MySql. Saving and Looping

<?
$cl = $row["saved_json_string_column"];
?>
expecting this output from the db query to create a new array
//cl = '[{"ifeid":1,"ans":"Yes","type":"SkipTo","target":"2"},{"ifeid":2,"ans":"Yes","type":"SkipTo","target":"5"}]';
cl = '<? echo $cl;?>';
// I would like to start with the saved 'cl' array and push new items to it.
skptoQarry = new Array();
//javascript function loop (not shown) generates vars and pushes to new array.
thisItem_eid = 1;
yes_no_is_this = 'No';
SkipToTartgetEID = 5;
var skptoQarry_temp = {
"ifeid" : thisItem_eid,
"ans" : yes_no_is_this,
"type" : "SkipTo",
"target" : SkipToTartgetEID
};
skptoQarry.push(skptoQarry_temp);
cl = JSON.stringify(skptoQarry); //for ajax post to php for saving
//this is what is in saved the DB via ajax post
[{"ifeid":1,"ans":"Yes","type":"SkipTo","target":"2"},{"ifeid":2,"ans":"Yes","type":"SkipTo","target":"5"}]
//...but when PHP echos it out only this comes out: cl = "[,]"
// I think i'm saving it wrong or echoing the column data the wrong way.
//read text from mysql and append where needed.
cl = $.parseJSON(cl);
jQuery.each(cl, function (i) {
jQuery.each(this, function (key, value) {
if (key == "ifeid") {
$('div').append('if this id: '+value+'<br>');
} else if (key == "ans") {
$('div').append('is: '+value+'<br>');
} else if (key == "type") {
$('div').append('then: '+value+'<br>');
} else if (key == "target") {
$('div').append('this id: '+value+'<br><br>');
}
});
});
function saveit(){
saved_logic_dialog = JSON.stringify(skptoQarry);
var posturl = "myurl?event=save&saved_logic_dialog="+saved_logic_dialog;
jQuery.ajax({
traditional: true,
type: "POST",
url: posturl,
success: function(data) {
//messages and stuff
}
});
}
//php
$loadvfsql = "SELECT `saved_logic_dialog` FROM `questions` WHERE `id` = '{$id}' ORDER BY `questions`.`question_order` ASC";
$loadv_result=mysql_query($loadvfsql);
while($rows=mysql_fetch_array($loadv_result)){
$clc = $rows['current_logic_cont'];
$cl = $rows['saved_logic_dialog'];
//more stuff
}
This will ensure your array of objects is properly encoded - jQuery will not encode the URL for you.
var posturl = "myurl?event=save&saved_logic_dialog=" + encodeURIComponent(saved_logic_dialog);
When saving to DB - check for properly escaping the value (as it will certainly contain quotes);
When echoing the value back into HTML - use htmlspecialchars($cl) to properly escape the symbols which might have special meaning in HTML.
Before using the value in JavaScript - use JSON.parse(cl) to convert from String into Array.

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

How can I return object values the corect way to do it

I'm trying to return a global variable and set an object in an array.
Could anyone explain what I am doing wrong to retrieve the global variable outPutArray? It become undefined when I try to return it.
var outPutArray = {};
var goAjax = function(data, filePath) {
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: filePath, //Relative or absolute path to response.php file
data: data,
success: function(data) {
for (x in data) {
outPutArray[x] = data[x];
}
//logs the the wanted value
console.log('inside ' + outPutArray['json']);
}
});
};
goAjax.prototype.getValue = function() {
console.log('outside ' + outPutArray['json']);
//logs undefined ??
};
It's undefined when you try to return it because AJAX is asynchronous.
See this questions, and this question, or Google "return AJAX response" or something similar.
It boils down to the fact that asynchronous calls happen outside of the normal event loops and execution, so when you set a global variable with an asynchronous response, there's no way for JavaScript to "know" when it'll get there.
First I would like to thank every one who tried to help me .The answer is to use a parameter that would work as an interface in java to fire a function inside another function or a method to be fired inside other method .
/**
*This is a constructor of javascript firing a server side PHP script.
*
* #param {Object} filePath PHP file path
*/
var AjsToPHP = function(filePath){
this.filePath = filePath;
};
/**
*
* Firing server side PHP script and return respond as an array.
* #param {Object} data Input an array of object to go as POST command.
* #param {Object} response An interface function to return the respond value.
*/
AjsToPHP.prototype.PHP_PROCESS_RETURN = function(data,response){
var PHP_RETURNS= {};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: this.filePath, //Relative or absolute path to response.php file
data: data,
success: function(data) {
for (x in data) {
PHP_RETURNS[x] = data[x];
}
response(PHP_RETURNS);
}
});
};
/**
*
* Firing server side PHP script and return respond OK if it success.
* #param {Object} data Input an array of object to go as POST command.
* #param {Object} response An interface function to return the respond value.
*/
AjsToPHP.prototype.PHP_PROCESS = function(data,response){
var PHP_RETURNS= "";
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: this.filePath, //Relative or absolute path to response.php file
data: data,
success: function(data) {
PHP_RETURNS= "ok";
response(PHP_RETURNS);
}
});
};
An example
<script src="jsToPHP.js"></script>
<script src="js/jquery-1.8.2.min.js"></script>
$("document").ready(function(){
var data = {
"action": "test",
"Name" :"abdulla"
};
var obj = new AjsToPHP("response.php");
obj.PHP_PROCESS_RETURN(data,function(PHP_RESPONE){
alert('inside '+PHP_RESPONE['json']);
});
obj.PHP_PROCESS(data,function(PHP_RESPONE){
alert(PHP_RESPONE);
});
The response.php script
<?php
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //This is how we are able to create different function according to different function call
case "test": test_function(); break;
}
}
}
function test_function(){
//this a correct way of creating an associative array.
$name = $_POST["Name"];
$return["name"] = $name;
$return["favorite_beverage"] = "Coke";
$return["favorite_restaurant"] = "McDonald's";
$return["json"] = json_encode($return);
//return data to javascript
echo json_encode($return);
}
?>

Get value from php function to 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);

creating query from data recived from javascript via ajax

I have the following javascript:
function update_number_of_adds_found(field_dropdown, selected_value) {
selected_value="";
for(i=0; i<document.submitadd.elements.length; i++){
if(document.submitadd.elements[i].value !='' && document.submitadd.elements[i].value != 'Αναζήτηση' && document.submitadd.elements[i].checked !=''){
selected_value += (document.submitadd.elements[i].name +'-' + document.submitadd.elements[i].value +' ');
}
}
var result5 = $.ajax({
'url': '<?php echo site_url('search/findNumberOfAdds'); ?>/' + selected_value,
'async': false
}).responseText;
$('#totalNumOfAdds').empty();
$("#totalNumOfAdds").append(result5);
}
This script send the data in the following format:
addtypeid-1%20isnew-1%20geographicareaid-3
I am a bit restriced in which symbols i can use, because I am using codeigniter, and if I use & for example i get message that i use dissalowed characters in my url.
My question is how can i transform this data in the format $key['fieldname'] = $value['fieldvalue'] so i can built my where clausule?
I was trying something with explode or replace, but without success so far. Any help will be deeply appreciated.
Regards, John
Just following up on my comment above ... You can try something like this ... I haven't tested it but should give you ideas to how to go about ...
jQuery('.submit').click(function(){
var str = $("#myForm").serialize();
str += '&serialize=' + encodeURIComponent(str);
str += '&action=myformsubmit';
jQuery.ajax('phpscripturl.php', {
method: 'POST',
data: str,
success: function(response) {
alert('Got this from the server: ' + response);
},
beforeSend: function(){
alert('Sending...');
}
});
return false;
});
By serializing the form inputs with jQuery's serialize you create a string like:
a=1&b=2&c=3&d=4&e=5&postID=10
So you can fetch this serialized data as
$data = $_POST['serialize'];
foreach($data as $key => $value) {
if($value == '') continue; //skip empty values as per your request
//else save in db etc ...
}
Build an JSON object then Stringify and post it in one variable. Then use json_decode($_POST['key']) to create a PHP object and can access the values easily.
In JS
var ValueToSend = new Object();
ValueToSend.field1 = value1;
var postString = JSON.stringify(ValueToSend)
In PHP
$Object = decode_json($_POST['key']);

Categories

Resources