I would like to send data to a Node.js server running on localhost with ajax. To test this, I wanted to send the input of type text to the server and just log it there.
This is my Post-Function (which is called by clicking on a button):
function answer(){
let data = {
name : $('#send').val()
};
console.log(data);
$.ajax({
type: 'POST',
url: 'http://localhost:3456/MyWebApp/Test',
dataType: 'text',
data: data.name,
success: console.log('post was successfull'),
error: function(textStatus, errorTrown){
console.log(textStatus + " " + errorTrown);
}
});
}
On my Server I try to collect the data with the following function:
app.post('/MyWebApp/Test', function(request,response){
console.log(request.body.data);
});
app.listen(3456);
My problem is, that the value on my server (in the above console.log) is always undefined.
I already tried to send the whole json-Object with dataType-Parameter json instead of text, but then I get an error in my server for trying to read a property value of something undefined. How do I have to implement the app.post function, to make the data readable and work with it?
I hope it is possible to understand what I am trying to achieve and what my problem is, I dont really know much about Node.js or Ajax, still I would be thankful for any help.
You're sending one string value data.name so your http request Content-Type would be plain/text
At NodeJS side you're using express library and it doesn't provide post request body by default.
You need to collect post request body using "data" event
request.on("data", callback);
I want to store my javascript output in PHP. I mean, my js code is:
function loadCurrentUser () {
var url = APIPATH + 'load_current_user.php' ;
var result = $.ajax({
type : "GET" ,
url : url,
async : false
}). responseText ;
var resultJSON = processJSONResult(result);
}
What I want is to store the output I received (in json format) to my variable $json (in php). How can I do that?
based on the comments above it cannot be done as you think. But if you insist on getting response date to a php variable you will have to make another ajax call as ajax call occur at client side and php runs in your server not on the browser #briosheje had explained it nicely. may be what you need is session variable ($_SESSION['index']) to store your response data
The following is the response I'm receiving in my AJAX success function:
"{"success":true,"data":{"id":1841,"title":"atitle","filename":"filename.jpg","url":"http:\/\/example.com\/wp-content\/uploads\/2014\/11\/filename.jpg","link":"http:\/\/example.com\/?attachment_id=1841","alt":"","author":"21","description":"","caption":"","name":"filename-39","status":"inherit","uploadedTo":0,"date":1415555051000,"modified":1415555051000,"menuOrder":0,"mime":"image\/jpeg","type":"image","subtype":"jpeg","icon":"http:\/\/example.com\/wp-includes\/images\/media\/file.png","dateFormatted":"November 9, 2014","nonces":{"update":"b832c2939d5","delete":"83dda46357e","edit":"51ac41b11c6"},"editLink":"http:\/\/example.com\/wp-admin\/post.php?post=1841&action=edit","meta":false,"authorName":"Some One","filesizeInBytes":10755,"filesizeHumanReadable":"11 kB","sizes":{"thumbnail":{"height":90,"width":90,"url":"http:\/\/example.com\/wp-content\/uploads\/2014\/11\/filename-90x90.jpg","orientation":"landscape"},"full":{"url":"http:\/\/example.com\/wp-content\/uploads\/2014\/11\/filename.jpg","height":260,"width":236,"orientation":"portrait"}},"height":260,"width":236,"orientation":"portrait","compat":{"item":"","meta":""}}}"
I'm trying to update the src attribute of a particular image on my page using the data that is returned in this response. For example:
$( '#myimage' ).attr( 'src', response.data.url );
The problem is, I get the error Uncaught TypeError: Cannot read property 'url' of undefined
I'm sure response.data.url is wrong. How can I get the URL from the response so that I can update the image's src attribute?
You might be able to take advantage of jQuery's getJSON method. When you're using ajax, you are only receiving a string response, so you would first have to parse it as json using parseJSON. However, getJSON will do parseJSON for you.
$.getJSON('my/service', function(data) {
$('#myimage').attr('src', data.url);
});
yo could use
x=$.parseJSON(response)
and this will convert the json string to a valid json objet, if there is an error will throw an exception you can use try{}catch(e){} to fix it
try{
var x=$.parseJSON(response);
}catch(e){
console.log(e);
}
use JSON.parse to parse as an object, your returned data is string:
response=JSON.parse(response);
$( '#myimage' ).attr( 'src', response.data.url );
The simple way is to use an AJAX request like this:
$.post('remote_url', {key:value}, function(response){
if(response.success) {
$('#myimage').attr('src', response.data.url);
}
}, 'json');
In this example, I've used $.post and you didn't provide enough information about the request type so it could be a $.getJSON request as well. Also, {key:value} is an object which will be passed to the server if required. So, use it if you pass any data to server, otherwise remove it.
In this example, 'json' is being used as data type so the response will be parsed by jQuery also if you use $.getJSON then the response will be parsed but in this case, you don't need to use 'json' as the last parameter. For example:
$.getJSON('remote_url', function(response) {
if(response.success) {
$('#myimage').attr('src', response.data.url);
}
});
Note: getJSON loads JSON-encoded data from the server using a GET HTTP request. So, for a POST request use $.post instead.
I am falling into a silly issue where the server is giving JSON response with XSS safe text added.
The server gives only 2 kinds of response:
HTML page with hidden input field that contains the value I want
JSON String with the value which can be preferably converted to JS
Object.
The problem is, for preventing JavaScript XSS attacks, the JSON response is made like this:
while(1);{
"name": {
"abc": "123",
...
}
}
So this goes to parseerror in jQuery ajax method and therefore in the error callback.
How do I fix this?
Also, I tried putting a hook in the error function and change the JSON data:
error: function(jqXHR) {
removeJSCode (jqXHR.responseText);
}
// ...
function removeJSCode(json) {
.. Code to filter the response
}
But this does not work.
jQuery's $.ajax has dataFilter property in its configuration. Pass it a function and it runs after jQuery receives ajax data, but before jQuery has a chance to touch it.
The function is provided the string response as first argument and data type as second argument. The second argument will depend if you passed dataType in the configuration.
There, you can use .replace('while(1);','') and return the string from the function for jQuery to parse.
$.ajax({
...
dataType : 'json',
dataFilter : function(response,type){
//if not JSON, don't do anything with it
if(type !== 'json') return response;
//otherwise, replace and return
return response.replace('while(1);','');
}
...
});
Please help me with the following situation:
there is the page p1.aspx with only one button:
<button id="btn1" onclick="btnclick();">Button</button>
<script type="text/javascript">
$('#btn1').click(function () {
$.getJSON("http://localhost/p2.aspx", function (data) {
$.each(data, function (i, field) {
alert(field);
});
});
});
</script>
Above is how I want to get the JSON text via javascript.
Web application http://localhost/p2.aspx is redirected to http://localhost/p3.aspx inside. And the page http://localhost/p3.aspx again is redirected back to
http://localhost/p2.aspx?code=1.
code=1
is the value I want read in my javascript code. But it's not works.
In p2.aspx I generate JSON data as following
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(jsonString);
Response.End();
After this I can not read json data via javascript. But if I just put the http://localhost/p2.aspx via web browser then it get json data on the page.
You need to use JSONP if you want that to work.
So your script should take into account the callback parameter:
Response.Clear();
string callback = Request["callback"];
if (!string.IsNullOrEmpty(callback))
{
Response.ContentType = "application/javascript; charset=utf-8";
Response.Write(string.Format("{0}({1})", callback, jsonString));
}
else
{
Response.ContentType = "application/json; charset=utf-8";
Response.Write(jsonString);
}
Response.End();
And then on the client:
$.getJSON("http://localhost/p2.aspx?callback=?", function (data) {
...
});
Notice how the callback query string parameter is set to ?. Basically jQuery will translate this to a request that looks like this:
http://localhost/p2.aspx?callback=jQuery123456789....
and your server side script should of course return JSONP which is your JSON string wrapped into the callback name:
jQuery123456789....({"code":1})
Also make sure that the jsonString variable used in your code is an actual JSON string (as its name suggests). Because what you have shown in your question (code=1) is very far from being JSON.