I wish to extract one variable by one variable from my json file. My goal is to use this variable in php, to be able to do mysql query for exemple.
So my json file is here: pages/getRank-classic.php?idstart=0
[
{"rank":1,"id":"111","site_name":"test1","site_vip":"No","boost":"0","site_banner":"test.png","site_banner_wallrank":"","site_pointstotaux":"5044","site_motclef1":"Pvp\/Fac","site_motclef2":"Skyblock","site_motclef3":"Cr\u00e9atif","site_motclef4":"Hunger-Games","site_motclef5":"SKywars\/Mini-Gam","site_presentationvideo":"3TGjebmNOfs"},
{"rank":2,"id":"222","site_name":"test2","site_vip":"No","boost":"0","site_banner":"test.jpg","site_banner_wallrank":"","site_pointstotaux":"4114","site_motclef1":"hunger","site_motclef2":"games","site_motclef3":"pvp","site_motclef4":"survival","site_motclef5":null,"site_presentationvideo":"3TGjebmNOfs"}
]
I am trying to use it in include like:
<script type="text/javascript" >
$.ajax({
type: 'POST',
dataType: 'json',
url: '/pages/getRank-classic.php?idstart=0',
data: data,
cache: false,
success: function(test) {
alert(test.id);
alert(test.rank);
}
});
</script>
So how I can do it please?
Since it is an array of json, you need to specify the index too.
test[0].id
Also you can iterate through the object using this way,
var data = [{
"rank": 1,
"id": "111",
"site_name": "test1",
"site_vip": "No",
"boost": "0",
"site_banner": "test.png",
"site_banner_wallrank": "",
"site_pointstotaux": "5044",
"site_motclef1": "Pvp/Fac",
"site_motclef2": "Skyblock",
"site_motclef3": "Cr\u00e9atif",
"site_motclef4": "Hunger-Games",
"site_motclef5": "SKywars/Mini-Gam",
"site_presentationvideo": "3TGjebmNOfs"
}, {
"rank": 2,
"id": "222",
"site_name": "test2",
"site_vip": "No",
"boost": "0",
"site_banner": "test.jpg",
"site_banner_wallrank": "",
"site_pointstotaux": "4114",
"site_motclef1": "hunger",
"site_motclef2": "games",
"site_motclef3": "pvp",
"site_motclef4": "survival",
"site_motclef5": null,
"site_presentationvideo": "3TGjebmNOfs"
}];
$(data).each(function () {
alert(this.id);
});
You can fetch the json using the ajax, then in the success event, put this code like,
$.ajax({
type: 'POST',
dataType: 'json',
url: '/pages/getRank-classic.php?idstart=0',
data: data,
cache: false,
success: function(test) {
$(test).each(function () {
alert(this.id);
});
}
});
I finally used php like that =>
<?php
$jsonlink = '/pages/getRank-classic.php?idstart=0';
$json = file_get_contents($jsonlink);
$link = mysql_connect('localhost', 'database', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('database', $link);
$result = json_decode($json);
foreach($result as $key => $value) {
if($value) {
mysql_query("UPDATE `database`.`sites` SET `site_rank` = '$value->rank' WHERE `sites`.`site_id` = '$value->id'");
}
mysql_close;
}
?>
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');
}
});
});
I'm able to convert my data into JSON format in php and while sending that data to Ajax call, I'm not able to get the details. In fact first the length of Json data shows 87, where it is actually 2.
My php code is
// credentials of MySql database.
$username = "root";
$password = "admin";
$hostname = "localhost";
$data = array();
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("Angular",$dbhandle)
or die("Could not select Angular");
//execute the SQL query and return records
$result = mysql_query("SELECT id,name,password FROM User");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
$id = $row{'id'};
$name = $row{'name'};
$password = $row{'password'};
$data[] = array('id' => $id, 'name' => $name, 'password' => $password);
}
echo json_encode($data);
Output it shows is
[
{
"id": "1",
"name": "Rafael",
"password": "rafael"
},
{
"id": "2",
"name": "Nadal",
"password": "nadal"
}
]
My Ajax call is
$.ajax({
type: "GET",
url: "ListUsers.php",
success: function (dataCheck) {
console.log(dataCheck.length);
for(index in dataCheck) {
/*
console.log("Id:"+dataCheck[index].id);
console.log("Name:"+dataCheck[index].name);
console.log("Password:"+dataCheck[index].password);*/
}
},
error: function () {
alert("Error");
}
});
Please let me know if there is any thing wrong in my code
set the dataType to 'JSON' and you are all set:
$.ajax({
type: "GET",
url: "ListUsers.php",
success: function (dataCheck) {
/* ... */
},
error: function () {
alert("Error");
},
dataType: 'JSON'
});
The dataCheck inside success() is a string. You must convert it like this:
var data = $.parseJSON(dataCheck);
Now you can use it in you for loop like
data.forEach(function(item){
console.log(item.name)
});
This should be your Ajax call:
$.ajax({
type: "GET",
url: "ListUsers.php",
success: function (dataCheck) {
var data = $.parseJSON(dataCheck);
$(data).each(function(item){
console.log(item.name);
});
},
error: function () {
alert("Error");
}
});
I am trying to display a JSON object query from a database, the JSON object I receive seems to be correct:
{
"cols": [
{
"id": "A",
"label": "Date",
"type": "string"
},
{
"id": "B",
"label": "User",
"type": "string"
},
{
"id": "C",
"label": "Cement Brand",
"type": "string"
},
{
"id": "D",
"label": "Volume",
"type": "string"
},
{
"id": "E",
"label": "Type",
"type": "string"
}
],
"rows": [
{
"c": [
{
"v": "08-06-2013"
},
{
"v": "razee.hj#gmail.com"
},
{
"v": "Muthana"
},
{
"v": "27"
},
{
"v": "Local Plant"
}
]
}
]
}
but there seems to be a problem with the php file I query data from but I can't find the mistake.
This is the dataTableViewDaily.php file
<?php
$selectQuery = 'SELECT * FROM competitive_daily_volume';
$table = array();
$table['cols'] = array(
array("id"=>"A","label"=>"Date","type"=>"string"),
array("id"=>"B","label"=>"User","type"=>"string"),
array("id"=>"C","label"=>"Cement Brand","type"=>"string"),
array("id"=>"D","label"=>"Volume","type"=>"string"),
array("id"=>"E","label"=>"Type","type"=>"string")
);
$rows = array();
$result = mysql_query($selectQuery);
while($row = mysql_fetch_assoc($result)){
$temp = array();
$temp[] = array("v"=> $row['Date']);
$temp[] = array("v"=> $row['UserId']);
$temp[] = array("v"=> $row['CementBrand']);
$temp[] = array("v"=> $row['VolumeBGLP']);
$temp[] = array("v"=> $row['Type']);
$rows[] = array("c"=> $temp);
}
$table['rows'] = $rows;
$jsonObj = json_encode($table);
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
echo $jsonObj;
?>
And this is the javascript file:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['table']});
</script>
<script type="text/javascript">
function drawVisualization() {
// var jsonData = null;
var jsonData = $.ajax({
url: "php/DailyVolume/dataTableViewDaily.php", // make this url point to the data file
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
// Create and draw the visualization.
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, null);
}
google.setOnLoadCallback(drawVisualization);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="table"></div>
</body>
</html>
I have been working on this for quiet long time and I can't find what I am missing, would appreciate any kind of comments.
The problem is this:
var jsonData = $.ajax({
url: "php/DailyVolume/dataTableViewDaily.php", // make this url point to the data file
dataType: "json",
async: false
}).responseText;
Change it to:
var jsonData;
$.ajax({
url: "php/DailyVolume/dataTableViewDaily.php", // make this url point to the data file
dataType: "json",
async: false,
success:function(data){
//get data in your callback
jsonData = data;
}
});
Or use a recommended approach with promise and avoiding async: false:
$.ajax({
url: "php/DailyVolume/dataTableViewDaily.php", // make this url point to the data file
dataType: "json",
}).done(function(jsonData){
var data = new google.visualization.DataTable(jsonData);
// Create and draw the visualization.
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, null);
});
Need to change this
var jsonData = $.ajax({
url: "php/DailyVolume/dataTableViewDaily.php", // make this url point to the data file
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
to this
$.ajax({
url: "php/DailyVolume/dataTableViewDaily.php", // make this url point to the data file
dataType: "json",
async: false,
success : function(response){
var data = new google.visualization.DataTable(response);
// other code
}
});
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.