How to send javascript object with POST XMLHttpRequest - post
I want to send the following data in POST XMLHttpRequest method.
Data to be sent:
var data = {xx:"value",user:{password:"pass",username:"xyz"}};
Code used:
var xmlhttp = new XMLHttpRequest();
var data = {xx:"value",user:{password:"pass",username:"xyz"}};
data = JSON.stringify(data);
xmlhttp.open("POST",Url,true);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.send(data );
Result:
Getting "xx" is missing.
Kindly help me to resolve this issue.
Related
twitter-api-v2 / Bad Twitter streaming request: 403
var Twit = require('twit'); var replie = ['1','2','3']; var T = new Twit({ .... }) var stream = T.stream('statuses/filter', { track: '#beykant_' }); stream.on('tweet',tweetEvent); function tweetEvent(eventMsg) { var replyto = eventMsg.in_reply_to_screen_name; var text = eventMsg.text; var from = eventMsg.user.screen_name; if(replyto == 'beykant_'){ var newTweet = '#' + from + replie[Math.floor(Math.random() * replie.length)]; tuit(newTweet); } } function tuit(txt){ var tweet = { status: txt } T.post('statuses/update',tweet, tweeted); function tweeted (err, data, response) { if(err){ console.log('err'); }else{ console.log('ready') } console.log(data) } } I used twitter-api-v2, I couldn't find the response event when #mentioned on it. When I tried the twit module, it gave such an error again, can anyone show a solution, it would be better if it can be done with the twitter-api-v2 module, thank you.
Mirth HTTP POST request with Parameters using Javascript
The following code by #Nick Rupley works well, but, I need also to pass parameters as POST. How do we pass POST parameters? from java.net.URL var url = new java.net.URL('http://localhost/myphpscript.php'); var conn = url.openConnection(); var is = conn.getInputStream(); try { var result = org.apache.commons.io.IOUtils.toString(is, 'UTF-8'); } finally { is.close(); } 2 Parameters to pass: firstname="John" and lastname="Smith" Thanks
This will POST with MIME type application/x-www-form-urlencoded. It is using apache httpclient, which is already included with mirth, as it is used internally by the HTTP Sender connector, as well as some other functionality. Other solutions may require you to download jars and add library resources. Closer is part of Google Guava, which is also already included with mirth. Check comments where Rhino javascript allows for simplified code compared to direct Java conversion. It wouldn't be a bad idea to wrap all of this up in a code template function. var result; // Using block level Java class imports with (JavaImporter( org.apache.commons.io.IOUtils, org.apache.http.client.methods.HttpPost, org.apache.http.client.entity.UrlEncodedFormEntity, org.apache.http.impl.client.HttpClients, org.apache.http.message.BasicNameValuePair, com.google.common.io.Closer)) { var closer = Closer.create(); try { var httpclient = closer.register(HttpClients.createDefault()); var httpPost = new HttpPost('http://localhost:9919/myphpscript.php'); // javascript array as java List var postParameters = [ new BasicNameValuePair("firstname", "John"), new BasicNameValuePair("lastname", "Smith") ]; // Rhino JavaBean access to set property // Same as httpPost.setEntity(new UrlEncodedFormEntity(postParameters, "UTF-8")); httpPost.entity = new UrlEncodedFormEntity(postParameters, "UTF-8"); var response = closer.register(httpclient.execute(httpPost)); // Rhino JavaBean access to get properties // Same as var is = response.getEntity().getContent(); var is = closer.register(response.entity.content); result = IOUtils.toString(is, 'UTF-8'); } finally { closer.close(); } } logger.info(result);
Following is a complete working HTTP POST request solution tested in Mirth 3.9.1 importPackage(Packages.org.apache.http.client); importPackage(Packages.org.apache.http.client.methods); importPackage(Packages.org.apache.http.impl.client); importPackage(Packages.org.apache.http.message); importPackage(Packages.org.apache.http.client.entity); importPackage(Packages.org.apache.http.entity); importPackage(Packages.org.apache.http.util); var httpclient = HttpClients.createDefault(); var httpPost = new HttpPost("http://localhost/test/"); var httpGet = new HttpGet("http://httpbin.org/get"); // FIll in each of the fields below by entering your values between the ""'s var authJSON = { "userName": "username", "password": "password", }; var contentStr =JSON.stringify(authJSON); //logger.info("JSON String: "+contentStr); httpPost.setEntity(new StringEntity(contentStr,ContentType.APPLICATION_JSON,"UTF-8")); httpPost.setHeader('Content-Type', 'application/json'); httpPost.setHeader("Accept", "application/json"); // Execute the HTTP POST var resp; try { // Get the response resp = httpclient.execute(httpPost); var statusCode = resp.getStatusLine().getStatusCode(); var entity = resp.getEntity(); var responseString = EntityUtils.toString(entity, "UTF-8"); var authHeader = resp.getFirstHeader("Authorization"); // logger.info("Key : " + authHeader.getName()+" ,Value : " + authHeader.getValue()); // Save off the response and status code to Channel Maps for any potential troubleshooting channelMap.put("responseString", responseString); channelMap.put("statusCode", statusCode); // Parse the JSON response var responseJson = JSON.parse(responseString); // If an error is returned, manually throw an exception // Else save the token to a channel map for use later in the processing if (statusCode >= 300) { throw(responseString); } else { logger.info("Token: "+ authHeader.getValue()); channelMap.put("token", authHeader.getValue()); } } catch (err) { logger.debug(err) throw(err); } finally { resp.close(); } This linke + above answers helped me to come up with a solution https://help.datica.com/hc/en-us/articles/115005322946-Advanced-Mirth-Functionality
There are plenty of libraries that can help you with URI building in Java. You can find them below. But if you want to stay in Javascript just add your parameters manually than create it. function addParam(uri, appendQuery) { if (appendQuery != null) { uri += "?" + appendQuery; } return uri; } var newUri = addParam('http://localhost/myphpscript.php', 'firstname="John"'); var url = new java.net.URL(newUri); Java EE 7 import javax.ws.rs.core.UriBuilder; ... return UriBuilder.fromUri(url).queryParam(key, value).build(); org.apache.httpcomponents:httpclient:4.5.2 import org.apache.http.client.utils.URIBuilder; ... return new URIBuilder(url).addParameter(key, value).build(); org.springframework:spring-web:4.2.5.RELEASE import org.springframework.web.util.UriComponentsBuilder; ... return UriComponentsBuilder.fromUriString(url).queryParam(key, value).build().toUri();
There are multiple ways to provide http client connection with java. Since your question is specific to java.net.URL I will stick to that. Basically you can pass parameters as POST, GET, PUT, DELETE using .setRequestMethod this will be used along with new java.net.URL(ur-destination-url).openConnection(); Here is the complete code I've using javascript in Mirth using the same java.net.URL use this it will be helpful. It worked well for me. do { try { // Assuming your writing this in the destination Javascript writer var data = connectorMessage.getEncodedData(); //Destination URL destURL = “https://Your-api-that-needs-to-be-connected.com”; //URL var url = new java.net.URL(destURL); var conn = url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); enter code here conn.setRequestProperty (“Authorization”, globalMap.get(‘UniversalToken’)); conn.setRequestMethod(“DELETE”); // this can be post or put or get or patch conn.setRequestProperty(“Content-length”, data.length()); conn.setRequestProperty(“Content-type”, “application/json”); var outStream = conn.getOutputStream(); var outWriter = new java.io.OutputStreamWriter(outStream); outWriter.write(data); outWriter.close(); // Get response Code (200, 500 etc.) var respCode = conn.getResponseCode(); if (respCode != 200) { // Write error to error folder var stringData = response.toString() + “\n”; FileUtil.write(“C:/Outbox/Errors/” + $(“originalFilename”) + “.ERROR_RESPONSE”, false, stringData); // Return Error to Mirth to move the file to the error folder return ERROR; } errorCond = “false”; break; } catch(err) { channelMap.put(“RESPONSE”, err); responseMap.put(“WEBSVC”, ResponseFactory.getErrorResponse(err)) throw(err); // Can return ERROR, QUEUED, SENT // This re-queues the message on a fatal error. I”m doing this since any fatal message may be // caused by HTTPS connect errors etc. The message will be re-queued return QUEUED; // Re-queue the message java.lang.Thread.sleep(6000); // 6 seconds * 10 errorCond = “true”; } } while (errorCond == “true”);
How to make ol.source.ImageWMS send POST request
In our project, we're using OpenLayers-3's ol.source.ImageWMS to show image provided by Mapserver WMS. Since we're using Mapserver runtime substitution, our request can become quite long, which could cause a problem for a GET request. Is there a way to make ol.source.ImageWMS send POST request?
I answer this just for the reference based on this Openlayers dev thread, hopefully it will help someone in the future!. I needed to pass a very long CQL request to a Geoserver wms, and GET was limited in size, so I used POST like the following: var POSTWMSLayer = new ol.layer.Image({ source: new ol.source.ImageWMS({ url: 'https://test.server.com/geoserver/wms', params: { 'LAYERS': 'firstworkspace:states', 'CQL_FILTER':'gid IN (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,2785,2786,2787,2788,2789,2790,2791,2792,2793,2794,2795,2796,2797,2798,2799,2800,2801,2802,2803,2804,2805,2806,2807,2808,2809,2810,2811,2812,2813,2814,2815,2816,2817,2818,2819,2820,2821,2822,2823,2824,2825,2826,2827,2828,2829,2830,2831,2832,2833,2834,2835,2836,2837,2838,2839,2840,2841,2842,2843,2844,2845,2846,2847,2848,2849,2850,2851,2852,2853,2854,2855,2856,2857,2858,2859,2860,2861,2862,2863,2864,2865,2866,2867,2868,2869,2870,2871,2872,2873,2874,2875,2876,2877,2878,2879,2880,2881,2882,2883,2884,2885,2886,2887,2888,2889,2890,2891,2892,2893,2894,2895,2896,2897,2898,2899,2900,2901,2902,2903,2904,2905,2906,2907,2908,2909,2910,2911,2912,2913,2914,2915,2916,2917,2918,2919,2920,2921,2922,2923,2924,2925,2926,2927,2928,2929,2930,2931,2932,2933,2934,2935,2936,2937,2938,2939,2940,2941,2942,2943,2944,2945,2946,2947,2948,2949,2950,2951,2952,2953,2954,2955,2956,2957,2958,2959,2960,2961,2962,2963,2964,2965,2966,2967,2968,2969,2970,2971,2972,2973,2974,2975,2976,2977,2978,2979,2980,2981,2982,2983,2984,2985,2986,2987,2988,2989,2990,2991,2992,2993,2994,2995,2996,2997,2998,2999,3000,3001,3002,3003,3004,3005,3006,3007,3008,3009,3010,3011,3012,3013,3014,3015,3016,3017,3018,3019,3020,3021,3022,3023,3024,3025,3026,3027,3028,3029,3030,3031,3032,3033,3034,3035,3036,3037,3038,3039,3040,3041,3042,3043,3044,3045,3046,3047,3048,3049,3050,3051,3052,3053,3054,3055,3056,3057,3058,3059,3060,3061,3062,3063,3064,3065,3066,3067,3068,3069,3070,3071,3072,3073,3074,3075,3076,3077,3078,3079,3080,3081,3082,3083,3084,3085,3086,3087,3088,3089,3090,3091,3092,3093,3094,3095,3096,3097,3098,3099,3100,3101,3102,3103,3104,3105,3106,3107,3108,3109,3110,3111,3112,3113,3114,3115,3116,3117,3118,3119,3120,3121,3122,3123,3124,3125,3126,3127,3128,3129,3130,3131,3132,3133,3134,3135,3136,3137,3138,3139,3140,3141,3142,3143,3144,3145,3146,3147,3148,3149,3150,3151,3152,3153,3154,3155,3156,3157,3158,3159) }, serverType: 'geoserver', imageLoadFunction: function (image, src) { var img = image.getImage(); if (typeof window.btoa === 'function') { var urlArray = src.split("?"); var url = urlArray[0]; var params = urlArray[1]; var xhr = new XMLHttpRequest(); xhr.onload = function (e) { if (this.status === 200) { var uInt8Array = new Uint8Array(this.response); var i = uInt8Array.length; var binaryString = new Array(i); while (i--) { binaryString[i] = String.fromCharCode(uInt8Array[i]); } var data = binaryString.join(''); var type = xhr.getResponseHeader('content-type'); if (type.indexOf('image') === 0) { img.src = 'data:' + type + ';base64,' + window.btoa(data); } } }; xhr.open('POST', url, true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.responseType = 'arraybuffer'; xhr.send(params); } else { img.src = src; } } }) });
Actually the httprequest is the problem, use Httprequest Post method instead of get method in ol.source.ImageWMS? Get request can not pass long string parameters. For big parameters we need to pass request with post method. Now the bottleneck is that the post method is not supported in openlayers 3 whereas in old version it had support for post method. Note: This is old OpenLayers code var query = new OpenLayers.Layer.WMS.Post("My Layer", 'http://192.168.6.51:8090/geoserver/VP/wms', { LAYERS : 'Namespace:LayerName', sld_body : strSld_body, format : 'image/jpeg', transparent : 'true' }, { unsupportedBrowsers: [], isBaseLayer: false, yx : {'EPSG:4326' : true} } ); In openlayers 3 there may be a workaround.
How to handle error scenarios in Csv file download with web api
I am using the following code to post data to my api controller var form = document.createElement('form'); form.action = '/api/reportsapi/exportToCsv'; form.method = 'POST'; form.style.display = 'none'; for (i in data) { if (data[i] != "") { var inputElement = document.createElement('textarea'); inputElement.name = i; inputElement.value = data[i]; form.appendChild(inputElement); } } document.body.appendChild(form); form.submit(); and my api controller returns a HttpResponseMessage var csvValidRequestResult = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(csvReport.Data) }; csvValidRequestResult.Content.Headers.ContentType = new MediaTypeHeaderValue("text/comma-separated-values"); csvValidRequestResult.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = csvReport.FileName }; return csvValidRequestResult; all this works fine. A file with data is downloaded when the above scripts hits the controller. But the problem arises if there is any server side exception, in that case the page gets redirected to the the form's api url. Is there something I can do to get to know of the error and act accordingly on the client side ?
How can we send/get the http headers information with AJAX?
Is there any way to send/get the http headers (like, content-type... ) through AJAX?. Then, can please explain me, what will we archive by passing the http headers in AJAX and where will use this technique?. Thanks
I'm no expert, But you should look at the AJAX object XmlHttpHeader and the wikipedia article here. EDIT: quoting the www.w3.org reference: function test(data) { // taking care of data } function handler() { if(this.readyState == 4 && this.status == 200) { // so far so good if(this.responseXML != null && this.responseXML.getElementById('test').firstChild.data) // success! test(this.responseXML.getElementById('test').firstChild.data); else test(null); } else if (this.readyState == 4 && this.status != 200) { // fetched the wrong page or network error... test(null); } } var client = new XMLHttpRequest(); client.onreadystatechange = handler; client.open("GET", "unicorn.xml"); client.send(); If you just want to log a message to the server: function log(message) { var client = new XMLHttpRequest(); client.open("POST", "/log"); client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8"); client.send(message); } Or if you want to check the status of a document on the server: function fetchStatus(address) { var client = new XMLHttpRequest(); client.onreadystatechange = function() { // in case of network errors this might not give reliable results if(this.readyState == 4) returnStatus(this.status); } client.open("HEAD", address); client.send(); }