I am trying to make a post request to my api which saves the data that I send through my request. I have tried all the solutions that I found here on SO but none worked.
This is how I am sending the request through ajax:
var data={
apiname: 'register', first_name: fname, last_name: lname, email_address: email,
acc_pass: pass, coach_phone: phone, coach_dob: dob, profile_picture: myFile,
coach_address: address, coach_state: state, coach_city: city, zip_code: zip, coach_bio: about,
teaching_locations: teaching, playing_exp: playing_exp, teaching_exp: teaching_exp,
private_lesson_rate: private_rate, group_lesson_rate: group_rate, certification: certifications,
any_crime: 'No', us_citizen: 'Yes', allowed_contract_work: 'Yes', agree_terms: 'Yes',
virtual_session: sessions
};
$.ajax({
type: "POST",
url: "my-url/signup_api.php",
processData: false,
contentType: "application/x-www-form-urlencoded",
dataType: 'json',
data: data,
success: function (data2) {
if (data2.status == '200') {
alert(data2.message);
}
else {
showError(data2.message, 3000);
}
},
error: function (jqXHR, exception) {
alert(exception);
}
});
I don't want to send the data in a json way like json.stringify. The variables (fname, lname etc) are the input fields of my form and I am getting the values like this:
var fname = $("#first_name").val();
and same for all the other variables. And on my php side, I am trying to access the data like this:
if($_POST['apiname']=="register"){
//do stuff
}
But my code never gets inside this if statement. Been stuck on this since last 2 days now.
Related
Good evening SO, this been bugging me for a few hours already and still haven't figure out how to fix this.
All of my request data is fine except for subscriptionTag, it's value is always null whenever i send the request to server. I even tried removing JSON.stringify but it gives me false value instead.
Edit : Added HTTPPost in controller and type: post in javascript, i'm having an 500(internal server error) now :(
Edit 2 : Added Request Payload and Request URL
Request URL: http://localhost:49895/exclusive/send
Request Payload:
subscriptionTag=%7B%22IsAutomotive%22%3Atrue%2C%22IsMusicandDance%22%3Afalse%2C%22IsBeautyLifestyle%22%3Atrue%2C%22IsNighlifeEvent%22%3Afalse%2C%22IsFashion%22%3Afalse%2C%22IsRestaurantBar%22%3Afalse%2C%22IsHealthAndFitness%22%3Afalse%2C%22IsSportsOutdoor%22%3Afalse%2C%22IsHomeDecor%22%3Afalse%2C%22IsTravel%22%3Afalse%7D&pageid=33&emailAddress=gabyap1390%40gmail.com&token=cz0xJmV4Y2x1c2l2ZUlkPTM20&FirstName=Gabriel&source=%2Fsiggpay&MembershipLevelId=33
.NET
`
[HttpPost]
[Route("~/exclusive/send")]
public JsonResult Send(SubscriptionTag subscriptionTag, int pageid, string EmailAddress, string token, string FirstName = "", string source = "", int? MembershipLevelId = null)
{
return Json(new { error = false }, JsonRequestBehavior.AllowGet);
}
`
JAVASCRIPT
var subscriptionTag = {};
subscriptionTag.IsAutomotive = $('#IsAutomotive').is(":checked");
subscriptionTag.IsMusicandDance = $('#IsMusicandDance').is(":checked");
subscriptionTag.IsBeautyLifestyle = $('#IsBeautyLifestyle').is(":checked");
subscriptionTag.IsNighlifeEvent = $('#IsNighlifeEvent').is(":checked");
subscriptionTag.IsFashion = $('#IsFashion').is(":checked");
subscriptionTag.IsRestaurantBar = $('#IsRestaurantBar').is(":checked");
subscriptionTag.IsHealthAndFitness = $('#IsHealthAndFitness').is(":checked");
subscriptionTag.IsSportsOutdoor = $('#IsSportsOutdoor').is(":checked");
subscriptionTag.IsHomeDecor = $('#IsHomeDecor').is(":checked");
subscriptionTag.IsTravel = $('#IsTravel').is(":checked");
$.ajax({
url: MyAppUrlSettings.MyUsefulUrl,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
data: {
subscriptionTag: JSON.stringify(subscriptionTag),
pageid: pageid,
emailAddress: emailAddress,
token: token,
FirstName: firstName,
source: source,
MembershipLevelId: membershipLevelId
},
success: function (result) {
if (result.error == false)
location.href = ""
}
});
},`
Just in case you might ask, heres my query string parameters.
subscriptionTag: {"IsAutomotive":false,"IsMusicandDance":false,"IsBeautyLifestyle":true,"IsNighlifeEvent":true,"IsFashion":false,"IsRestaurantBar":true,"IsHealthAndFitness":true,"IsSportsOutdoor":false,"IsHomeDecor":false,"IsTravel":false}
pageid: 33
emailAddress: gabyap1390#gmail.com
token: cz0xJmV4Y2x1c2l2ZUlkPTM20
FirstName: Gabriel
source: /siggpay
MembershipLevelId: 33
Thanks to all who commented on this but I managed to fix my problem I change my data from
data: {
subscriptionTag: JSON.stringify(subscriptionTag),
<code>some code here</code>
},
into
data: JSON.stringify({
subscriptionTag: subscriptionTag,
<code>some code here</code>
}),
That's how I reach when I send some values that are specified in my input and therefore they need to send to a API.
When I try to send them to the monkey, my monkey tells me that nothing has been sent.
At my console.log(token), it tells me what data is available and I also agree that it all fits together. But the problem is just that it has to come over to my API.
function PayStripe() {
// Open Checkout with further options:
handler.open({
name: 'XXX ',
description: 'XX abonnement',
currency: "dkk",
amount: $('#HiddenPrice').val() * 100,
email: $('#Email').val()
});
};
// Close Checkout on page navigation:
$(window).on('popstate', function () {
handler.close();
});
var handler = StripeCheckout.configure({
key: 'pk_test_xxxx',
locale: 'auto',
token: function (token) {
token.subscriptionId = $('#SubscriptionId').val();
token.City = $('#City').val();
token.Postnr = $('#Postnr').val();
token.Mobil = $('#Mobil').val();
token.Adresse = $('#Adresse').val();
token.CVRVirksomhed = $('#CVRVirksomhed').val();
console.log(token.subscriptionId);
console.log(token);
$.ajax({
type: "POST",
url: "/api/Stripe",
contentType: "application/json",
data: token,
success: function (data) {
//window.location.href = '/Subscriptions/Succes';
alert(data + "Succes")
},
error: function (data) {
console.log(data + "Error");
},
dataType: 'json'
});
// You can access the token ID with `token.id`.
// Get the token ID to your server-side code for use.
}
});
Where the problem lies is that the API is by no means able to get informed information from jquery. so it's like it can not / will receive it.
[HttpPost]
[Route("api/Stripe")]
[Produces("application/json")]
public async Task<IActionResult> Post([FromForm] JObject token)
When I grab the token that I need for example. then I do this here:
var SubscriptionId = (int)token.GetValue("subscriptionId");
When you set contentType: "application/json", you need to stringify the data to json yourself
data: JSON.stringify(token),
I have a very strange issue here, that I think has got something to do with the Backbone.js routing.
In our mobile app, there is a login-screen, that executes a AJAX-Post-Request (with jQuery), that runs against an API. Username, password and a third parameter are in the POST-body. This works like a charm.
The strange behaviour kicks in, after Backbone.js begins to to do some routing. After re-directing the browser, (only!) the username and password are send as a parameter-list to the GET request.
So the request i.e.
http://localhost:3000/#login
for unknown reason becomes
http://localhost:3000/?username=myuser&password=mypassword#login
Please notice, that the new parameters in the GET-request are not 100% part of the POST-body, because the savePassword-parameter is missing. Also notice, that the login-request goes against the API, (/api/user/login), not the route of the login-screen (/#login)
I already tried out a lots of things, also taking all the backbone-sourcecode apart, but still can't find how to prevent this behaviour.
Another notice: I see this only on mobile, so in the UIWebView on iOS and the WebView-object on Android. Maybe this issue is also related to the mobile...
I am very happy for any help, answers or hints, how to disable this behaviour and get the username/password out of this freakin URL.
Edited:
This is the AJAX-Request for loggin in.
login: function(username, password, savePassword, successcallback, errorcallback) {
$.ajax({
method: 'POST',
dataType: 'json',
url: config.api_base_url + 'user/login',
data: {
username: username,
password: password,
savePassword: savePassword
},
success: function(data, response, xhr) {
app.auth_token = xhr.getResponseHeader('Authtoken');
$.cookie('auth_token', app.auth_token);
if (successcallback) {
successcallback();
}
},
error: function(data) {
if (errorcallback) {
errorcallback(data);
}
}
});
}
According to jQuery.ajax() docs:
data
Type: PlainObject or String or Array
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must
be Key/Value pairs. If value is an Array, jQuery serializes multiple
values with same key based on the value of the traditional setting
(described below).
And than, you should add in your settings processData equal to false:
processData (default: true)
Type: Boolean
By default, data passed in to the data option as an object
(technically, anything other than a string) will be processed and
transformed into a query string, fitting to the default content-type
"application/x-www-form-urlencoded". If you want to send a
DOMDocument, or other non-processed data, set this option to false.
Code jQuery.ajax():
login: function(username, password, savePassword, successcallback, errorcallback) {
$.ajax({
method: 'POST',
dataType: 'json',
url: config.api_base_url + 'user/login',
data: {
username: username,
password: password,
savePassword: savePassword
},
processData: false,
success: function(data, response, xhr) {
app.auth_token = xhr.getResponseHeader('Authtoken');
$.cookie('auth_token', app.auth_token);
if (successcallback) {
successcallback();
}
},
error: function(data) {
if (errorcallback) {
errorcallback(data);
}
}
});
}
I'm trying to send JSON data from a web page using JQuery, like this:
$.ajax({
type: "post", // Request method: post, get
url: "http://localhost/ajax/login",
data: '{username: "wiiNinja", password: "isAnub"}',
dataType: "json", // Expected response type
contentType: "application/json",
cache: false,
success: function(response, status) {
alert ("Success");
},
error: function(response, status) {
alert('Error! response=' + response + " status=" + status);
}
});
In cake2.2, I have a controller named Ajax that has a method named "login", like this:
public function login($id = null)
{
if ($this->RequestHandler->isAjax())
{
$this->layout = 'ajax'; // Or $this->RequestHandler->ajaxLayout, Only use for HTML
$this->autoLayout = false;
$this->autoRender = false;
$response = array('success' => false);
$data = $this->request->input(); // MY QUESTION IS WITH THIS LINE
debug($data, $showHTML = false, $showFrom = true);
}
return;
}
I just want to see if I'm passing in the correct data to the controller. If I use this line:
$data = $this->request->input();
I can see the debug printout:
{username: "wiiNinja", password: "isCool"}
I read in the CakePHP manual 2.x, under "Accessing XML or JSON data", it suggests this call to decode the data:
$data = $this->request->input('json_decode');
When I debug print $data, I get "null". What am I doing wrong? Is my data passed in from the Javascript incorrect? Or am I not calling the decode correctly?
Thanks for any suggestion.
============= My own Edit ========
Found my own mistake through experiments:
When posting through Javascript, instead of this line:
data: '{username: "wiiNinja", password: "isAnub"}',
Change it to:
data: '{"username": "wiiNinja", "password": "isAnub"}',
AND
In the controller code, change this line:
$data = $this->request->input('json_decode');
To:
$data = $this->request->input('json_decode', 'true');
It works.
Dunhamzzz,
When I followed your suggestions, and examine the "$this->request->params" array in my controller code, it contains the following:
array(
'plugin' => null,
'controller' => 'ajax',
'action' => 'login',
'named' => array(),
'pass' => array(),
'isAjax' => true
)
As you can see, the data that I'm looking for is not there. I've already got the the proper routes code. This is consistent with what the documentation for 2.x says here:
http://book.cakephp.org/2.0/en/controllers/request-response.html
So far, the only way that I found to make it work, is as stated above in "My own Edit". But if sending a JSon string to the server is not the right thing to do, I would like to fix this, because eventually, I will have to handle third party code that will send JSon objects.
The reason you are struggling wit the data is because you are sending a string with jQuery, not a proper javascript object (JSON).
$.ajax({
type: "post", // Request method: post, get
url: "http://localhost/ajax/login",
data: {username: "wiiNinja", password: "isAnub"}, // outer quotes removed
dataType: "json", // Expected response type
contentType: "application/json",
cache: false,
success: function(response, status) {
alert ("Success");
},
error: function(response, status) {
alert('Error! response=' + response + " status=" + status);
}
});
Now the data will be available as a PHP array in $this->request->params.
Also for sending a JSON response, please see this manual page. Most of your code there can be reduced to just 2 lines...
//routes.php
Router::parseExtensions('json');
//Controller that sends JSON
$this->set('_serialize', array('data'));
I'm having a problem with my JSON response in my MVC 3 application. When JSON is responding, my browser cannot handle application/json and tries to open it as a file. However, I'm recieving the correct data in the file.
I've added this to my Global.asax file:
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
This is my javascript code:
$('#register).submit(function () {
if ($(this).valid()) {
var ai = {
Firstname: $("#Firstname").val(),
Lastname: $("#Lastname").val(),
Email: $("#Email").val()
};
var json = $.toJSON(ai);
$.ajax({
url: '/Person/Create',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("Success");
},
error: function (data) {
alert("Error");
}
})
}
});
And this is my ActionResult method:
[HttpPost]
public ActionResult Create(Person person)
{
if (ModelState.IsValid)
{
db.Personer.Add(person);
db.SaveChanges();
}
return Json(new { Success = person.ID > 0, Firstname = person.Firstname, Lastname = person.Lastname });
}
I've also added .json (application/json) to the MIME-list in IIE.
If you're trying to access a file with JSON headers in Firefox directly (meaning: you're entering the URL into the address bar), Firefox will download it as a file. However, when you call your JSON in an AJAX request, it'll work the way you want it to.