Angular $http.post not sending any data - javascript

I'm super stuck with trying to simply post JSON data but for some reason it won't work.
angular.module('pocket.controllers', [])
.controller('ArticleList', function($scope, $http) {
$scope.signIn = function() {
var postObject = new Object();
postObject.consumer_key = pocketKey;
postObject.redirect_uri = "http://www.example.com";
$http.post(apiUrl, postObject).success(function(data){
alert(data);
});
}
})
When I inspect the request in the Chrome inspector it doesn't seem like any data is actually being posted:
Request URL:https://getpocket.com/v3/oauth/request
Request Method:OPTIONS
Status Code:400 Bad Request
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, origin, x-requested-with, content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Connection:keep-alive
Host:getpocket.com
Origin:http://pocket.dev:8000
Pragma:no-cache
Referer:http://pocket.dev:8000/app/index.html
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36
Response Headersview source
Cache-Control:private
Connection:keep-alive
Content-Length:15
Content-Type:text/html; charset=UTF-8
Date:Wed, 24 Jul 2013 17:18:04 GMT
P3P:policyref="/w3c/p3p.xml", CP="ALL CURa ADMa DEVa OUR IND UNI COM NAV INT STA PRE"
Server:Apache/2.2.25 (Amazon)
Status:400 Bad Request
X-Error:Missing consumer key.
X-Error-Code:138
X-Powered-By:PHP/5.3.27
X-Source:Pocket
As you can see, the X-Error is "Missing consumer key" which implies the data is not being posted correctly.

Add this line to your code;
$http.defaults.headers.post["Content-Type"] =
"application/x-www-form-urlencoded";
Modified code will be like this;
angular.module('pocket.controllers', []) .controller('ArticleList',
function($scope, $http) {
$scope.signIn = function() {
var postObject = new Object();
postObject.consumer_key = pocketKey;
postObject.redirect_uri = "http://www.example.com";
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.post(apiUrl, postObject).success(function(data){
alert(data);
});
}
})

Related

jQuery Ajax Form Data settings convert to pure javascript

Found the answer thanks from Patrick Evans:
window.onload = function()
{
var data = new FormData();
data.append("gcd", "gcd");
data.append("name", "name");
ajax({
type: "POST",
url: url,
data: data,
success: function(resopnse)
{
console.log(resopnse);
},
dataType: "json"
});
}
var http_request = new XMLHttpRequest();
function ajax(options) {
http_request.open(options.type || 'GET', options.url, true);
http_request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
http_request.send(options.data || null);
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var type = options.dataType || '';
switch (type.toLowerCase()) {
default:
options.success(http_request.responseText);
break;
case 'json':
options.success(JSON.parse(http_request.responseText));
break;
}
}
}
}
}
Here is my Ajax test javascript using jQuery and Pure Javascript Ajax:
window.onload = function()
{
var url = "GRNM";
var data = {
gcd: "gcd",
name: "name"
};
$.ajax({
type: "POST",
url: url,
data: data,
success: function(resopnse)
{
console.log(resopnse);
},
dataType: "json"
});
ajax({
type: "POST",
url: url,
data: data,
success: function(resopnse)
{
console.log(resopnse);
},
dataType: "json"
});
}
Pure Javascript Ajax:
var http_request = new XMLHttpRequest();
function ajax(options) {
http_request.open(options.type || 'GET', options.url, true);
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
http_request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
http_request.send(JSON.stringify(options.data) || null);
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var type = options.dataType || '';
switch (type.toLowerCase()) {
default:
options.success(http_request.responseText);
break;
case 'json':
options.success(JSON.parse(http_request.responseText));
break;
}
}
}
}
}
And this is the result:
jQuery: I could get the value data successfully
General:
Request URL: http://gaspc-011:8888/GRNM
Request Method: POST
Status Code: 200
Remote Address: 192.168.1.120:8888
Referrer Policy: strict-origin-when-cross-origin
Response Headers:
Connection: keep-alive
Content-Length: 43
Content-Type: application/json
Date: Fri, 27 Aug 2021 06:20:37 GMT
Keep-Alive: timeout=60
Request Headers:
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 17
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Host: gaspc-011:8888
Origin: http://gaspc-011:8888
Referer: http://gaspc-011:8888/index01
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36
X-Requested-With: XMLHttpRequest
Form Data:
gcd: gcd
name: name
Pure Javascript: I couldn't get the data
General:
Request URL: http://gaspc-011:8888/GRNM
Request Method: POST
Status Code: 400
Remote Address: 192.168.1.120:8888
Referrer Policy: strict-origin-when-cross-origin
Response Headers:
Connection: close
Content-Language: en-US
Content-Type: text/html;charset=Shift_JIS
Date: Fri, 27 Aug 2021 06:20:37 GMT
Transfer-Encoding: chunked
Request Headers:
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 27
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Host: gaspc-011:8888
Origin: http://gaspc-011:8888
Referer: http://gaspc-011:8888/index01
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36
X-Requested-With: XMLHttpRequest
Form Data:
{"gcd":"gcd","name":"name"}:
My Spring Boot Controller couldn't find the gcd and name parameter that came from pure javascript because the Form Data format is different. I've also tried to use FormData() but couldn't make it work.
My Form Data becomes like this:
Form Data:
------WebKitFormBoundaryLgD8tjkxnVk4hfiE
Content-Disposition: form-data; name: "gcd"
gcd
------WebKitFormBoundaryLgD8tjkxnVk4hfiE
Content-Disposition: form-data; name="name"
name
------WebKitFormBoundaryLgD8tjkxnVk4hfiE--
I've also tried changing http_request.send(JSON.stringify(options.data) || null); to http_request.send(options.data || null); but didn't worked.
How can I achieve the same result as jQuery? How can I pass my var data object to controller using Ajax POST same as jQuery?
You need to supply the correct content-type with the correct content.
If you want to send JSON text you have to use application/json content-type
http_request.setRequestHeader('Content-Type', 'application/json');
http_request.send(JSON.stringify(options.data));
If you want to use the FormData object you need the multipart/form-data content-type
let fd = new FormData();
for(let key in options.data){
fd.append(key,options.data[key]);
}
//don't need to explicitly set content-type when sending FormData
//it will automatically do that
//http_request.setRequestHeader('Content-Type', 'multipart/form-data');
http_request.send(fd);
If you just want to use your object you will need to convert it to one of the previously mentioned methods or create a param string from it and use application/x-www-form-urlencoded content-type
//builds a param=value&param2=value2 type of string from your options.data object
let paramStrings = [];
for(let key in options.data){
paramStrings.push(`${key}=${options.data[key]}`);
}
let data = paramStrings.join('&');
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
http_request.send(data);

php can not parse json data to ajax

The question is very common in stackoverflow. I have been to too many solution provided in this forum for problem like mine. but it did not help. So i am posting it. Please please be kind enough to answer me.
Problem:
I am trying to send an integer from cakephp controller function to view having ajax call.
I keep getting this error for all the solutions i tried from here and other forums.
"SyntaxError: Unexpected token a in JSON at position 0"
Please tell me what is wrong looking at my code :
I can see clearly i get data in json format in php while i make echo but not in main Ajax call.
Console says :the result is {"data":1}
Controller :
public function addit()
{
$mycount = 1;
$responseJSON = array(
'data' => $mycount
);
//$responseJSON = array('status' =>'true', 'result'=>$arr);
header('content-type:application/json');
$response = json_encode($responseJSON);
echo $response;
}
ajaxcall in view:
$(document).ready(function(){
$('#bn_cart').click(function(event){
//alert('clicked');
var form_data = $(this).serialize();
var id = $('#id').val();
alert("your item id is "+ id);
var csrfToken = <?php echo(json_encode($this->request->getParam('_csrfToken'))) ?>;
//alert("your form data "+csrfToken);
event.preventDefault();
$.ajax({
headers: {
'X-CSRF-Token': csrfToken
},
url:'../addit',
type:'POST',
data: { id : id },
dataType:'json',
success:function(xhr, response){
var respons = response;
console.log("conosle success says "+ (respons.result));
alert("success"+respons.result);
},
error:function(xhr, e,etype,response){
//alert("<br>error<br>"+ error.responseText.message);
alert("response = "+ response +"xhr = "+ xhr + " e = " + e + " etype = "+ etype);
console.log(" response =" + response + "error ="+ e +"xhr = "+ xhr + " etype = "+ etype );
// $("#result").html(error.Message);
// alert('error ='+(error.Message));
}
});
});
});
Network>Header:
Request URL: http://localhost/shoppingCart/products/addit
Request Method: POST
Status Code: 200 OK
Remote Address: [::1]:80
Referrer Policy: no-referrer-when-downgrade
Cache-Control: no-store, no-cache, must-revalidate
Connection: Keep-Alive
Content-Length: 583
Content-Type: text/html; charset=UTF-8
Date: Tue, 23 Oct 2018 14:10:08 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive: timeout=5, max=99
Pragma: no-cache
Server: Apache/2.4.29 (Win32) OpenSSL/1.0.2n PHP/7.1.15
X-DEBUGKIT-ID: 182187f0-546d-48d4-9e5a-6746a40dba64
X-Powered-By: PHP/7.1.15
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 4
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Cookie: csrfToken=0a8a1f6e98fe8274e80f9bdcb3ba5df66a5af4296126302d3e79bf44e856ed720438947bb93f041f772ac1e39d083aa2d88c5159697c9843a8b04eace893260b; CAKEPHP=mhphclr8cuvacrlotbit45dd3l; csrftoken=t0p47S5P7NBcwGGQ9sfuNGLi5JJDkll8ifuCWhG3W6MRSIewe9GtRNjanPUqms54
Host: localhost
Origin: http://localhost
Referer: http://localhost/shoppingCart/products/view/2
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
X-CSRF-Token: 0a8a1f6e98fe8274e80f9bdcb3ba5df66a5af4296126302d3e79bf44e856ed720438947bb93f041f772ac1e39d083aa2d88c5159697c9843a8b04eace893260b
X-Requested-With: XMLHttpRequest
Network>>Response :
{"data":1}
You need to return your response encoded in json. You are trying to echo a non json-encoded response which will not work.
public function addit()
{
$mycount = 1;
$responseJSON = array(
'data' => $mycount
);
//$responseJSON = array('status' =>'true', 'result'=>$arr);
header('content-type:application/json');
return json_encode($responseJSON);
}
Ajax call :
success:function(data, status, jqxhr)
var respons = data;
console.log("conosle success says "+ (respons.result));
alert("success"+respons.result);
},

How to Set value in Http Request Header

I am dealing with cross origin request to access my restful API's,so i want to set field "Authorization" in http request header on every request,but is not going to set in header...so what am doing wrong here?
My app.js
'use strict';
var app = angular.module('samepinch', [
'ngResource',
'ngCookies',
'ui.router',
'toaster',
'ui.bootstrap',
'oc.lazyLoad',
'samepinch.controllers',
'samepinch.directives',
'samepinch.factory',
'samepinch.services',
// Added in v1.3
'FBAngular',
'Config',
'samepinch.login',
'samepinch.item',
'samepinch.common'
]);
angular.module('samepinch.login',[]);
angular.module('samepinch.item',[]);
angular.module('samepinch.common',[])
app.run(function($http)
{
$http.defaults.headers.common.Authorization = '';
// Page Loading Overlay
public_vars.$pageLoadingOverlay = jQuery('.page-loading-overlay');
jQuery(window).load(function()
{
public_vars.$pageLoadingOverlay.addClass('loaded');
})
});
Controller is
angular.module('samepinch.login').controller('LoginController',['$scope','LoginService','$rootScope','$http',function($scope,LoginService,$rootScope,$http){
$rootScope.isLoginPage = true;
$rootScope.isLightLoginPage = false;
$rootScope.isLockscreenPage = false;
$rootScope.isMainPage = false;
$scope.register = function(credentials){
$http.defaults.headers.common.Authorization = 'dfdfdf';
LoginService.post(credentials,function(success){
},function(error){
});
}
}]);
My Service is
'use strict';
angular.module('samepinch.login').factory('LoginService', ['$resource','$enviornment', function ($resource,$enviornment) {
var url = $enviornment.backendurl;
return $resource(url+'authenticate',{},{
query: {
method:'GET',
params:{itemId:''},
isArray:true
},
post: {
method:'POST',
headers: {
'Authorization': 'Basic dGVzdDp0ZXN0',
'Content-Type': 'application/json'
}
},
update: {
method:'PUT', params: {itemId: '#entryId'}
},
remove: {
method:'DELETE'
}
});
}]);
My Http request looks like
Remote Address:127.0.0.1:8080
Request URL:http://localhost:8080/api/v1/authenticate
Request Method:OPTIONS
Status Code:401 Unauthorized
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, authorization, content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:8080
Origin:http://localhost:9006
Pragma:no-cache
Referer:http://localhost:9006/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36
Response Headersview source
Access-Control-Allow-Methods:POST, GET, OPTIONS, DELETE,PUT
Access-Control-Allow-Origin:*
Access-Control-Max-Age:3600
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Length:0
Date:Wed, 22 Jul 2015 07:52:15 GMT
Expires:0
Pragma:no-cache
Server:Apache-Coyote/1.1
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block
So 'Authorization' field is not set in headers..please help me what am i missing here
This log is for OPTIONS request
Request Method:OPTIONS
First you need to setup your server to return 200 OK for OPTIONS call then the POST call with proper parameters will be send
Look for instructions here http://enable-cors.org/ how to configure CORS (including OPTIONS request) on your architecture

$http angular pass object?

Hello how can i pass this object as param in Http with angular?
Because my wcg public void CreateNewAccount(Users us)
$scope.RegisterUser = function(){
var us = {
UserName:$scope.userName,
Password:$scope.password,
UserRoleID:null,
Company:$scope.company,
Terms:$scope.terms,
ID:null,
BuyerID:app.buyerId
};
$http.get(
app.wcf+'/CreateNewAccount'angular.toJson({us:us}))
.then(
function(resp){
app.Logger(resp.data);
},
function(err){
app.Logger(err);
})};
You need to pass your object as params in to the config of the $http.get(url, config) method.
$http.get(app.wcf + '/CreateNewAccount', {params: us})
.then(function(resp){
app.Logger(resp.data);
},
function(err){
app.Logger(err);
})};
That said, you shouldn't be passing this data as a GET request, especially not with a username and password in the query string.
For get, you should use params:
$http({method:'GET', url:'url', params:us})
I'm getting this it seams to call OPTIONS
Remote Address:192.168.58.182:80
Request URL:http://192.168.58.182/ESService/ESService.svc/CreateNewAccount
Request Method:OPTIONS
Status Code:405 Method Not Allowed
Request Headersview source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,pl;q=0.6
Access-Control-Request-Headers:accept, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:192.168.58.182
Origin:http://localhost:8100
Referer:http://localhost:8100/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36
Response Headersview source
Access-Control-Allow-Headers:Content-Type, Accept
Access-Control-Allow-Methods:POST,GET,OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Max-Age:1728000
Allow:POST
Content-Length:1565
Content-Type:text/html; charset=UTF-8
Date:Fri, 30 Jan 2015 14:10:34 GMT
Server:Microsoft-IIS/7.5
X-Powered-By:ASP.NET

Jquery File Upload - Not sending headers in IE9

I'm using jQuery Fileupload to upload files. Its not sending headers that I set to the server. Why is the Authorization header missing only in IE but passed in chrome?
Here is the code:
upload_photo: function(){
var url = '/api/v1/upload';
$('#photoupload').fileupload({
url: url,
dataType: 'json',
paramName: 'uploadFile',
beforeSend: function ( xhr ) {
setHeader(xhr);
$("#check_progress").html('true');
},
done: function (e, responseJSON) {
var id = responseJSON.result.id;
url = responseJSON.result.url;
var photo_ids = $("#photo_ids");
var val = photo_ids.val();
photo_ids.val(val + id.toString() + ",");
$(".photothumb-wapper").append('<div class=\"photothumb\" id="post_photo_'+id+'"><div><img src=\"'+url+'\" /></div><img class=\"thumb-delete photo_delete\" id=\"'+id+'\" title=\"Remove\" src=\"/assets/delete-red.png\"></div>');
$("#check_progress").html("");
},
start: function (e, data) {
$(".photothumb-wapper").append('<div class="photothumb photoprogress" style="border:none"><img src="/assets/ajax-loader.gif" /></div>');
},
always: function (e, data) {
$(".photoprogress").remove();
}
});
}
var setHeader = function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer fdf49c4f1cfgc176eb952f18eeefaec3e7');
};
Headers passed in IE:
Request : POST /api/v1/upload HTTP/1.1
Accept : text/html, application/xhtml+xml, \*/\*
Referer : url
Accept-Language : en-US
User-Agent :Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
Content-Type :multipart/form-data; boundary=---------------------------7de2dfe037204f6
Accept-Encoding :gzip, deflate
Host :url
Content-Length :776595
DNT :1
Connection :Keep-Alive
Cache-Control :no-cache
Cookie :sitecookies
Headers passed in Chrome:
ResponseHeaders
date : Tue, 04 Mar 2014 07:32:20 GMT
Connection: Keep-Alive
content-length:225
content-type:application/json; charset=utf-8
cache-control:no-cache
RequestHeaders
Accept: application/json, text/javascript, \*/\*; q=0.01
Authorization: Bearer fdf49c4f1cfgc176eb952f18eeefaec3e7
X-Requested-With: XMLHttpRequest
Why is the Authorization header missing in IE?
This answers my question,
Only browsers with support for XHR file upload support setting custom headers.
As a workaround in old browsers like our dear IE, you could set a cookie with the authentication token when the user authenticate and then get it in the server and verify it the same way you verify the header one. I know that it is not the most elegant solution but it works.

Categories

Resources