Converting data from JSON to JavaScript array - javascript

I'm having a problem with converting data sended from "naloga3.php" .
How can i convert from JSON to array.
JAVASCRIPT
<script>
function shrani(){
var formData = {naslov: document.getElementById("naslov").value,
besedilo: document.getElementById("besedilo").value,
datum:0
};
$.ajax({
url : "naloga3.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
$('#zapisi').append('<a>'+data+'</a></br>');
var x = eval("(" + data + ")");
for(var i=0;i<x.length;i++)
{
$('#zapisi').append('<a>'+x.length+'</a></br>');
}
},
error: function (jqXHR, textStatus, errorThrown)
{
$('#zapisi').append('<a>Napaka</a></br>');
}
});
}
</script>
naloga3.php
<?php
$file="podatki.txt";
$podatki=file_get_contents($file);
$izpolje=array();
$izpolje= json_decode($podatki,true);
$polje=$_POST;
$polje['datum']=date('H:i:s');
if($izpolje!=null)
{
array_unshift($izpolje,$polje);
file_put_contents($file,json_encode($izpolje));
}else
{
$tr=array();
array_unshift($tr,$polje);
file_put_contents($file,json_encode($tr));
}
$podatki=file_get_contents($file);
echo json_encode($izpolje);
?>
My output
[{"naslov":"d","besedilo":"d","datum":"16:07:05"},{"naslov":"dddd","besedilo":"d","datum":"15:51:41"},{"naslov":"d","besedilo":"d","datum":"15:51:33"},{"naslov":"d","besedilo":"d","datum":"15:51:30"},{"naslov":"d","besedilo":"d","datum":"15:51:26"}]

What you need to do is set the dataType of your ajax response to json, then you need to iterate the returned object and append within the $.each() loop.
$.ajax({
url : "naloga3.php",
type: "POST",
data : formData,
dataType: "json", // jQuery will now parse the returned data and return an object
success: function(data, textStatus, jqXHR)
{
$.each(data, function(i,obj){
//now you can acess navlos, besedilo and datum
$('#zapisi').append(obj.naslov+'</br>');
$('#zapisi').append(obj.besedilo+'</br>');
$('#zapisi').append(obj.datum+'</br>');
});
},
error: function (jqXHR, textStatus, errorThrown)
{
$('#zapisi').append('<a>Napaka</a></br>');
}
});

Related

Fetch Json data in local storage using loop on each json sub object

I want to store data locally for each sub object returned in json format like this -
key - name sectionType+number of section type , value - this object
My existing JS code:
function syncAllSections_4(){
user_sections= loggeduser_array.id;
console.log(user_sections);
var dict_4 = { userId: user_sections };
$.ajax({
url: 'http://funiks.com/adminv7/offline-api/listSections.php',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(dict_4),
})
.done(function(data, textStatus, jqXHR) {
if(data.status=="SUCCESS") {
localStorage.setItem("sections",JSON.stringify(data.sections));
//console.log(JSON.parse(localStorage.getItem("sections")));
var sections_array = [];
sections_array = JSON.parse(localStorage.getItem("sections"));
}
}).fail(function(jqXHR, textStatus, errorThrown) {
alert("error");
});
}
The data format returned in Json is:
https://pastebin.com/4XBR23ua
This is how I want to save it in local storage:
It seems that "sections" is already an array, so you shouldn't stringify it for array length. Also, the solution is quite straightforward (not tested but should work):
function syncAllSections_4(){
user_sections= loggeduser_array.id;
console.log(user_sections);
var dict_4 = { userId: user_sections };
$.ajax({
url: 'http://funiks.com/adminv7/offline-api/listSections.php',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(dict_4),
})
.done(function(data, textStatus, jqXHR) {
if(data.status=="SUCCESS") {
data.sections.forEach(section)=>{
localStorage.setItem("SectionTypes"+section.sectionType,JSON.stringify(section));
})
}
}).fail(function(jqXHR, textStatus, errorThrown) {
alert("error");
});
}

How to get data value using this code?

I used this below code to post data to server,its working fine,but How do I get values of data.Suppose server will send name and surname of a persion alert message showing these values but how do I get in variable...please help...
var data = {"data":{"app_name":"hansel","device_id":"123456"}};
//data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "http://15.27.0.180/cr/z0501/getconfig", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$.each(data, function(key, value){
$.each(value, function(key, value){
//alert(value)
alert("key" +key +""+value)
var servervalues=value;
//alert(servervalues+servervalues);
});
});
}
});
return false;
});
Just use jqXhr object
$.ajax({
//...
success: function(data, textStatus, xhr) {
console.log(xhr.status);
},
complete: function(xhr, textStatus) {
console.log(xhr.status);
}
});

Add top level JSON to Javascript object

does anyone know how to append a top level json to an existing object?
this is what I have:
var url = "http://domain.com/gettxt";
$.ajax({
url: url,
dataType: "json",
success: function (data, textStatus, jqXHR) {
rootData = data;
renderView();
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error" + errorThrown)
}
});
At this point, data contains the following:
[{"id":1,"title":"Johnson"}]
And I need it to be like this:
{ "record": [ {"id":1}, {"title":"Johnson"} ] }
In other words:
rootData = "{ "record":" + data + "}";
Does anyone know how can I do the above? Unfortunately adding the top level before it comes to Javascript is not an option, thanks.
You can directly add object type like this,
rootData = { record: data };
Your final code will be
var url = "http://domain.com/gettxt";
$.ajax({
url: url,
dataType: "json",
success: function (data, textStatus, jqXHR) {
rootData = { record: data };
renderView();
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error" + errorThrown)
}
});
You can just use an object literal to do this:
rootData = { record: data };
So your code would look like this:
success: function (data, textStatus, jqXHR) {
rootData = { record: data };
renderView();
},
try this
var arr = [{"id":1,"title":"Johnson"}];
var obj ={};
obj.record = arr;
console.log(obj);
a = [{"id":1,"title":"Johnson"}]
root = {record: a}

php - return the value of an ajax post back to javascript

I'm trying to test the successful submission of data from javascript to a php file by having that php file return the results of the javascript post back to javascript. I'm getting a successful response in the ajax post, but the data is an empty string. How do I find out what data was posted? Here's my code:
JAVASCRIPT:
var benefitsArray = ["someData","someOtherData"];
$('#drop-submit').on('click',function(){
if (benefitsArray.length > 0){
var formData = { "benefits" : benefitsArray };
debugger;
$.ajax({
url : "dd-receiver.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
console.log(data); //result is "";
debugger;
//data - response from server
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log('failure');
}
});
}
});
PHP:
<?php
echo $_POST["benefits"]
?>
UPDATE:
I got a response by, in the php code, doing:
echo json_encode($_POST['benefits']);
but the problem is that in the javascript, if I log the data, the result is
"["someData","someOtherData"]" (a string)
and not
["someData","someOtherData"] (an array)
how do I get it to return an array and not a string?
You're not parsing the JSON being sent to you.
You can make jQuery do this for you by adding dataType: 'JSON' to your $.ajax options...
$.ajax({
dataType: 'JSON',
url : "dd-receiver.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR) ...
Or manually with JSON.parse:
success: function(data, textStatus, jqXHR) {
benefits = JSON.parse(data);
...
}

Unable to access json data retrieved from php page using jquery $.ajax

How to access this json data in JavaScript.
when I alert it the result is undefined
Here is jQuery code
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Here is the problem
alert(data[0]['Result']);
}
});
This is PHP code
$data=array($no);
for($i=0;($i<$no && ($row=mysql_fetch_array($result)));$i++)
{
$data[$i]=array();
$data[$i]['Result'] = $row['Result'];
$data[$i]['TestCode'] = $row['TestCode'];
$data[$i]['TestStatus'] = $row['TestStatus'];
$data[$i]['SrNo'] = $row['SrNo'];
}
$data1=json_encode($data);
echo $data1;
exit;
I have tested the PHP file independently,
The json data is output as follows:
[{"Result":"1","TestCode":"22","TestStatus":"0","SrNo":"1"},{"Result":"1","TestCode":"23","TestStatus":"1","SrNo":"2"}]
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = jQuery.parseJSON(data)
alert(data[0]['Result']);
}
});
You can access to your data by doing
data[0].Result
It's an Object, not an array.
so data[0]['Result'] it's not the proper way
EDIT:
Since you have more objects, you have to do a loop this way:
$.each(data, function(key, val){
console.log(val.Result);
console.log(val.TestCode);
//...
});
When you see something like
{
"foo":"bar",
...
}
you can access to it the same way as above:
name_of_the_object.foo
that will have the value "bar"
Try to add parse JSON. I have added. Now it may be work.
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = $.parseJSON(data)
alert(data[0]['Result']);
}
});

Categories