I have this script:
<script type="text/javascript">
jQuery(function($) {
var newsList = $('.handsontable');
function updateNews(){
newsList.html("Loading…");
$.ajax({
url: "<?php echo $this->createUrl('data')?>",
cache: false,
success: function(data) {
//alert(data);
newsList.html(JSON.parse(data));
},
});
}
updateNews();
});
which returns a valid json:
{
"score": [
{
"player_fullname": "Alex",
"game_id": "78",
"player_id": "1"
},
{
"player_fullname": "George",
"game_id": "78",
"player_id": "2"
},
{
"player_fullname": "Nick",
"game_id": "78",
"player_id": "3"
},
{
"player_fullname": "John",
"game_id": "78",
"player_id": "4"
},
{
"player_fullname": "Steve",
"game_id": "78",
"player_id": "5"
}
]
}
I want now to convert it into array. I tried JSON.parse(data), but it doesn't return anything. What am I doing wrong? Please help.
PS. I'm using Yii, this code is in a view, and I need to convert this data into array so that I can use it with handsontable api.
First, add a dataType to your AJAX call, set it to 'json' and it will automatically convert the data on re-entry. Now, simply set the data in your success
success: function(data) {
var myArray = data.score;
}
#tymeJV is correct but if you REALLY need an array you can do this
var players = $.parseJSON(data);
Related
I am having trouble sending $_POST data via jQuery Ajax. I have read over everything I can find regarding the matter and still I am getting nowhere. I have even gone back to very basic data and still nothing, the JSON data has been validated using the JSON validate site. For the life of me I cannot echo/print_r/var_dump or get access to any data.
My JavaScript:
$('#updateJSON').click(function(){
var content = [{
"id": 21,
"children": [{
"id": 196
}, {
"id": 195
}, {
"id": 49
}, {
"id": 194
}]
}];
var someText = "someText";
$.ajax({
type: 'POST',
url: 'test.php',
data: {data: content},
cache: false,
success: function(){
alert("success");
console.log(content);
window.location = "test.php";
},
error:function(){
alert('ajax failed');
}
});
});
My PHP:
<?php
if(isset($_POST['data'])) {
$json = stripslashes($_POST['data']);
var_dump(json_decode($json, true));
} else {
echo "No Data";
}
?>
So I do get the alert("success"), and then get redirected to test.php
once at test.php I get the echo "No Data".
Thanks in advance for any help with this issue.
The reason is you are using window.location to redirect to the PHP file (without any post data) instead of posting the form on test.php.
You should either post the form without ajax on test.php.
Or use the response from test.php in your success function.
$('#updateJSON').click(function(){
var content = [{
"id": 21,
"children": [{
"id": 196
}, {
"id": 195
}, {
"id": 49
}, {
"id": 194
}]
}];
var someText = "someText";
$.ajax({
type: 'POST',
url: 'test.php',
data: {data: content},
cache: false,
success: function(response){
alert("success");
console.log(response);
//window.location = "test.php";
},
error:function(){
alert('ajax failed');
}
});
You are passing data as a string to ajax file. Please use JSON.stringify(conten) to pass data as a json format in ajax file.
use
data: {data: JSON.stringify(content)}
in place of
data: {data: content}
Use:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
Then access each field as follows:
$field1 = #$request->field1Name;
$field2 = #$request->field2Name;
etc..
EDIT:
Well, the first part of the answer is still valid.
I've tried your code and slightly modified it on my machine, and i was able to access the whole data as you will see below:
Javascript: removed the square brackets from the outside of your JSON and removed the curly brackets from the 'data' part of the ajax since they are not necessary
as you can see, i've also added the "data" to the success function so i can debug the response from test.php better
$(document).ready(function(){
$('#updateJSON').click(function(){
var content = {
"id": 21,
"children": [{
"id": 196
}, {
"id": 195
}, {
"id": 49
}, {
"id": 194
}]
};
var someText = "someText";
$.ajax({
type: 'POST',
url: 'test.php',
data: JSON.stringify(content),
cache: false,
success: function(data){
alert(data);
console.log(content);
},
error:function(){
alert('ajax failed');
}
});
});
});
PHP:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$field1 = #$request->id;
echo $field1;
and $field1 is echoed as "21", the correct answer
You can apply this to your code and check also.
Thanks everyone for the help I have managed to figure it out with the help of each of you.
I needed to create in the test.php file a, $json = array(), and then populate the array, $json[] = json_decode($_POST['data']);
that then allowed me to place the contents in a JSON file.
here is the php code:
<?php
$json = array();
if($_POST['data']) {
$json[] = json_decode($_POST['data']);
file_put_contents("../JSON/test.json",json_encode($json));
} else {
echo "No Data";
}
?>
and as long as the file "JSON/test.json" exists then it will write the JSON passed from the JS.
I would like to note:
without the JSON.stringify(content); the data is NULL so thank you # Rahul Patel for making sure this was being applied.
the JSON data is valide according to the JSON validate site.
also just for keeps sake the JS code:
$('#updateJSON').click(function(){
var content = {
"id": 21,
"children": [{
"id": 196
}, {
"id": 195
}, {
"id": 49
}, {
"id": 194
}]
};
$.ajax({
type: 'POST',
url: 'test.php',
data: {data: JSON.stringify(content)},
cache: false,
success: function(){
alert("JSON Updated");
},
error:function(){
alert('ajax failed');
}
});
});
Forgive me, I am still learning php and jquery. I am trying to save changes to a json file from data attributes.
I have a .json file below
[{
"name": "test1",
"value": "1",
"ID": ""
},
{
"name": "test1",
"value": "1",
"ID": ""
},
{
"name": "test2",
"value": "1",
"ID": ""
}]
I load the file like this:
$str_data = file_get_contents("data.json");
$data = json_decode($str_data, true);
foreach($data as $key => $val)
echo "<li><a data-num='". $val['value'] ."'>". $val['value'] ."</a></li>";
I can change the data attributes like this:
$('li a').click(function(e) {
e.preventDefault();
var value = +$(this).attr("data-num");
console.log(value);
value = value + 1;
console.log(value);
$(this).attr('data-num', value);
$(this).text(value);
});
This is were I'm stuck. I can I save/update the .json file with the new values based upon the updated data attributes?
$("#submit").click(function() {
$.ajax({
type: 'POST',
url: 'save_to_json.php',
success: function(data){
// do something on success
},
error: function(){
// do something on error
}
});
Working a Project here and I need some help. I have a php page and an html page, trying to pass the username of the php into a DataTable that is in my html file. The code that I have for each is:
PHP is below:
public function __construct(Guard $auth)if (Auth::check() ||Auth::attempt()) {
$auth_id = Auth::user()->id;}
My HTML portion is the following:
var table = $('#example').DataTable( {
// Makes one continuous line
"autoWidth": false,
// How many rows to return
"pageLength": 25,
// Setup the search box with the current username to filter the values on the screen - jsg 2/12/2016
"search": {
"search": $('auth')
}, dom: "Bfrtip",
ajax: "../php/staff.php",
columns: [
{
data: null,
defaultContent: '',
className: 'select-checkbox',
orderable: false
},
{ data: "instructor", visible: false },
{ data: "first_name" },
{ data: "last_name" },
{ data: "category" },
{ data: "Metric_text" },
{ data: "response_value" },
{ data: "fkey_course_id", visible: false },
{ data: "course_code" },
{ data: "course_number" },
{ data: "course_section"}
],
My Question is how can I get $auth_id into the search portion of the HTML coding. As you can see I've tried this with $('auth') but its giving me an object error. If I trying a name like "search": "Test" then test populates and it works. Basically I want to pass the username into the search box of the DataTable so it ill show only the usernames rows.
you can use Ajax.
The code looks like this:
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "scripts/ids-objects.php",
"columns": [
{ "data": "first_name" },
{ "data": "last_name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "start_date" },
{ "data": "salary" }
]
} );
} );
Look at this sample.
Hope it can help you.
I am attempting to return a json encoded array to JS from PHP and i've done so many times before but now i'm getting a weird error. I am successfully getting the data and it's displaying the array in chrome. However, I cannot get it to enter the AJAX success function if I specify the dataType: 'json'. If I remove the dataType and use var parsed = JSON.parse(data); it will enter the success function but it will throw an unexpected type error. Please help.
Chrome output:
[
{
"fullURL": "https://lh6.googleusercontent.com/--ZKG_L-SA9c/UgqECNqP4II/AAAAAAAAA2I/i5nCa3CvKqM/s912/2010raptor_firstdrive002_opt.jpg",
"thumbURL": "https://lh6.googleusercontent.com/--ZKG_L-SA9c/UgqECNqP4II/AAAAAAAAA2I/i5nCa3CvKqM/s128-c/2010raptor_firstdrive002_opt.jpg",
"location": "",
"caption": "",
"tags": "",
"program_instance_id": "a0Ji0000001pPO6EAM"
},
{
"fullURL": "https://lh3.googleusercontent.com/-kyUg7_Rul90/UgqEDIu4DhI/AAAAAAAAA2Q/WF0BAEI7smo/s912/220px-Microchip_PIC24HJ32GP202.jpg",
"thumbURL": "https://lh3.googleusercontent.com/-kyUg7_Rul90/UgqEDIu4DhI/AAAAAAAAA2Q/WF0BAEI7smo/s128-c/220px-Microchip_PIC24HJ32GP202.jpg",
"location": "",
"caption": "",
"tags": "",
"program_instance_id": "a0Ji0000001pPO6EAM"
}
]
PHP
$arr = array();
foreach($photoURLS as $photo)
{
$arr[] = $photo;
}
}
echo json_encode($arr);
JS
$.ajax
({
async: "false",
type: 'POST',
data: {action: 'var1', albumName: 'var2'},
dataType: 'json',
url: '/controller/function',
success: function(data)
{
//alert($.isArray(data));
$.each(parsed, function(i, index) {
alert(index.fullURL);
});
}
});
So I worked the code back and think this solution might work for you.
$.ajax({
async: "false",
type: 'POST',
data: {
action: 'var1',
albumName: 'var2'
},
dataType: 'json',
url: '/controller/function',
success: function(data) {
$.each(data, function(index, element) {
console.log(index);
console.log(element.fullURL);
console.log(element);
});
}
});
I can't test the ajax event however I have tested out the json you provided with the each loop and it seams to work. LINK TO FIDDLE
var data = [{
"caption": "",
"fullURL": "https://lh6.googleusercontent.com/--ZKG_L-SA9c/UgqECNqP4II/AAAAAAAAA2I/i5nCa3CvKqM/s912/2010raptor_firstdrive002_opt.jpg",
"location": "",
"program_instance_id": "a0Ji0000001pPO6EAM",
"tags": "",
"thumbURL": "https://lh6.googleusercontent.com/--ZKG_L-SA9c/UgqECNqP4II/AAAAAAAAA2I/i5nCa3CvKqM/s128-c/2010raptor_firstdrive002_opt.jpg"
}, {
"caption": "",
"fullURL": "https://lh3.googleusercontent.com/-kyUg7_Rul90/UgqEDIu4DhI/AAAAAAAAA2Q/WF0BAEI7smo/s912/220px-Microchip_PIC24HJ32GP202.jpg",
"location": "",
"program_instance_id": "a0Ji0000001pPO6EAM",
"tags": "",
"thumbURL": "https://lh3.googleusercontent.com/-kyUg7_Rul90/UgqEDIu4DhI/AAAAAAAAA2Q/WF0BAEI7smo/s128-c/220px-Microchip_PIC24HJ32GP202.jpg"
}];
$.each(data, function (index, element) {
console.log(index);
console.log(element.fullURL);
});
also good news is that your json is 100% valid so what is being passed back seams correct. Hope this helps
Maybe you need to send the correct HTTP header with your response.
See here: https://stackoverflow.com/questions/267546/correct-http-header-for-json-file
The variable parsed at your $.each function is not defined. you should use data instead of parsed as data is the variable at your success callback function.
$.each(data, function(i, index) {
alert(index.fullURL);
});
I'm using jsTree 1.0. And have this code :
$(document).ready(function () {
$("#folders_tree").jstree({
"core": {
"initially_open": ["root"]
}, "html_data": {
"data": '<?= $folders; ?>'
}, "themes": {
"theme": "default",
"dots": true,
"icons": true,
"url": "<?= Yii::app()->request->baseUrl ?>/css/jstree/themes/default/style.css"
}, "contextmenu": {
"items": {
"create": {
"label": "Create",
"action": function (obj) {
this.create(obj);
}, "_disabled": false,
"_class": "add",
"separator_before": false,
"separator_after": false,
"icon": false
}, "rename": {
"label": "Rename",
"action": function (obj) {
this.rename(obj);
}, "_disabled": false,
"_class": "rename",
"separator_before": false,
"separator_after": false,
"icon": false
}, "remove": {
"label": "Delete",
"action": function (obj) {
this.remove(obj);
}, "_disabled": false,
"_class": "delete",
"separator_before": true,
"separator_after": false,
"icon": false
}, "ccp": false
}
},
"plugins": ["themes", "html_data", "ui", "crrm", "contextmenu"]
});
/* Callbacks */
var folders = $("#folders_tree");
folders.bind("create.jstree", function (e, data) {
var parent_id = data.rslt.parent[0].id;
var name = data.rslt.name;
var node = data.args[0];
var dataArray = {
"ref_folder": parent_id,
"name": name
};
var dataString = JSON.stringify(dataArray);
$.ajax({
type: 'POST',
url: '<?= Yii::app()->createUrl('
ajax / createfolder ') ?>',
data: {
data: dataString
}, success: function (jdata) {
var json_data = JSON.parse(jdata);
// Here's! This code is not working. Id is not set.
$(node).attr("id", json_data.new_id);
}, dataType: 'text'
});
});
});
$(node).attr("id", json_data.new_id) // this code is not working.
I'm stuck on this :( How can I set this id?
The node variable must be declared as :
var node = data.rslt.obj;
And called as :
node.attr("id", json_data.new_id);
I would do alert(jdata) in the success callback.
Be sure the server is returning safe JSON and that the actual new_id attribute exists.