Http Post request in Angular JS - ajax

We are new to angular js.
We tried http request using $http.get it is working fine. But in post request it is creating an issue, it comes to success and show bad parameter error code 103.
Same we have tried in ajax request using $.ajax({}), and it is working fine.
I have also paste my code.
Can anyone help us out?
mainApp.controller('registrationCtrl', function($scope, $location, $http) {
$scope.registration = function() {
console.log("registration called");
var ws_url = "http://apparelinindia.com/selfiestandoff/WebServices/register";
var request = $http({
method: "post",
url: ws_url,
data: {
user_email: $scope.email,
user_password: $scope.password
},
dataType: 'json',
headers: {
'Content-Type': 'application/json'
}
});
request.success(function(data) {
console.log("Success" + data);
});
request.error(function(error) {
console.log("Success" + JSON.stringify(error));
});
};
});

You can use http Post in following way:
var request = $http.post(ws_url, {
user_email: $scope.email,
user_password: $scope.password
});

The name of the http method should be written in uppercase. Also, the property datatype is not awaited by $http, you should remove it:
var request = $http({
method: "POST",
url: ws_url,
data: {
user_email: $scope.email,
user_password: $scope.password
},
headers: {
'Content-Type': 'application/json'
}
});
Note, in the above call to $http you are setting the header 'Content-Type': 'application/json'. But this header is automatically injected by $http (see $http documentation), therefore you can remove it, and use the short syntax:
var request = $http.post(ws_url, data);
with data equals to:
{
user_email: $scope.email,
user_password: $scope.password
}

Are You Getting this error ??
{"status":false,"error":{"code":"103","message":"Required Parameters not found"}}
If Yes, Its Not your Problem Contact the Web service provider.
Ask him to give the valid parameter

Related

Ajax Call return error like "The POST method is not supported for this route. Supported methods: OPTIONS " in Laravel

I am fetching some data from server using ajax on page loading. But these calls always returns error as The POST method is not supported for this route. Supported methods: OPTIONS. I have tried all the options I can but no use. Here is my code.
var today = new Date();
var monthYear = moment(today).format('MMM/YYYY');
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: baseUrl + 'statisticalboxes',
method: 'POST',
data: {
'project-month': monthYear
},
success: function(data) {
console.log(data);
},
error:function(e) {
console.log(e);
}
});
web.php
Route::post('statisticalboxes', ['as' => 'statisticalboxes','uses' => 'DashboardController#getStasticalBoxData']);
I have changed method into all other options, but no use.
When I look into the network tab, the requested url look like
Request URL: http://127.0.0.1:8000/nullstatisticalboxes, but the actual one is Request URL: http://127.0.0.1:8000/statisticalboxes
Your baseUrl variable return null value.
Where you define baseUrl?
Define baseUrl variable.
--- OR ---
Use url like this.
url: '/statisticalboxes',

Wordpress returns 400 Bad Request on ajax call with fetch API

I am making a Ajax call to the admin-ajax.php with a fetch API syntax. Here is the code that calls the back-end script:
fetch(ajax_obj.ajaxurl, {
method: "POST",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
body: JSON.stringify(this.data),
headers: {
"Content-Type": "application/json"
}
})
and getting 400 Bad Request response.
Can someone tell me where does this request is not right?
When checking the Network Development Tools in chrome, I can see that the body that is sent is ok, the url is also ok...
... and as far as I know 4xx status codes are for errors on the client, so I don't even look on the server side code... if I am wrong please give me feedback on this...
Actually, I had jQuery ajax call like this:
this.data = {
'action': 'ajax_product_query',
'locations': this.locations,
'type': this.category != '' ? this.category : [],
'all-locations': this.filters['locationFilter'].all.checked,
'page': ajax_obj.current_page
};
$.ajax({
url: ajax_obj.ajaxurl,
method: 'post',
dataType: 'json',
data: this.data,
beforeSend: function(xhr) {
button.innerHTML = 'Loading...';
},
success: (data) => { ...
... and it worked like a charm...
Than, willing to remove jQuery dependency, wanted to turn the jQuery ajax call into Fetch API syntax like this:
fetch(ajax_obj.ajaxurl, {
method: "POST",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
body: JSON.stringify(this.data),
headers: {
"Content-Type": "application/json"
}
})
.then(response => response.json()) ...
And than the requests turned into 400 Bad Requests...
Thanks!
Because after JS fetch 'POST' request you can't get $_POST data in Php. Dirty solution. You could add this code in u "/wp-admin/admin-ajax.php" to resolve this:
if ( !empty( trim( file_get_contents("php://input" ) ) ) ) {
$post = trim(file_get_contents("php://input"));
$_POST = ( array ) json_decode( $post );
$_REQUEST['action'] = $_POST['action'];
}
Or try to find a better solution.
P.S. Sorry for my English

Can't set Access-Control-Allow-Origin request header

I making an AJAX request to the food2fork api and can't get by the No 'Access-Control-Allow-Origin' header is present error. I've tried setting the header in beforeSend and setting crossDomain: true but it didn't work.
This is my AJAX call:
$.ajax({
type: "GET",
dataType: 'json',
url: url,
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
},
success: function(data){
console.log('in ajax json call');
console.log(data);
$('#info').html(JSON.stringify(data));
}
});
I tried setting the request header server side in node express.js with:
router.get('/test', cors(), function(req,res)
{
res.set("Access-Control-Allow-Origin", "*"); //set header here
res.render('exampleSearch', {title: 'FM | Test'});
});
Cors is an npm package that sets cross-reference permissions but didn't help me solve the problem.
Can you tell me what I'm doing wrong?
Client-side request doesn't work in this case. I had to do the request server side:
router.post('/test', function(req,res){
var callback = function(response){
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved
response.on('end', function () {
var recipes = JSON.parse(str);
//do something with recipes
});
}
var options = {
host: "food2fork.com",
path: "/api/search?key=[myKey]&q=" + ingredients
};
http.request(options,callback).end();
});
Used code from nodejitsu.com

Extjs 4.2: How to send parameters properly in a Ext.Ajax.Request POST

I have to do a POST from my ExtJs script in order to delete something from my DB:
Ext.Ajax.request({
url: 'deleteRole.html',
method: 'POST',
headers: {'Content-Type': 'text/html'},
waitTitle: 'Connecting',
waitMsg: 'Sending data...',
params: {
"rolename" : rolename
},
scope:this,
success: received,
failure: function(){console.log('failure');}
});
when the post is sent i can see in the firebug the rolename in font but not as a param. I would like to show you another post (made with spring:form) relative to the user registration. If i inspect the post i can see the following:
(source: subirimagenes.com)
And i can get the parameters in my controller using #RequestParam.
But in the post that i have problems i can't see the parameters part, i can only see the Font(Fuente) part:
(source: subirimagenes.com)
As a consequence, my spring controller does not detect any parameter. Is it something wrong in my POST?
Thank you
The problem is that you are using the line headers: {'Content-Type': 'text/html'}, in your original question. This would set the content to text/html instead of the content being post data.
I solved it with the following code:
var rolename = 'myRol';
Ext.Ajax.request({
url: 'deleteRole.html',
method: 'POST',
params: {
rolename: rolename
},
success: received,
failure: function(){console.log('failure');}
});
I'm using this in a Sencha Touch app. I had to add an extra config called jsonData and make it true or else nothing is passed to my endpoint url.
Ext.Ajax.request({
url: endpoint,
method : "POST",
headers: {
'Content-Type': 'application/json'
},
params : {add: formattedAddress, lat: latitude},
jsonData: true,
useDefaultXhrHeader : false,
withCredentials: true,
success : function(response) {
Ext.Msg.alert("Success", 'yea');
},
failure : function(response) {
var respObj = Ext.JSON.decode(response.responseText);
Ext.Msg.alert("Error", respObj.status.statusMessage);
}
});

ExtJs 4.1 : How to send json data in the request body using Ext.Ajax.request()?

I would like to send json data using Ext.Ajax.request() then access it in ASP.NET using Request.InputStream which is the content of the request body. I need a way to tell ExtJs to write the data in the request body as it is done while using an Ext.data.proxy.Ajax.
Specify POST method and just use the request's jsonData config:
Ext.Ajax.request({
url: 'myUrl',
method: 'POST',
params: {
requestParam: 'notInRequestBody'
},
jsonData: 'thisIsInRequestBody',
success: function() {
console.log('success');
},
failure: function() {
console.log('woops');
}
});
If you want a record written as JSON you can use a JSON writer like this also.
var writer = Ext.create('Ext.data.writer.Json'),
record = Ext.getStore('SomeStoreID').first();
Ext.Ajax.request({
url: 'myUrl',
method: 'POST',
params: {
requestParam: 'notInRequestBody'
},
jsonData: writer.getRecordData(record),
success: function() {
console.log('success');
},
failure: function() {
console.log('woops');
}
});

Resources