Working with JSON via GET requests in Javascript - javascript

I've built a php API that provides data in json output, I need to get the values via a get request to then plot as a graph on the page.
The front end web component in hosted on the same server as in the api in this basic structure:
index.php
graph.php
/api/
/api/src
/api/src/api.php
My current code in graph.php is as follows:
<script>
var myJson;
$.getJson('api/src/api.php/poll/results/current/13/', function(jd){
myJson = jd.AnswerCount.1;
});
document.getElementById('jsonhere').innerHTML = myJson; //just to test
</script>
The endpoint outputs data like the following:
{"AnswerCount":{"1":5,"3":1,"2":2,"4":1,"5":5,"6":3,"7":2}}
Which I need loaded into a key-value pair array,
1:5
3:1
2:2
4:1
...
to then be put into the graphing library.
How do I fix my code/write new code to do this? I'm pretty stuck here.
EDIT:
On a hunch I logged all the get requests via wireshark, and no request is ever sent to the url in question. Even with an empty function { } ? http://grab.kfouwels.com/pmgW

You can't use a number as an identifier, to access the 1 property you have to say [1] not .1
You have to use the variable containing your data, not x which hasn't been mentioned until you try to assign it somewhere
The A in Ajax stands for Asynchronous. You have to work with your data inside your callback since the function you pass to getJson won't be called until the HTTP response arrived but the line starting document.get will run as soon as the HTTP request has been sent.

Related

Can't able to get the data using ajax in the MVC

I am using AJAX call in JS and calling a controller and action method with the url
I ran the code in my local it is working fine but when it was deployed in production the AJAX call didn't get the data and it is throwing a message in console
Could not load content for https://az416426.vo.msecnd.net/scripts/JavaScript/JavaScriptSDK/ajax/ajax.ts (HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE)
The data on local is limited but it has more data on production
I tried it by calling through AJAX and from the action method I am returning the data in the JSON format and the data i recieved is parsed and then it is sent to a hidden field it was running fine on my local all the data is there but when it was deployed on production after the page load the ajax will be called but I can't able to see the data and it shows the error which I mentioned above.
I will give you two recommendations that work better for me when dealing with passing JSON data from a controller.
First try this on your get data method:
[HttpGet]
public ContentResult Getsubscriptiondata()
{
var subdata = db.ExistingSubscriptionList.Where(substatus => substatus.OSCP_SubStatusId == "1").ToList();
return Content(JsonConvert.SerializeObject(subdata));
}
Second in your javascript change the line
document.getElementById('hdnExistingSubs').value = JSON.stringify(data)
to
document.getElementById('hdnExistingSubs').value = JSON.parse(data)
This gives me more consistent results when receiving data from the controller, hope this helps.
Clarification: I prefer this methods because passing a Json result sometimes haves quirks in the way the data is rendered on the javascript in the browser.

Passing JS variables to a PHP file (using ajax) in order to update SQL table [duplicate]

I have a problem sending data with an AJAX query to a php file, basically I use post request to send some data just for testing it out, the request is successful when I checked with developer tools in Chrome, as I can see the data that was sent , but the variable $_POST[] in php is always null, and don't understand why, because my data was sent to the php file.
Tried all kind of possibilities found on here, non of them will let me to go further, all of them will leave my $_POST[] empty. I modified the values inside the data attribute I added or removed content-type but nothing worked.
Here you have my jQuery code.
$.ajax({
method: "POST",
url: "2.php",
data: { name: 'JohnDoe', age: '19' }
}).done(function( msg ) {
alert(msg);
});
This is my PHP code.
<?php
$user=$_POST['name'];
var_dump($user);
?>
Errors
$user=$_POST['name'];
//ERROR - Notice: Undefined index: name in G:\xampp\htdocs\weather\2.php on line 6
//Expected result is 'JohnDoe'.
var_dump($user);
//this is Null
//Expected result is to contain some data
This are my two results I get in php.
The html and php files are in the same folder.
You are making two HTTP requests.
The first one using JavaScript, where you make a POST request and alert the response.
You can see the data from the response there.
You make the second request by typing the address into the address bar, where you make a GET request and have the response rendered as a webpage.
$_POST contains the POSTed data from the current request, not the data from any previous request.
The data you POSTed when you made the first request is not available when the PHP program runs again using the second request as input.
If you want to access that data then you need to explicitly do something to make it persist. This could be linked to the browser (so different users would not see each others data) — such as in a session or a cookie — or it could be independent of the browser — such as in a database — so every visitor to the site could see the data.

The file is emptied when I use file_put_contents

Main issue was solved in comments, although one of the bonus questions is still open and the other's solution could use some improvement
All of this takes place on a webhosting service, the folder structure is as follows:
The JavaScript and PHP files are in /public_html/, the JSON is in /public_html/data/.
In my JS code, I'm sending a POST request with some data for my JSON file:
console.log(objdata.buildings[0].coords);
var params = JSON.stringify(objdata);
if (objdata.buildings[0].coords != " "){
$.ajax({
type: "POST",
data: params,
url: "writecoords.php",
success: function(data){
console.log(params);
console.log(data);
console.log("AJAX success");
},
error: function(){
console.log("failed to send POST");
alert("error");
}
});
}
PHP file:
<?php
function debug_to_console($data){
if(is_array($data) || is_object($data))
{
echo("\n".json_encode($data));
} else {
echo("\n".$data);
}
}
$newJSON = json_decode(file_get_contents('php://input'));
debug_to_console($newJSON);
if (is_writable('data/strogi.json')) {
$a = file_put_contents('data/strogi.json', $newJSON);
if(! $a)
debug_to_console("Wrote nothing");
debug_to_console("PHP write success");
} else {
debug_to_console("PHP write failed");
}
?>
As you can see, I perform a check at every possible point to see if I'm actually processing non-empty data -- I log the value of the key in question, the AJAX request is sent only if it was changed, I log the data being sent and I log the data my PHP file receives and decodes.
I also check if the file is writable to avoid a possible permission problem, and only then I try to write to the file. The file comes out empty and I get the following outputs in console
params is my JSON object as a single line;
data is: my JSON object as a single line with line breaks before every new object and all cyrillic converted to \u format, "Wrote nothing!", "PHP write success";
"AJAX success"
If I check the strogi.json file after this, it's absolutely empty.
To rule out a problem with the format of passed JSON object, I tried writing to a simple test.txt file in the same directory as the .php, which turns out empty as well.
I tried using the method described here, but nothing changed.
I tried using a FTP upload (the method is pointed out somewhere in the comments here), and I got "No such file or directory" returned both for the strogi.json and test.txt files. I used both public_html/test.txt and test.txt as file name.
I tried using the combination of locks FILE_APPEND | LOCK_EX, and no changes happen to either of the files.
My questions are:
Why?
Can a different solution be used if all of this is taking place in the .done() callback for $.getJSON() called on the same file?
Follow-up question worthy of a separate section:
coords is a 3-dimensional array
[
[[x1,y1],[x2,y2],...]]
]
where the external array contains up to two arrays. The first array contains points of the external polygon and (if present) second array contains points of the internal polygon that serves as a cutout.
The code in question is an attempt to make submitting the coords array to strogi.json work for at least one object.
What I'm trying to do, in general, is
$.getJSON() the data/strogi.json file
go through the buildings[] array of objects inside it in the .done()
callback
for each object, check if "coords" is " " (default value)
If it is, a constructor is called to build a polygon using a map API, and when construction is finished, $.ajax is used to submit coords extracted through one of API's functions.
As of now, I'm submitting the whole JSON object, because I'm only working with one of the inner objects, but I imagine resubmitting the whole thing is excessive with multiple objects presented.
Is there a way to pass objdata.buildings[i].coords with the index i to PHP to change the "coords" key value in JSON for a certain buildings[i] object?
Do I need to make any changes to the way I'm processing data to make my JSON valid upon further reads? I assume I'd have to change the "coords" value from [[[x1,y1],[x2,y2]]] (the way it's passed now) to something like this (pastebin because there's no code formatting even though I'm using the 4 space indent)
for it to work, right? How do I do that? partly solved by going through the array in JS with two for() loops and applying toString() to every coordinate, there's gotta be a better way

JSON Reader issue: cannot access jsonData

I have a strange thing going on here: I am using a JSON reader within a store to fetch search results. After loading the store I receive data or error states (built together as a JSON, too). So in both ways I get a successfully response, so I have to check the JSON for myself to trap "error conditions". But I cannot access the jsonData property that shhould be a JSON object within the reader. Chrome tells me that:
I can access the applyDefaults though (it returns true in that case) but not the jsonData.
My code looks like this:
var result = searchStore.getProxy().getReader();
console.log(result.jsonData);
The output is "undefined". As you can see in the picture the jsonData object holds my JSON (with the isError property I wanted to access).
What I am doing wrong?
You need to think more async and think of the timing it takes for a request to return and when you are trying to get the jsonData. Instead of using console.log, set a breakpoint or use the debugger; statement so you can freeze the browser and walk through the code. You can then inspect variables and such to see what the object looks like.
Try to access your JSON data in a success callback, to make sure the data is gathered from the server.

AJAX responseXML

i have a problem regarding the responseXML of ajax..
I have this code from my callback function:
var lineString = responseXML.getElementsByTagName('linestring')[0].firstChild.nodeValue;
However, the linestring can only hold up to 4096 characters max.. the remaining characters are rejected.
I dont know what to use to get all the values that the lineString
returns. its quite a big data thats why I thought of using the responseXml
of AJAX, BUT turned out it still cannot accomodate everything.
My linestring consists of lines from a logfile which I concatenated and just
put line separator. I need to get this data in my form so that is why after reading from the php, i send it back via AJAX
Do you have suggestions guys.
XML adds a lot of extra markup for most ajax requests. If you are expecting some kind of list with data entities, sending them in a JSON format is the way to go.
I used JSON to get quite huge arrays with data.
First of all, JSON is just Javascript Object Notation meaning that the Ajax Request would request a String which will actually be evaluated as a Javascript object.
Some browsers offer support for JSON parsing out of the box. Other need a little help. I've used this little library to parse the responseText in all webapps that I developed and had no problems with it.
Now that you know what JSON is and how to use it, here's how the PHP code would look like.
$response = [
"success" => true, // I like to send a boolean value to indicate if the request
// was valid and ok or if there was any problem.
"records" => [
$dataEntity1, $dataEntit2 //....
]
];
echo json_enconde($response );
Try it and see what it echos. I used the php 5.4 array declaration syntax because it's cool! :)
When requesting the data via Ajax you would do:
var response
,xhr = getAjaxObject(); // XMLHttp or ActiveX or whatever.
xhr.open("POST","your url goes here");
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200) {
try {
response = JSON.parse(xhr.responseText);
} catch (err) {
response = {
success : false,
//other error data
};
}
if(response.success) {
//your data should be in response
// response.records should have the dataEntities
console.debug(response.records);
}
}
}
Recap:
JSON parsing needs a little help via JSON2 library
PHP can send maps as JSON
Success boolean is widely used as a "successful/unsuccessful" flag
Also, if you're into jQuery, you can just set the dataType : "json" property in the $.ajax call to receive the JSON response in the success callback.

Categories

Resources