I am trying to post to a local son file which is saved within the same folder as all my code. I have done the following:
function test(){
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", "data/people.json");
xmlhttp.setRequestHeader("Content-Type", "application/json;");
xmlhttp.send(JSON.stringify({name:"John Rambo"}));
}
The above function is run when I click on a button in my html:
<input type="button" onclick="test()">
And my son file looks like this:
{
"People": [
{"name": "tony stark"},
{"name": "iron man"}
]
}
but I keep getting a 404 not found error. is there anything that I am doing wrong?
Apologies if I missed something out if you require more information to answer the question please let me know.
Thanks in advance.
Since I can't comment because I don't have enough reputation, if you want to enter data into your json file, the best thing you can do is:
Get the file and turn the JSON into an Object.
Once you have the object, push more data into it.
Afterwards, save the file / replace it with the object containing the new and the old information.
This is just a simple work around, but as other said in comments, you can't "POST" data into the file unless you do what I've just said.
Hope it helps!
Double check the URL end point.
Should be server script file which is made to accept the request.
And try sending is Key=Value pair.
xmlhttp.send("name=John Rambo");
Related
I'm building a little web-app where I'd like the users to be able to upload files, I'm using FormData to do so, /
<input id="fileInput" type="file">
var formData = new FormData()
var request = new XMLHttpRequest();
request.onreadystatechange = function () {window.resp = this}
request.open("POST", "upload.php");
request.send(formData);
But I have no idea how to get the data using PHP.
I know you can normally do
$_POST["KEY"]
But in this case I'm not using a key because the data isn't a string.
I've searched for quite some time now and came across the following things
print_r($_POST) // returned an empty array
var_dump($_POST) // returned an empty array
I don't know what I'm doing wrong and it's probably just some thing you have to know, but I can't seem to figure it out. Thanks in advance.
EDIT
Turns out you can just get the file using the
$_FILES
global, huge thanks to #tobias K!
SOURCES:
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
If you are posting raw data, you can get it in PHP by
$rawData = file_get_contents("php://input");
I have been traversing through Stackoverflow and everywhere else on the web to try and find a solution to my issue..
I am working in Javascript and attempting to POST a small section of JSON to an endpoint in the API i know is working (I have completes the GET and POST manually in Postman)
Here is my issue..
I want dont really want to do the "GET" in my programme I just want to either reference the file or even just store it in a little variable.
So for example I have in my code:
var OauthUpload = {
"objects": [
{
"name": "api",
"serviceID": 16,
"properties": {}
}
],
"version": "integration",
"environment": "redshift"
}
Then I am trying to reference this in the JS function:
function ApiPostOauth (port) {
$.post(OauthUpload, "http://docker.dc.test.com:" + getActualPort(port) + "/rest/v1/oauth/import", runner);
}
But I am having no joy! I have seen a few different silutions but none seem to fit for me.
Basically I want a way to just:
Reference my own JSON as a variable and then insert tht so my function "ApiPostOauth" has that inserted before it runs?
Thanks guys
Steve
I have put together an example for your use. When executing this code, the server will return the same object it is sent. So the 'OauthUpload` object is sent as the request body and the server returns the exact same object. Note: if you don't see output in the output panel when running the sample I will need to restart the server (leave a comment). This is here to demonstrate:
[EDIT] - after re-reading your question, it appears you would like to pass the 'OauthUpload` object into the function. I've updated the example.
You have a mistake in your call to jQuery post() method. As shown in the comments, the first two arguments are reversed in the call to post().
Since you didn't pick up on that, I decided to provide an example using your code. Since I don't have your server, I stood up a server for this example. So the URL and port will be different, but the AJAX call will be the same.
Please pay close attention to the OauthUpload object. Notice the property names are no longer surrounded by ". I removed these quotes because they seemed to be causing you confusion about JavaScript objects and JSON strings (there is no such thing as a JSON Object regardless of what you read on the web - JSON is a string format).
Next, look at the differences between the call made to $.post() in my example and your code. You will see the URL comes first in that call.
let url = "//SimpleCORSEnabledServer--randycasburn.repl.co/rest/v1/oauth/import";
let OauthUpload = {
objects: [{
name: "api",
serviceID: 16,
properties: {}
}],
version: "integration",
environment: "redshift"
}
ApiPostOauth(OauthUpload);
function ApiPostOauth(data) {
$.post(url, data, runner)
}
function runner(data) {
document.querySelector('pre').textContent = JSON.stringify(data, null, 2);
}
<pre></pre>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
First Question:
I have been trying to figure out how to update a JSON file through HTTP POST method when both files (HTML and JSON files) are on the same server (ex. Godaddy or AWS). At this point, it is working and sending data to the server as expected, but the JSON file is not updating. I believe I am missing something here. Is it Godaddy API? Check out my codes below:
Second Question:
Is there anyway to add authentication HTTP request? ex. only the user who has access or credential would be able to submit this data change request.
Here is the HTML file
<body>
<button id="my-button">Click Me</button>
<script>
document.getElementById('my-button').addEventListener('click', dataRequest);
function dataRequest (){
var xhttp = new XMLHttpRequest();
xhttp.open('POST','my-data.json', true);
xhttp.send('Name=YOYO&PhoneNumber=777-777-7777');
}
</script>
Here is my-data.json
{ "Name" : "First Name Last Name",
"PhoneNumber" : "888-777-9999" }
Thank you all for your time
POSTing data to a URL handled by a static file won't do anything.
If you want to change the data on the server, you'll need to write some server side code to handle it.
I am very new to Log4Javascript and logging in general, so bear with me.
I am attempting to POST the logs to a CouchDB. I am receiving an error from the server:
{"error":"bad_request","reason":"Document must be a JSON object"}
Okay cool. So its not a JSON Object, I can fix that.
Except that I can't figure out how.
The code I am using is:
var log = log4javascript.getLogger();
var ajaxAppender = new log4javascript.AjaxAppender(url);
var layout = new log4javascript.JsonLayout(true, false);
ajaxAppender.addHeader("Content-Type", "application/json");
ajaxAppender.setLayout(layout);
log.addAppender(ajaxAppender);
// Test the logger
log.debug(JSON.stringify("Hello world!"));
Everywhere I have searched says this is the way to send it as a JSON object, so I imagine this is correct.
When I look at the request payload, I realize that the CouchDB server must not like the way it is formatted, which is like so:
[
{
"logger": "[anonymous]",
"timestamp": 1487961971605,
"level": "DEBUG",
"url": "url.to.couchdb",
"message": "\"Hello world!\""
}
]
As you can see, it is a JSON object within an array, and I believe this is where my problem lies.
So my questions are:
Did I miss something in setting up the AjaxAppender and the JsonLayout?
Is there a way to change the format of the Request Payload with log4javascript?
If not, is there a way in CouchDB that when a document is POSTed, I can intercept and change the Request Payload and continue on, so it removes the array (that I am assuming it does not like)?
Thanks.
I have found my answer.
The JsonLayout has properties called batchHeader and batchFooter among others, but these two were the culprits for me.
For whatever reason, it still included them even though I was not doing batch log sending, so I removed both of them like so:
...
var layout = new log4javascript.JsonLayout(true, false);
layout.batchHeader = "";
layout.batchFooter = "";
...
This fixed my problem and I successfully POSTed logs to CouchDB.
Hope this helps someone else.
I'm currently creating a facebook fan page (www.facebook.com.SSBMstream), and I am using a static html app to create a section that will allow users to select a twitch.tv stream they wish to watch using a button. I want to go one step further and list channels based on whether or not they are 'live' or offline. Twitchtv/Justintv already has an api set up for exactly that (http://api.justin.tv/api/stream/list.json?channel=) where you can just plug in the channel name and get '[]' if it is not live and what I believe is JSON if it is. How to dynamically check each channel in my array to determine if it is live and, if possible, access the information in that api to allow me to update titles and the like?
EDIT: Here's the hollowed out version of my code (Only the part I'm having trouble with)
I'm having it return the information from the other page as a debugger so I can test whether or not (if/when) it's working.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function loadJSON()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)
{
document.getElementById("div1").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://api.justin.tv/api/stream/list.json?channel=ignproleague",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="div1"><h2>Just a test</h2></div>
<button type="button" onclick="loadJSON()">Change Content</button>
</body>
</html>
It depends on how twitch defines what is live and what isn't. Sorry I'm not super familiar with twitch's API but if it returns an empty array if the channel isn't live you could simply check if (array.length == 0).
If you are given a JSON object, then just interact with the appropriate information you need. I don't know exactly how twitch formats their JSON objects but here is an example. Let's say it returned this JSON object:
var JSONobj = {
"channelName": "e-sports", "channelTheme: "Professional Gaming", "viewerCount": 100
};
To retrieve the information you would just have to call the appropriate field.
var chan = JSONobj.channelName; //chan = "e-sports
var theme = JSONobj.channelTheme; //theme = "Professional Gaming"
Hope this helps
EDIT: It seems you need help with understanding AJAX. Let me just give you a rough idea of what the syntax is. I personally use a framework called Prototype.js
new Ajax.Request(WEB_SERVICE, {
method: "get",
parameters: {"type" : type, "name" : name},
onSuccess: successCall,
onFailure: ajaxError,
onException: ajaxError
});
This is your pretty typical AJAX request. When this is called, it'll throw an AJAX request to a WEB_SERVICE (generally a PHP document that will get the parameters passed and then calculate something from it). In this scenario the method being passed is "GET" and the parameters being passed is in the form of an object with the fields "type" and "name". successCall is a method that is called when the AJAX request successfully is passed and returns the ajax that has been calculated. I'm assuming in your scenario your AJAX should be receiving some information in a JSON format so its important your successCall function not only gets back that information, but parses through it as if it were JSON. Your successCall function would look something like this:
function successCall(ajax) {
var info = JSON.parse(ajax.responseText);
Hopefully from here you have a good understanding of what's going on. Try to work with this and if you still need help, just comment.
Oh and I didn't see that other comment. If you want to MAKE a JSON object you can do so like this.
var JSONobj = {};
JSONobj.field = something;
Your JSON object would then look something like this:
JSONobj = { "field" : something };
It is important you stringify the JSONobj if you want to pass it as a String. I guess it depends on how your WEB_SERVICE is handling it and you can do so like this.
var stringJSON = JSON.stringify(JSONobj);
Hope this helps.