PHP string to json array - javascript

So basically I'm making cURL request and getting response that looks like this(var_dump):
string(595) "{"user_id":1,"currency":"eur","purchase_packs":{"1":{"amount":500,"allowed_payment_methods":["ideal","paypal","visa","mc"]},"3":{"amount":1000,"allowed_payment_methods":["mc","ideal","paypal","visa"]},"6":{"amount":2500,"allowed_payment_methods":["mc","ideal","paypal"]},"8":{"amount":5000,"allowed_payment_methods":["ideal"]},"9":{"amount":10000,"allowed_payment_methods":["ideal"]}},"payment_methods":{"ideal":{"name":"ideal","allow_recurring":false},"paypal":{"name":"paypal","allow_recurring":false},"visa":{"name":"visa","allow_recurring":false},"mc":{"name":"mc","allow_recurring":false}}}"
What I want is to access it in the JS file like this:
success: function (data) {
alert(data.user_id);
}
But I don't know how to convert(?) it properly.
And my next step(question) after that will be if I can do a for loop for every purchased pack, so I can create button for each one of them
Probably something like this:
var pack;
var packs = data.purchase_packs;
for (pack= 0; pack < packs.length; pack++) {
console.log(packs[pack]);
}

I'm tried to understand your "question"....
In js:
$.post('/some/url',{query: 'somequery'},
function (data) {
try {
data = JSON.parse(data);
} catch (e) {
return false;
}
console.log(data);
});
In PHP:
data = json_decode(rtrim($myJSONEncodedString, "\0"));
if (!empty($data->purchase_packs)
foreach ($data->purchase_packs as $key => $value)
var_dump($value);

After receiving response using cURL, just echo that json string between <script></script> tag.
Then json string will look like:
<script>
var jsondata = {"user_id":1,"currency":"eur","purchase_packs":{"1":{"amount":500,"allowed_payment_methods":["ideal","paypal","visa","mc"]},"3":{"amount":1000,"allowed_payment_methods":["mc","ideal","paypal","visa"]},"6":{"amount":2500,"allowed_payment_methods":["mc","ideal","paypal"]},"8":{"amount":5000,"allowed_payment_methods":["ideal"]},"9":{"amount":10000,"allowed_payment_methods":["ideal"]}},"payment_methods":{"ideal":{"name":"ideal","allow_recurring":false},"paypal":{"name":"paypal","allow_recurring":false},"visa":{"name":"visa","allow_recurring":false},"mc":{"name":"mc","allow_recurring":false}}};
</script>
Then, your javascript code between <script></script>. Like this:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
alert(jsondata.user_id); // return user_id value
jQuery.each(jsondata.purchase_packs, function(i, val) {
alert(val.amount); // return amount
var paymentMethod = val.allowed_payment_methods;
jQuery.each(paymentMethod, function() {
alert(this); // will return all payment gateway method
});
});
</script>
Hope will help!

Related

Java Script getJSON properly not working in laravel 5.+?

Controller
public function getback(Request $request)
{
$chart = DB::table('BirthChart_1')
->where('FileId', 123)
->get();
foreach ($chart as $key ) {
$f[] = [$key->k1,$key->k2,$key->k3,$key->k4,$key->k5,$key->k6,$key->k7,$key->k8,$key->k9,$key->k10];
}
return response()->json($f);
}
javascript
$(document).ready(function() {
$.getJSON("/getback", function(data) {
var items = [];
$.each(data, function(key, val) {
items.push(val);
});
alert(items);
alert(items[0]);
alert(items[1]);
});
});
http://127.0.0.1:8000/getback
Result...
[[3,4,null,null,null,5,null,null,null,null]]
http://127.0.0.1:8000
Result
alert(items); // 3,4,,,,5,,,,
alert(items[0]); // 3,4,,,,5,,,, (here I want 3)
alert(items[1]); // undefined (here ,I want 4)
What is my mistake in here ? or how to correct it properly ?
Just Changed
alert(items[0][1]);
alert(items[0][2]);
I got answer form #charlietfl Thank you sir ..

How to transfer variable from ajax to php and php to ajax with JSON?

I am using laravel 5.0.
I have a controller named pesananController like this:
public function ambilnamakomp(Request $request)
{
$data = DB::table('komputer')->where('id', $idkomp);
$hasil = json_encode($data);
return $hasil;
}
view bookhari.blade.php:
<script type="text/javascript">
var namakomp = "";
var urltemp = "/ambilnamakomp/" + idkomp;
$(document).ready(function () {
$.get(urltemp, function(){
namakomp = jQuery.parseJSON(hasil)
});
});
alert(namakomp);
</script>
routes I like this:
Route::get('/ambilnamakomp/{id}', 'pesananController#ambilnamakomp');
I wanted to take the form of data records in the database using ajax.
I do not understand how to send a variable from php ajax and then process it in JavaScript.
In your laravel code, you can use response helper with json method:
public function ambilnamakomp(Request $request)
{
$data = DB::table('komputer')->where('id', $idkomp);
return (new Illuminate\Http\Response())->json($data);
}
You can get data in your JQuery $.get function like this:
<script type="text/javascript">
var namakomp = "";
var urltemp = "/ambilnamakomp/" + idkomp;
$(document).ready(function () {
$.get(urltemp, function(data){
//data is object from php script
namakomp = data;
});
});
alert(namakomp);
</script>

asynchronous HTTP (ajax) request works in script tag but not in js file

I have this ajax call here in a script tag at the bottom of my page. Everything works fine! I can set a breakpoint inside the 'updatestatus' action method in my controller. My server gets posted too and the method gets called great! But when I put the javascript inside a js file the ajax call doesn't hit my server. All other code inside runs though, just not the ajax post call to the studentcontroller updatestatus method.
<script>
$(document).ready(function () {
console.log("ready!");
alert("entered student profile page");
});
var statusdropdown = document.getElementById("enumstatus");
statusdropdown.addEventListener("change", function (event) {
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
// do something with the returned value e.g. display a message?
// for example - if(data) { // OK } else { // Oops }
});
var e = document.getElementById("enumstatus");
if (e.selectedIndex == 0) {
document.getElementById("statusbubble").style.backgroundColor = "#3fb34f";
} else {
document.getElementById("statusbubble").style.backgroundColor = "#b23f42";
}
}, false);
</script>
Now I put this at the bottom of my page now.
#section Scripts {
#Scripts.Render("~/bundles/studentprofile")
}
and inside my bundle.config file it looks like this
bundles.Add(new ScriptBundle("~/bundles/studentprofile").Include(
"~/Scripts/submitstatus.js"));
and submitstatus.js looks like this. I know it enters and runs this code because it I see the alert message and the background color changes. So the code is running. Its just not posting back to my server.
$(document).ready(function () {
console.log("ready!");
alert("submit status entered");
var statusdropdown = document.getElementById('enumstatus');
statusdropdown.addEventListener("change", function (event) {
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
// do something with the returned value e.g. display a message?
// for example - if(data) { // OK } else { // Oops }
});
var e = document.getElementById('enumstatus');
if (e.selectedIndex == 0) {
document.getElementById("statusbubble").style.backgroundColor = "#3fb34f";
} else {
document.getElementById("statusbubble").style.backgroundColor = "#b23f42";
}
}, false);
});
In the console window I'm getting this error message.
POST https://localhost:44301/Student/#Url.Action(%22UpdateStatus%22,%20%22Student%22) 404 (Not Found)
Razor code is not parsed in external files so using var id = "#Model.StudentId"; in the main view will result in (say) var id = 236;, in the external script file it will result in var id = '#Model.StudentId'; (the value is not parsed)
You can either declare the variables in the main view
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
and the external file will be able to access the values (remove the above 2 lines fro the external script file), or add them as data- attributes of the element, for example (I'm assuming enumstatus is a dropdownlist?)
#Html.DropDownListFor(m => m.enumStatus, yourSelectList, "Please select", new { data_id = Model.StudentId, data_url = Url.Action("UpdateStatus", "Student") })
which will render something like
<select id="enumStatus" name="enumStatus" data-id="236" data-url="/Student/UpdateStatus">
Then in the external file script you can access the values
var statusbubble = $('#statusbubble'); // cache this element
$('#enumStatus').change(function() {
var id = $(this).data('id');
var url = $(this).data('url');
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
....
});
// suggest you add/remove class names instead, but if you want inline styles then
if (status == someValue) { // the value of the first option?
statusbubble.css('backgroundColor', '#3fb34f');
} else {
statusbubble.css('backgroundColor', '#b23f42');
};
});

alert part of AJAX response

I am using JS to submit data without loading the page and it is working fine, on response i am trying to send JSON which looks like this
{"mes":"<div class=\"alert alert-success\">Your goal has been updated.<\/div>","graph_data":"[['07\/9\/2014',500],['07\/8\/2014',900],['07\/7\/2014',1200],['07\/6\/2014',500],['07\/5\/2014',500],['07\/4\/2014',500],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000]]"}
There are two items in the JSON response mes and graph_data. Now how can i make use of graph_data and mes seperately?
If I do this alert(data); this shows the above JSON response
But if I do the following I cant get them to alert seperately.
alert(data.graph_data);
alert(data.mes);
I will really appreciate if anyone can guide me on how to separate the two.
Update
This is the JS i am using to send and retrieve data on click of a button
$('#goalgraphdatasubmit').click(function () {
$('#goalgraphupdateform').submit();
});
$('#goalgraphupdateform').submit(function (e) {
"use strict";
e.preventDefault();
document.getElementById("goalgraphdatasubmit").innerHTML = "saving..";
var post = $('#goalgraphupdateform').serialize();
var action = $('#goalgraphupdateform').attr('action');
$("#holiday_goal_message").slideUp(350, function () {
$('#holiday_goal_message').hide();
$.post(action, post, function (data) {
$('#holiday_goal_message').html(data);
document.getElementById('holiday_goal_message').innerHTML = data;
$('#holiday_goal_message').slideDown('slow');
document.getElementById("goalgraphdatasubmit").innerHTML = "Submit";
alert(data);
if (data == '<div class="alert alert-success">Your goal has been updated.</div>') {
//$('#divGoal').load('dashboard-goals.php');
$("#holiday_goal_message").hide(2000);
updatetestGraph();
}
});
});
});
Use Like
var data = JSON.parse('{"event1":{"title":"My birthday","start":"12\/27\/2011 10:20 ","end":"12\/27\/2011 00:00 "},"event2":{"title":"My birthday again","start":"12\/27\/2011 10:20 ","end":"12\/27\/2011 00:00 "}}');
arr = []
for(var event in data){
var dataCopy = data[event]
for(key in dataCopy){
if(key == "start" || key == "end"){
// needs more specific method to manipulate date to your needs
dataCopy[key] = new Date(dataCopy[key])
}
}
arr.push(dataCopy)
}
alert( JSON.stringify(arr) )
Demo1
Demo2
Sorry cannot comment so have to answer
I have taken your JSON string in a variable here and it gives me proper result
See here
var d = {"mes":"<div class=\"alert alert-success\">Your goal has been updated. <\/div>","graph_data":"[['07\/9\/2014',500],['07\/8\/2014',900],['07\/7\/2014',1200],['07\/6\/2014',500],['07\/5\/2014',500],['07\/4\/2014',500],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000]]"};
alert(d.graph_data);
alert(d.mes);

How can I get javascript to read from a .json file?

My script currently looks like this:
<script type="text/javascript">
function updateMe(){
var x = 0;
var jsonstr = '{"date":"July 4th", "event":"Independence Day"}';
var activity=JSON.parse(jsonstr);
while(x<10){
date = document.getElementById("date"+x).innerHTML = activity.date;
event = document.getElementById("event"+x).innerHTML = activity.event;
x++;
}
}
</script>
Where date"x" and event"x" are a series of html tags. This function runs when the page loads (onload). My goal is to do this exact same thing, only from a local .json file as opposed to the hard code that I've got above. I've already checked out http://api.jquery.com/jQuery.getJSON/.
The local .json file looks like this:
{"date":"July 4th", "event":"Independence Day"}
Any suggestions?
Assuming you mean "file on a local filesystem" when you say .json file.
You'll need to save the json data formatted as jsonp, and use a file:// url to access it.
Your HTML will look like this:
<script src="file://c:\\data\\activity.jsonp"></script>
<script type="text/javascript">
function updateMe(){
var x = 0;
var activity=jsonstr;
foreach (i in activity) {
date = document.getElementById(i.date).innerHTML = activity.date;
event = document.getElementById(i.event).innerHTML = activity.event;
}
}
</script>
And the file c:\data\activity.jsonp contains the following line:
jsonstr = [ {"date":"July 4th", "event":"Independence Day"} ];
NOTICE: AS OF JULY 12TH, 2018, THE OTHER ANSWERS ARE ALL OUTDATED. JSONP IS NOW CONSIDERED A TERRIBLE IDEA
If you have your JSON as a string, JSON.parse() will work fine. Since you are loading the json from a file, you will need to do a XMLHttpRequest to it. For example (This is w3schools.com example):
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
<!DOCTYPE html>
<html>
<body>
<h2>Use the XMLHttpRequest to get the content of a file.</h2>
<p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>
<p id="demo"></p>
<p>Take a look at json_demo.txt</p>
</body>
</html>
It will not work here as that file isn't located here. Go to this w3schools example though: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax
Here is the documentation for JSON.parse(): https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Here's a summary:
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
Here's the example used:
var json = '{"result":true, "count":42}';
obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
Here is a summary on XMLHttpRequests from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest:
Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in Ajax programming.
If you don't want to use XMLHttpRequests, then a JQUERY way (which I'm not sure why it isn't working for you) is http://api.jquery.com/jQuery.getJSON/
Since it isn't working, I'd try using XMLHttpRequests
You could also try AJAX requests:
$.ajax({
'async': false,
'global': false,
'url': "/jsonfile.json",
'dataType': "json",
'success': function (data) {
// do stuff with data
}
});
Documentation: http://api.jquery.com/jquery.ajax/
You can do it like...
Just give the proper path of your json file...
<!doctype html>
<html>
<head>
<script type="text/javascript" src="abc.json"></script>
<script type="text/javascript" >
function load() {
var mydata = JSON.parse(data);
alert(mydata.length);
var div = document.getElementById('data');
for(var i = 0;i < mydata.length; i++)
{
div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
}
}
</script>
</head>
<body onload="load()">
<div id= "data">
</div>
</body>
</html>
Simply getting the data and appending it to a div... Initially printing the length in alert.
Here is my Json file: abc.json
data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';
Actually, you are looking for the AJAX CALL, in which you will replace the URL parameter value with the link of the JSON file to get the JSON values.
$.ajax({
url: "File.json", //the path of the file is replaced by File.json
dataType: "json",
success: function (response) {
console.log(response); //it will return the json array
}
});
Instead of storing the data as pure JSON store it instead as a JavaScript Object Literal;
E.g.
window.portalData = [
{
"kpi" : "NDAR",
"data": [15,152,2,45,0,2,0,16,88,0,174,0,30,63,0,0,0,0,448,4,0,139,1,7,12,0,211,37,182,154]
},
{
"kpi" : "NTI",
"data" : [195,299,31,32,438,12,0,6,136,31,71,5,40,40,96,46,4,49,106,127,43,366,23,36,7,34,196,105,30,77]
},
{
"kpi" : "BS",
"data" : [745,2129,1775,1089,517,720,2269,334,1436,517,3219,1167,2286,266,1813,509,1409,988,1511,972,730,2039,1067,1102,1270,1629,845,1292,1107,1800]
},
{
"kpi" : "SISS",
"data" : [75,547,260,430,397,91,0,0,217,105,563,136,352,286,244,166,287,319,877,230,100,437,108,326,145,749,0,92,191,469]
},
{
"kpi" : "MID",
"data" : [6,17,14,8,13,7,4,6,8,5,72,15,6,3,1,13,17,32,9,3,25,21,7,49,23,10,13,18,36,9,12]
}
];
You can then do the following in your HTML
<script src="server_data.js"> </script>
function getServerData(kpiCode)
{
var elem = $(window.portalData).filter(function(idx){
return window.portalData[idx].kpi == kpiCode;
});
return elem[0].data;
};
var defData = getServerData('NDAR');

Categories