Sending Ajax to controller - javascript

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

Related

Ajax Data Call with or without slash in Codeigniter getting error

suppose my URL is example.com/controller/method/
when I use this ajax code it makes URL like example.com/controller/method/method which not getting data.
function getProductList() {
var category = document.getElementById('Category').value;
$.ajax({
type: 'POST',
url: 'GetProductList',
data: {CategoryId: category},
dataType: 'json',
cache:false,
success: function (response) {
}
});
}
but when my URL is example.com/controller/method then ajax getting data correctly. but i want to get data from the database on both situations.
Typically there is a one-to-one relationship between a URL string and its corresponding controller class/method. So you can not use example.com/controller/method/method.The segments in a URI normally follow this pattern: example.com/class/function/id/ , So your last method argument treated as a id. so create method in controller with the default argument Ex. public function mymethod($method = ''){ /** Your logic goes here */ }

Ajax does not want to send me a PUT query

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.

Transfer to another page in AJAX call

Hi there is it possible to redirect to another page using ajax? I have this piece of code that I have been working on to try this.
<script type="text/javascript">
$(document.body).on('click', '#btnPrintPrev', function() {
$.ajax({
url: '/pdfdatacal',
data: {
dummydata: "This is a dummy data"
},
});
});
</script>
Now it should be able to carry data to another page and redirect there. Problem is it doesn't.
This is what I am using in my route
Route::get('/pdfdatacal', 'GenerateReportController#pdfdatacal');
Then in the controller
public function pdfdatacal(Request $request) {
return $request->data['dummydata'];
}
My expected result should be a blank page containing the value of dummydata but it doesn't do that in my code. How do I accomplish this?
first your ajax must be something like
$.ajax({
url: '/pdfdatacal',
method: 'post',
data: { dummydata: "This is a dummy data" },
dataType: "JSON",
success: function(response){
console.log(response); // just to check if the data is being passed
// do something you want if ever .
}
});
then in your routes
Route::post('/pdfdatacal', 'GenerateReportController#pdfdatacal');
in your controller
public function pdfdatacal(Request $request) {
return response()->json($request->dummydata);
}
hope it helps ..
Use
window.location.href = "http://yourwebsite.com/pdfdatacal";
In your success call
The idea is that you send data to your controller, it sends back a response, then you redirect from javascript to where you want.
$.ajax({
url: '/pdfdatacal',
type : 'GET',
data : {
dummydata: "This is a dummy data"
},
success : function(data) {
window.location.href = "http://yourwebsite.com/pdfdatacal";
}
});
But if your controller does nothing with the data you send, then you don't need to use ajax at all, simple redirect using javascript.
you could use window.location.assign('your URL here!'); in the success.
success : function(data) {
window.location.assign('your URL here!');
}

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.

Jquery ajax post to MVC2 action

I'm using the following script to post to and endpoint, it's hitting the breakpoint on the server so I know the routing is correct.
$(document).ready(function() {
var o = new Object();
o.message = 'Hi from the page';
$.ajax({
type: 'POST',
contentType: 'application/json;',
data: JSON.stringify(o),
dataType: 'json',
url: 'home/PingBack',
success: function(result) {
alert(result.success);
}
});
});
The endpoint on the server looks like this.
public JsonResult PingBack(MHolder message)
{
return Json(new { success = "steve"});
}
and the Model looks like this.
public class MHolder
{
public string message { get; set; }
}
I'm sure that in the past the values have been automatically bound to the model, but I can't seem to get anything to be bound atm! Even if I just pass the value as a string, I'm sure it's something silly that I'm missing any ideas?
A few things to notice. You are sending the request as a JSON string (contentType: 'application/json' and JSON.stringify(o)) while on the server you are expecting an object of type MHolder. The default model binder won't do this transformation. You will need to either write a custom model binder capable of deserializing JSON back to an MHolder instance or send the request as key=value pairs (do not stringify):
var o = new Object();
o.message = 'Hi from the page';
$.ajax({
type: 'POST',
data: o,
dataType: 'json',
url: 'home/PingBack',
success: function (result) {
alert(result.success);
}
});
The code seems OK to me, at first glance.
try using...
data : {message : "Hi from the page."},
...to see if this causes the MHolder instance to be populated.
Also, use something like Fiddler to capture your requests and allow you to see exactly what is being posted.

Categories

Resources