How to convert array php to javascript array - javascript

I have some problem about parsing array php to javascript array, I use json_encode but I get error like
Uncaught SyntaxError: Unexpected number
This my code :
<?php
$b=array();
$a=array();
$pat = 0;
for($i = 0; $i<15;$i++)
{
if($pat == 5)
{
ini_set('memory_limit', '-1');
array_push($b,$a);
$a = array();
$pat = 0;
}
ini_set('memory_limit', '-1');
array_push($a,$i.'-1');
$pat = $pat +1;
}
?>
$(document).ready(function() {
$('#example').DataTable( {
serverSide: true,
ordering: false,
searching: false,
ajax: function ( data, callback ) {
var out1 = "<?php echo json_encode($b) ?>";
var out = [["0-1","0-2","0-3","0-4","0-5"],["1-1","1-2","1-3","1-4","1-5"]];
console.log(out);
setTimeout( function () {
callback( {
// draw: data.draw,
data: out,
recordsTotal: 5000000,
recordsFiltered: 5000000
} );
});
},
} );
} );
I want result like variable out, what can I do to fix this bug thanks,
and I'm sorry for my bad English

Generally we use rest apis for this kind of work but you can use given code snip in picture for your reference. If you have any specific question, let me know

Related

How return array in function() to javascript on wordpress ajax.php with following code:

it may seem stupid, but i'm in it for a week, help me ...
the "response" in xhr dev-tools chrome does not leave "0", it never returns the array I need ...
Javascript code to get data from wordpress
$(document).on("click", "[data-show-home-list-series]", function () {
var id = $(this).attr("data-show-home-list-series");
$("[data-show-home-list-series]").removeClass("active");
$(this).addClass("active");
var $list = $("#homeSliderSerieList");
$.post("wp-admin/admin-ajax.php", { getHomeSliderSeries: id }, function (html) {
var data = jQuery.parseJSON(html);
if (data.status == "success") {
var listing = data.list;
var lister = [];
for (var i = 0; i < 20; i++) {
var row = listing[i];
lister.push(seriePoster(row.url, row.rating, row.poster, row.title, row.cat, row.episode));
}
$list.parent(".itemsList").addClass("fadingOut");
setTimeout(function () {
$list.html(lister.join(""));
$list.trigger("destroy.owl.carousel");
createItemSlider();
$list.parent(".itemsList").removeClass("fadingOut");
}, 200);
} else {
return false;
}
});
});
PHP file to return data in array json to javascript show results in html.
wp-admin/admin-ajax.php (theme/inc/core/ajax.php)
function getHomeSliderSeries(){
// i Want see that bellow in xhr response to javascript:
//{"status":"success","list":{}}
}
add_action( 'wp_ajax_getHomeSliderSeries', 'getHomeSliderSeries' );
add_action( 'wp_ajax_nopriv_getHomeSliderSeries', 'getHomeSliderSeries' );
My language is not very good, i hope you undestand, thanks atentiton!!
Try ajax callback function in functions.php
function swt_ajax_data() {
$id = isset($_POST['id']) ? $_POST['id'] : '';
// Create an associative array for the response.
$responsedata = array(
'id' => $id,
);
$result = array();
// if need featch the data from the template un comment the bellow five lines and commented the sixth line
//ob_start();
//include('templatepatj');
//$opr_html .= ob_get_contents();
//ob_get_clean();
// $result['data'] = $opr_html;
$result['data'] = $responsedata;// POST array data.
}
return wp_send_json_success($result);
}
}
add_action('wp_ajax_swt_ajax_data', 'swt_ajax_data');
add_action('wp_ajax_nopriv_swt_ajax_data', 'swt_ajax_data');
Localize your script and pass the admin ajax url
// Register the script
wp_register_script( 'ajax-script', 'path/to/myscript.js' );
// Localize the script with new data
$js_array = array(
'ajaxurl' => admin_url('admin-ajax.php'),
);
wp_localize_script( 'ajax-script', 'swtobj', $js_array );
// Enqueued script with localized data.
wp_enqueue_script( 'ajax-script' );
Try Js as like below.
$(document).on("click", "[data-show-home-list-series]", function () {
var id = $(this).attr("data-show-home-list-series");
$("[data-show-home-list-series]").removeClass("active");
$(this).addClass("active");
var $list = $("#homeSliderSerieList");
var data = {
'action': 'swt_ajax_data', 'id': id
};
$.ajax({
url: swtobj.ajaxurl,
type: 'POST',
data: data,
cache: false,
dataType: 'json',
success: function (response, textStatus, jqXHR) {
var response_data = response.data.data;
if (response_data != "" || response_data.length != 0) {
console.log(response_data);
// write your code here
} else {
// write your code here
}
},
});
});
The data you send in $.post is missing an action property. This property is responsible for telling the admin-ajax.php which function that is registered with a wp_ajax_{function_name} hook should be called.
The value in the action property should match the function_name in wp_ajax_{function_name} and wp_ajax_nopriv_{function_name} to be called properly.
Combine the action property with other properties that you want to send to the backend to pass the data that you need to send.
// Set the action and get the id.
var action = 'getHomeSliderSeries';
var id = $(this).attr("data-show-home-list-series");
// Create object to send data to backend.
// This must include an action property with
// the name of the function on the backend.
var postData = {
action: action,
id: id,
example: 'Send any data as a property. You can also nest objects and arrays.'
};
$.post("wp-admin/admin-ajax.php", postData, function(response) {
if (response.status == "success") {
console.log(response);
}
}, 'json'); // Expect JSON from the backend. Now you don't need to parse.
Now on the server side your getHomeSliderSeries should be called. All the other properties (action included) can now be accessed through the global $_POST variable with their corresponding keys.
For a response, create an associative array with the data you want to return. This is the equivalent of an object in JavaScript. Encode the array to JSON and send it back. Now the frontend should see an object as a response.
function getHomeSliderSeries(){
// Get the id from the post request.
$id = isset($_POST['id']) ? $_POST['id'] : null;
$example_string = isset($_POST['example_string']) ? $_POST['example_string'] : null;
// Create an associative array for the response.
$response = array(
'status' => 'success',
'id' => $id,
'example' => $example_string
);
// Return the array as a JSON string.
return json_encode($response);
// Cuts connection by stopping the function.
die();
}
add_action( 'wp_ajax_getHomeSliderSeries', 'getHomeSliderSeries' );
add_action( 'wp_ajax_nopriv_getHomeSliderSeries', 'getHomeSliderSeries' );

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.

Query MySQL via PHP inside JavaScript with time interval [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Basically I want to query MySQL database using an external PHP script. I want this script to be called every 2 seconds. This 2 seconds interval are initiated with a javascript (jquery, flot), which is as follows:
<script type='text/javascript'>
var data = [];
var dataset;
var totalPoints = 50;
var updateInterval = 1000;
var now = new Date().getTime();
function GetData() {
data.shift();
while (data.length < totalPoints) {
var y;
$.ajax({
url: 'current_api.php',
success: function(currentValue){
y = currentValue;
console.log(y);
},
});
var temp = [now += updateInterval, y];
data.push(temp);
}
}
var options = {
...
}
$(document).ready(function () {
GetData();
dataset = [
{ label: "CURRENT READING", data: data }
];
$.plot($("#flot-line-chart"), dataset, options);
function update() {
GetData();
$.plot($("#flot-line-chart"), dataset, options)
setTimeout(update, updateInterval);
}
update();
});
</script>
Currently, Im getting a NULL value at console.log(y);. My PHP script (current_api.php) that handles MySQL queries is as simple as follows:
<?php
require "dbCon.php"; // database credentials
$databaseName = "MAIN";
$tableName = "day"
// OPEN MYSQL DATABASE CONNECTION IN PHP
$dbs = mysql_select_db($databaseName, $con);
// FETCH DATA FROM MYSQL DATABASE
$sql = "SELECT value FROM $tableName ORDER BY id DESC LIMIT 1";
$result = mysql_query($sql);
header('Content-Type: application/json');
while ($row = mysql_fetch_assoc($result)) {
$currentValue = (int) round($row['value']);
}
echo json_encode($currentValue);
// CLOSE THE DB CONNECTION
mysql_close($con);
?>
I'm new with AJAX and does not know if what I'm trying to do is possible. Can someone help me to debug why i'm getting a NULL value? Thanks in advance.
You are calling current_api.php in your ajax script without any data. So there is no query string, no $_GET['dbSelect'] and no database. So your json contains only an undefined variable, NULL.
Apart from that this is not correct, you cannot use escaping functions to clean up a user-provided table name, you need to check it against a whitelist.
Got it!
the problem is the declaration of variable y and the url in $.ajax. All thanks to barmar and jeroen for the hints!
The javascript should be:
<script type='text/javascript'>
var data = [];
var dataset;
var totalPoints = 50;
var updateInterval = 1000;
var now = new Date().getTime();
var y;
function GetData() {
data.shift();
while (data.length < totalPoints) {
$.ajax({
url: 'current_api.php?dbSelect=R9640E5F1E2',
success: function(currentValue) {
y = currentValue;
console.log(currentValue);
},
});
var temp = [now += updateInterval, y];
data.push(temp);
}
}
var options = {
...
}
$(document).ready(function () {
GetData();
dataset = [
{ label: "CURRENT READING", data: data }
];
$.plot($("#flot-line-chart"), dataset, options);
function update() {
GetData();
$.plot($("#flot-line-chart"), dataset, options)
setTimeout(update, updateInterval);
}
update();
});
</script>
where R9640E5F1E2 is the database; and the PHP stays as is. :)
Now.. move on to another problem... Query strings inside javascripts.
$.ajax({
dataType: "json",//insert line: receive data from server to json
url: 'current_api.php?dbSelect=123', //a method
/* a method other
type:"GET",
data:{dbSelect:dbSelect},
url: 'current_api.php',
*/
success: function(currentValue){
y = currentValue[0];///edit code y = currentValue
console.log(y);
},
});

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

Using Javascript with php

I know this question has already been asked a few times, but I'm trying to use javascript with php. I have a file called parsing.php that parses through a xml feed and converts the metadata into JSON Object called "data". The parsing is done using ajax calls with JavaScript and JQuery.
<script src="json2.js" type="text/javascript" language="javascript"></script>
<script type="text/javascript">
$.ajax({
type: 'GET',
url: 'fakeFeed.xml',
dataType: 'xml',
async: false,
success: function(data, textStatus, jqXHR) {
function getRandom(max) {
return Math.floor(Math.random() * max);
}
function getThumbId(small) {
var num = getRandom(15);
if (num == 0) {
num = 1;
}
if (num < 10) {
num = '0' + num;
}
return num.toString();
}
var categories = new Array(); // Array for the categories
var category = {
name : '',
videos: []
};
var data1 = data;
var data = {
categories: []
};
$(data1).find('item').each(function () {
var el = $(this);
var categoryName = el.find('category').text();
var p = categories.indexOf(categoryName);
if( p == -1) {
categories.push(categoryName);
var category = {
name: categoryName,
videos: []
};
for (var j = 0; j<5; j++) {
var video = {
sources: [el.find('media\\:content, content').attr('url')],
thumb : 'images\/thumbs\/thumb' + getThumbId() + '.jpg',
title : el.find("title").text(),
subtitle : el.find("description").text(),
description: ""
}
category.videos.push(video);
}
data.categories.push(category);
}
});
window.data = JSON.stringify(data);
<script>
"<?php
$dataVar = ?> <script type=text/javascript>window.data</script><?php;?>"
"<?php
print_r($dataVar,true);
?>"
The only reason why I need to use javascript and php is because I want to use the "print_r()" function from php which allows me to return the information rather than just printing it to the screen, but unfortunately I can't get it to work. If anybody knows of other alternative or could give some advice that would be greatly appreciated.
Here is what I believe you are trying to achieve, written in PHP:
$dom = new DOMDocument();
$dom->load("fakeFeed.xml");
$data = ["categories"=>[]]; // may need to use array() instead of [] depending on PHP version
foreach($dom->getElementsByTagName('item') as $item) {
$name = trim($item->getElementsByTagName('category')->item(0)->textContent);
if( !isset($data['categories'][$name])) {
$cat = ["name"=>$name,"videos"=>[]]; // again, adjust if you're on an older version
// I'm not entirely sure what you're trying to achieve on this part.
// you seem to be getting the same video five times...
// revise your approach, comment if needed, and I can try to help
// for now, "insert code here"
$data['categories'][$name] = $cat;
}
}
// we were using the name as a key for simplicity, now just take the values
$data['categories'] = array_values($data['categories']);
// done! $data now has your data.
var_dump($data);
If you really want to use this instead of using document.log for JS:
$.ajax({
type: "POST",
url: "some_php.php",
data: JSON.stringify(data);
})
.done(function( msg ) {
document.write(msg);
});
and the some_php.php
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);

Categories

Resources