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
}
});
Related
Have a form on a web page that is processed before to be sended to a PHP script that handle datas with :
$requestData = file_get_contents("php://input");
Datas are sended as JSON Object named "data":
[
{
"label": "Some label",
"value": "Some value"
},
{
"label": "Some label",
"value": "Some value"
},
...
]
Ajax call is make as follow :
$.ajax({
url: "/App/Reserver/Ajax/ajaxcall.php",
type: "POST",
dataType: "json",
processData: false,
data: data,
success: function(data,statut){
console.log("Données : " + JSON.stringify(data));
}
});
When i inspect post parameters in a web browser console, have always :
[object Object]
...
And the response is NULL using :
$requestData = file_get_contents("php://input");
var_dump($requestData);
Even if use :
$requestData = json_decode(file_get_contents("php://input"));
var_dump($requestData);
I'm missing something but don't know what... Not sure of my ajax call, nor my ajax call params.
Thanks for your help
if
data =[
{
"label": "Some label",
"value": "Some value"
},
{
"label": "Some label",
"value": "Some value"
},
...
]
from data:data; from your ajax sintax then
change data:{data:data}
and in the php use the $_POST variable to get the data value:
$data = json_decode($_POST['data']);
var_dump($data);
in the success you do:
success: function(data,statut){
console.log("Données : " +data);
}
Try:
$requestData = file_get_contents("php://input", NULL, NULL);
var_dump($requestData);
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');
}
});
});
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);
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 trying to pass custom values to autocomplete, so:
my custom work value's its based in this question
using a default source like doc's:
$("#inpPesqCli").autocomplete({
source: "ajax/search.php",
minLength: 2,
autoFocus: true
});
firebug returns this (example):
[...
{ "id": "29083", "label": "SOME ONE 2", "value": "SOMEONE WITH LELE" },
{ "id": "19905", "label": "SOME ONE", "value": "SOMEONE WITH LALA"},
...]
work's perfect, results shows up.
when i try to set some custom values:
$("#inpPesqCli").autocomplete({
source: function( request, response ) {
$.ajax({
url: "ajax/search.php",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2,
autoFocus: true
});
firebug return's me the exactly same array result:
[...
{ "id": "29083", "label": "SOME ONE 2", "value": "SOMEONE WITH LELE" },
{ "id": "19905", "label": "SOME ONE", "value": "SOMEONE WITH LALA"},
...]
but, the problem is, when i pass custom calues, the result's dosent shows up.
php:
$type = "C";
$q = strtolower($_GET["name_startsWith"]); // this i change: custom = name_startsWith / default = term
if (!$q) return;
$res = $p->SomeClass($codemp,$q,$type);
$items = array();
while(!$res->EOF){
$items[$res->fields["NOMCLI"]] = $res->fields["CODCLI"];
$res->MoveNext();
}
// below this, i have the php autocomplete default function, if u need, ask then i post.
dont know what i'm missing.
set ajax type = GET , maybe work, by default data send type is POST
$("#inpPesqCli").autocomplete({
source: function( request, response ) {
$.ajax({
url: "ajax/search.php",
dataType: "jsonp",
type : "GET",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 2,
autoFocus: true
});