Ajax does not want to send me a PUT query - javascript

I want to send to the controller a new e-mail given by the user using ajax
$.ajax({
type: 'PUT',
url: '/changeEmail?',
data: {
email: function() {
return $('#email').val();
}
},
success: function(result) {
console.log('function');
if(result === true) {
console.log("true");
} else {
console.log("false");
}
}
});
To the controller (sample code)
#PutMapping("/changeEmail")
public boolean changeEmail(
#RequestParam("email") String email
) {
System.out.println("email: " + email);
return true;
}
However, when dispatching, the browser console throws me out
jquery-3.2.1.min.js:4 PUT http://localhost:8080/signIn net::ERR_TOO_MANY_REDIRECTS
Ajax is trying to send data to a completely different address than the one I provided in ajax.
In Ajax I gave
/changeEmail
And he is trying to send me on
/signIn
What this is about?

A couple of issues here. Firstly remove the ? from the end of the URL. jQuery will add it automatically, if required.
Secondly don't provide a function in the object you set to data. Give the value directly. Also, result will be a string, so your comparison to a boolean will not work as you expect. To be safe while testing, it's best to just log the response directly. Try this:
$.ajax({
type: 'PUT',
url: '/changeEmail?',
data: {
email: $('#email').val();
},
success: function(result) {
console.log(result);
}
});
Lastly, if your request is being redirected from /changeEmail to /signIn, then it sounds like you will need to authenticate the request. Exactly how you do that varies from one API to another, so I'd suggest you check their documentation.

Related

Sending Ajax to controller

I am trying to get live validation on a register form that tells the user if the username they are trying has already been taken or not. I am using jQuery to detect change in the input and want to send the username they type as an AJAX to a Spring controller I have set up. Eventually it will plug it into a query and return if that username has already been registered. I am having trouble with the AJAX. Any ideas on how to accurately send the request?
My AJAX:
$(document).ready(() => {
function checkPassword() {
let usernameGiven = $("#username").val();
$.post( "/check",
{username: usernameGiven} ,
function(data) {
console.log(data)
})
}
$('#username').on('input', () => {
checkPassword()
});
});
My Controller:
#PostMapping("/check")
public String checkUsername(#RequestParam(name = "username") String username){
}
I haven't used jQuery in a long time but I don't think you can pass data with your post using that syntax. Try:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
dataType is the type of data you expect back from the server (xml, json, script, text, html).
While you're testing this, make sure you're actually returning some data back from your controller too, even if it's just mock data for now.
Maybe can work if you use:
<input id="username" onBlur="checkIfUserExist()">
Make a javascript function:
function checkIfUserExist() {
$.ajax({
url: "/check",
data:'username='+$("#username").val(),
type: "POST",
success:function(data){
console.log(data); //content user availability status
},
error:function (){}
});
}
}
Think I found what I was looking for. This is working for me. Let me know if you think there is a more efficient way of doing this.
#RestController
public class TestController {
#GetMapping("/getString")
public String getString(#RequestParam(name = "username") String username) {
return JSONObject.quote(username);
}
}

How to prevent Backbone.js routing (or history) to automagically add parameters to GET-request?

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);
}
}
});
}

Ajax post not received by php

I have written a simple code. In order to avoid flooding a JSON server, i want to break up the JSON response in pieces. So my jquery code should be parsing one variable ("page") to the php page that handles the JSON Oauth Request. On success, it should append the DIV with the latest responses.
My code should be working, except for the fact that my ajax post is not being received by my php file.
Here goes
archief.html
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: page,
success: function() {
console.log(page);
$.get("trytocombinenewageandgettagsendates.php", function(archief) {
$('#archief').append(archief);
});
},
error: function(err) {
alert(err.responseText);
}
});
return false;
});
The php file doesn't receive anything.
var_dump($_POST);
gives me array(0) { }.
Very strange, i'd really appreciate the help!
You are sending a string instead of key-value pairs. If you want to use $_POST you need to send key-value pairs:
...
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function() {
...
If you send a single value or string, you would need to read the raw input.
Also, you are sending 2 GET requests and 1 POST request to the same file. Is that intentional? Note that only the POST request will have the $_POST variable set.
Thank you for your help and not letting me post "this still doens't work" posts :)
I made the mistake of loading the "unConsulted" php file [$.get("trytocombinenewageandgettagsendates.php"] upon success. Instead, i append the response of the PHP.
The working code below:
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
//$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function(response){
$("#archief").append(response);
},
error: function(err) {
alert(err.responseText);
}
});
return false;

Calling a C# method from JavaScript

I want to to call a method GetAccount from my controller AccountController.cs, in my JavaScript factory LoginFactory.js. Something like this:
AccountController.cs:
public Account GetAccount(string userName)
{ ... }
LoginFactory.js:
if(x>y) {
var account = <%AccountController.GetAccount(someParam);%>
}
I've tried using [WebMethod] and Ajax, but I can't get it to work: I get a 404 response.
Assuming your GetAccount method can be reached at /Account/GetAccount when your application runs, you could use the following:
$.ajax({
type: 'GET',
url: '/Account/GetAccount',
data: { 'username' : 'a-username' },
dataType: 'json',
success: function(jsonData) {
alert(jsonData);
},
error: function() {
alert('error');
}
});
Note - this is dependant on jQuery.
This causes the browser to make a request to /Account/GetAccount as if you had done so by entering the URL in the URL bar, but of course, captures the returned json for use in your client side (javascript) script.
If this returns a 404, it would be worth checking your routing.

how to call web service rest based using ajax + jquery

I am calling web service on this url .
here is my code .
http://jsfiddle.net/LsKbJ/8/
$(document).ready(function () {
//event handler for submit button
$("#btnSubmit").click(function () {
//collect userName and password entered by users
var userName = $("#username").val();
var password = $("#password").val();
//call the authenticate function
authenticate(userName, password);
});
});
//authenticate function to make ajax call
function authenticate(userName, password) {
$.ajax({
//the url where you want to sent the userName and password to
url: "",
type: "POST",
// dataType: 'jsonp',
async: false,
crossDomain: true,
contentType: 'application/json',
//json object to sent to the authentication url
data: JSON.stringify({
Ticket: 'Some ticket',
Data: {
Password: "1",
Username:"aa"
}
}),
success: function (t) {
alert(t+"df")
},
error:function(data){
alert(data+"dfdfd")
}
})
}
Response
**
**
It mean that I first call this method then call login method ?
Perhaps the message means that during development, while you are writing and testing the code, use the URL:
http://isuite.c-entron.de/CentronServiceAppleDemoIndia/REST/GetNewAuthentifikationTicket
rather than:
http://isuite.c-entron.de/CentronService/REST/Login
Because you don't need the application id for the development method. You can see from the error message that you are missing the application (gu)id
The guid '61136208-742B-44E4-B00D-C32ED26775A3' is no valid application guid
Your javascript needs to be updated to use new url http://isuite.c-entron.de/CentronServiceAppleDemoIndia/GetNewAuthentifikationTicket as per the backend sode team.
Also, even if you do this, your will not be able to get reply correctly since service requires cross domain configuration entries in web.config. You have to use this reference:http://encosia.com/using-cors-to-access-asp-net-services-across-domains/ and configure server's web.config in a way so that you can call it from cross domain.

Categories

Resources