why i cant send data to .json format file by ajax - javascript

I'm making a simple server to send data to a .json file and receive that data from another page but I have problem how to store data in .json file
I used following code but it didn't work
<script src="jquery/jquery-3.4.1.min.js"></script>
<script>
var _lname = "x";
var _fname = "y";
var _mname = "x";
$.ajax({
type: "POST",
url: "data.json",
data: "{'lastName':'" + _lname + "','firstName':'" + _fname + "','middleName':'" + _mname + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
}
});
</script>

Simply POSTing data to a JSON file won't work, as sending a POST request requires the server to listen for requests and do something with the payload you sent. You could make a simple NodeJS or PHP script (or any other server-side language for that matter) that could handle saving the payload to a JSON-file.

When you make a POST request, you send data to a web server.
The web server can do something with the data in the POST request.
By default, it does nothing. Imagine the problems that would be caused if anybody could make a POST request to anyone else's web server and write a new file to it. Google's homepage would be defaced every other second.
If you want to store the results of a POST request, then you need to write server-side code to do it (and you almost certainly will want to perform authentication and authorisation when you do so).
Note that the value of data: in your example code will never be valid JSON. Don't try to write JSON by mashing strings together. Use a library function like JSON.stringify.

Related

Long polling with ajax and servlets

I'm doing a project using javascript for client side and servlets for server side. I'm trying to implement a way to update client info real time. i.e when a client update some info in the web application, other clients will also see the update. I found that long polling is a good technique for this. This is the code I tried to get to work.
function poll() {
setTimeout(function() {
$.ajax({
type: "GET",
url: "server",
contentType: "application/json",
data: {
type: "update",
card: "string"
},
success: function(data) {
alert(data);
},
error: function(data) {
alert('eroor');
},
dataType: "json",
complete: poll });
}, 5000);
}
I'm trying to send a request to the server every 5 seconds and get the response with new updates. But in all the skeleton codes I saw in the web, data: is not set. Without setting it, how would the sever know the type of request it received since there are other types of requests too. But when I set data: no requests are sent from the client. But without setting data: requests are sent to the server. Is it wrong to set data: ? Without it how would I let the servlet know the type of the request?
I understand that like mentioned in here long polling is not what I'm trying to do. But can anyone explain what I should do and where I'm doing wrong.
Since you make a GET request, the data values are appended to the URL as URL parameters. Your servlet must then use request.getParameter("type") and request.getParameter("card") to extract the information from the request.
If you think that no request is sent, first check your console for errors and look at the net communications panel in the developer tools of your browser.
data:
issue is how you set the data. If you want to send json object, you have to stringify before you send it, like below.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Without it how would I let the servlet know the type of the request?
What you mean by this? to know the contentType? If so, send contentType parameter as above.
I understand that like mentioned in here long polling is not what I'm trying to do. But can anyone explain what I should do and where I'm doing wrong.
Yes. This is not exactly a long polling. This is how you send a request to the server in every 5 seconds. Anyway server should support to long polling.

JQuery $.ajax request returns me "Error 404" even if the resource exists

I'm developing an app with TideSDK and I need to send some data to a PHP script that will create a file to store it on the pc. I'm pretty new to AJAX and to send data I do:
var jsonString = JSON.stringify(GW2.items);
$.ajax({
url: "/assets/scripts/save.php",
type: "post",
dataType: "json",
data: { jsonString: jsonString }
}).done(function(data){
console.log(data);
});
Where GW2.items is a JSON object, "save.php" is my script and jsonString is the variable I want to send.
But, when I try to execute the program it returns me:
POST http://127.0.0.1:52432/assets/scripts/save.php 404 Not Found
And the answer is: Cannot POST /assets/scripts/save.php
This is the PHP script:
<?php
$jsonString = $_GET['jsonString'];
return {};
?>
I checked the path and it's correct so why it can't find my file?
Did you try your path with POST or just GET? It could be exist for GET requests (pasting the url on a browser) but probably not for POST or other HTTP verbs.
You can use REST clients like Postman to be sure, which is also a Chrome extension.

How do I do an ajax call to a database using Javascript, a URL and a key

I have been given a url of type xxxx.xxxxx.com as well as a key of type FGHyehgvc787vbhj
in order to gain read-only access to an sql database and retrieve data from it using javascript.
I have no prior experience with databases and maybe my question will sound completely stupid but I was wondering how can I combine the above information in order to get access to the database (e.g. do an ajax call and retrieve data from it..)
I'm familiar with doing ajax calls to a webpage and getting data from it using jQuery, as in :
$.ajax(/*url of website*/, function (data)
{
var dataRetrieved = $(data);
// do something with the data retrieved...
});
so I was wondering whether there is something equivalent to the above when it comes to making an ajax call to a database, using however a key.
Thank you for any help, and please delete this post if you find it completely pointless and excuse me in advance for that by the way.
It is usually very bad design to allow client side code to interact with your database in any way. This can be a huge security issue. Generally you will want your server side code to do this (e.g PHP, node, etc.). You would send a request to your server with client side code, and the server side code would do the actual work of updating the database.
you can create a wcf service and call that service through ajax, that wont be huge security issue.
try this
$.ajax({
cache: false,
type: "GET",
async: false,
data: {},
url: http:xxxxxxxxxxxx.svc/webBinding/Result?metaTag=" + meta,
contentType: "application/json; charset=utf-8",
dataType: "json",
crossDomain: true,
success:function(result){},
error: function(){alert(err);}
});
Use this
$.ajax({
url: 'path/to/server-side/script.php', /*url*/
data: '', /* post data e.g name=christian&hobbie=loving */
type: '', /* POST|GET */
complete: function(d) {
var data= d.responseTXT;
/* Here you can use the data as you like */
$('#elementid').html(data);
}
});
Hope this helps...

javascript json request with some parameters

So a simple question:
JavaScript needs to send to server that request:
myserver/scipt.php?LANG=EN&AGENT={"Login":{"name":"user","pass":"user"}}
How I need to form url and data in Ajax?
Is this right?
var formData = {
"login":$("#field1").val(),
"pass":$("#field2").val()
};
$.ajax({
url:'http://myserver/scipt.php?LANG=EN&',
type:'GET',
data:'AGENT=' + $.toJSON(formData),
success: function(res) {
alert(res);
}
});
Thank you!
I'd recommend sending JSON via POST instead of GET. GET has some limitations that you want to avoid.
A part from that, yes, your code seems ok.
EDIT:
Sorry, your code is not ok.
Change the data line to:
data: $.toJSON(formData),
You need to send the data to the server in the form of a map ..
Your data is already in json format.. You need not do $.toJSON again
Instead of
data:'AGENT=' + $.toJSON(formData),
send it this way
data:{ 'AGENT' : {'Login' : formData } },
You need to URL encode any strings you want to pass through Ajax.
If jQuery works anything like a normal form, you also need to put all your query string data into data to avoid the existing query string being destroyed.
url:'http://myserver/scipt.php',
type:'GET',
data: {
"AGENT": $.toJSON(formData),
"LANG": "EN"
},
Note, you should use POST requests if you are transmitting user credentials. You don't want them cached or stored in server access.log files.

How do I ensure jQuery ajax call does not send a local copy of file?

$.ajax({
type: 'GET',
url: "string.txt",
cache: false,
success: function(str){
alert("Data is: "+ str);
}
});
In this example, string.txt is sent to the cache (\Temporary Internet Files)
How do I ensure that the file is not sent. I do not want copy to be sent.
Only a read from the server. Am I missing an option?
I set cache to false but that does not block it from being sent to client.
For example, ajax POST does not send a local copy.....
Here is some background info to what i am trying to do, but with jQuery.
I am curious as to why the standard ajax post seems to have the desired functionality I am looking for and am unable to do that with jQuery?
Thanks
Or set a no cache header server-side.

Categories

Resources