POST 400 error, ajax request - javascript

Why cant I save this, I get 400 (Bad Request),
and on headers response i get The CSRF token could not be verified.
$(document).ready(function() {
$("a#copylink").click(function (e) {
e.preventDefault();
var data = $('#campaign-form').serialize();
$.ajax(
{
contentType: "application/json; charset=utf-8",
dataType: 'json',
method: 'POST',
url: 'campaignsave',
data: data,
success: function(data){
alert(data);
}
}
)
});
});
on backend:
public function actionCampaignSave()
{
var_dump($_POST);
}

You can pass the [headers] parameter in your ajax call like this.
$.ajax({
url : 'campaignsave',
method : 'POST',,
headers : {
'X-CSRF-TOKEN' : $('input[name="token"]').val()
}
dataType : 'json',
data : data,
success : function(response) {
console.log(response);
}
});
Just make sure you've place {!! csrf_field() !!} on your [view] blade template to append the $(input[name="token"); html tag to get the token value to get the CSRF token as well. Hope this helps

Pass csrf token using headers property on ajax
$.ajax({
contentType: "application/json; charset=utf-8",
dataType: 'json',
method: 'POST',
url: 'campaignsave',
headers: { 'X-CSRF-TOKEN': 'token' }
data: data,
success: function(data){
alert(data);
}
});

Try this it may help you
$.ajax({
type: "POST",
url: 'campaignsave',
data: {test : data},
success: function(data) {
alert(data);
}
});

Related

How to send #RequestParam in AJAX POST request

I have my API which accepts Request Param:
#PostMapping(value = "/export")
#ResponseBody
public ResponseEntity<String> bulkExport(
#RequestParam(value = "managedObjects", required = false) List<String> managedObjects) {
//data
}
);
I want to send AJAX POST request.
$.ajax({
type: "POST",
//url: "policy/js_policy",
url: "/export/ ,
async: false,
data: { "managedObjects": ["Audit","Logs"]},
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (XMLHttpRequest, textStatus) {
//File Handling
}
});
I tried to send managedObjects in URL. In data also I am sending the same.But my API is not working. How to send the #RequestParam from AJAX POST request exactly?
pass a list in Query Param
$.ajax({
...
url: "/export?managedObjects=Audit,Logs" ,
...
});
pass a list in Request Body
$.ajax({
type: "POST",
url: "/export/",
...
data: {managedObjects[0]: "Audit",
managedObjects[1]: "Logs"}
...
});
Try stringifying your data:
var data = {
managedObjects: ["Audit", "Logs"]
}
$.ajax({
type: "POST",
url: "/export/",
async: false,
data: JSON.Stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (XMLHttpRequest, textStatus) {
}
});
Additionally you should use "name" instead "value" in #RequestParam:
#PostMapping(value = "/export")
#ResponseBody
public ResponseEntity<String> bulkExport(
#RequestParam(name = "managedObjects", required = false) List<String> managedObjects) {
//data
}
);
I think the problem is just with list that you want to send in your request.
var dataToSend = {
list: [{ fieldname: 'ABC' }, { fieldname: 'DEF' }]; // your list should something like this.
$.ajax({
type: "POST",
//url: "policy/js_policy",
url: "/export/?managedObjects=" + Mos ,
async: false,
data: JSON.stringify(dataToSend),
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (XMLHttpRequest, textStatus) {
}
});

How to display responded page by server using GET request in ajax call

function regCall(token){
$.ajax({
type: 'GET',
url: 'http://localhost:3000',
dataType: 'HTML',
headers: {
'x-auth': token
}
});
}
This is my ajax GET request I want to display the given url in html.
The below is the whole snippet with my login logic.
$(document).ready(()=>{
$('#login').submit((e)=>{
$.ajax({
type: 'POST',
url:'http://localhost:3000/login/users',
data: {
email: $('#email').val(),
password: $('#password').val()
},
success: function(data, status, req){
// alert(req.getResponseHeader('x-auth'));
localStorage.setItem('t',req.getResponseHeader('x-auth'));
var token = localStorage.getItem('t');
regCall(token);
// window.location.href = '/';
},
error: function (req, status, error) {
// alert(req.getResponseHeader('x-auth'));
localStorage.setItem('t',req.getResponseHeader('x-auth'));
alert('Invalid email and password');
window.location.href = '/login';
}
});
e.preventDefault();
});
})
This is the whole code of snippet.
extract response data from SUCCESS function:
function regCall(token){
$.ajax({
type: 'GET',
url: 'http://localhost:3000',
dataType: 'HTML',
headers: {
'x-auth': token
},
success: function(data){
//targetElement should be replaced by the ID of target element
$("#targetElement").html(data);
}
});
}
By using the success callback function you can display the response content on the HTML place
**First method:**
function regCall(token){
$.ajax({
type: 'GET',
url: 'http://localhost:3000',
dataType: 'HTML',
headers: {
'x-auth': token
},
success: function(responseData){
$("#div or class Id").html(responseData);
}
});
}
**Second method:**
function regCall(token){
$.ajax({
type: 'GET',
url: 'http://localhost:3000',
dataType: 'HTML',
headers: {
'x-auth': token
}
}).done(function(responseData){
$("#div or class Id").html(responseData);
});
}
**NOTE:**
Make sure you are having the jQuery script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

get the return value of success in Iron-Ajax after POST

I'm currently working the project using Polymer and I'd like to get the return value of API after POST using Iron-Ajax.
Here is my sample code,
var rs = $.ajax({
type: "POST",
url: apiUrl,
data: _data,
dataType: "json",
contentType: 'application/json'
});
rs.done(function (data) {
console.log(data);
alert(data);
}
});
Ajax is asynchronous by default,you need add async:false to make it synchronous
var rs = $.ajax({
type: "POST",
url: apiUrl,
data: _data,
async:false,
dataType: "json",
contentType: 'application/json'
});
var result = null;
rs.done(function (data) {
console.log(data);
alert(data);
result = data;
}
});
//return result;//you can return value like this

Don't know why AJAX form data is sending null to the MVC controller

I am sending a form data using AJAX and my Spring MVC controller is getting null value, but if I use Postman it will work fine.
Here is my ajax call:
$.ajax({
type: "post",
url:"http://localhost:8080/fivenet/mobile/api/login",
crossDomain: true,
data: JSON.stringify(formData),
dataType: 'json',
contentType: 'text/html;charset=UTF-8',
//contentType: 'application/json;charset=utf-8',
beforeSend: function(xhr){
},
success: function(msg){
console.log('sucess');
},
error: function(msg){}
Here is my controller:
#CrossOrigin(origins = "*", maxAge = 3600)
#RequestMapping(value = "create-account", method = RequestMethod.POST)
public #ResponseBody RespondMessage createAccount(
#RequestParam(value = "data", required = true) String dataString,
HttpServletRequest request) throws Exception {
RespondMessage responsed = new RespondMessage();
headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
JSONObject data = new JSONObject(dataString);
return responsed;
}
I have finally solved the problem. Its the way I serve my data.
$.ajax({
type: 'POST',
url: "http://localhost:8080/fivenet/mobile/api/login",
crossDomain: true,
data: {"data": JSON.stringify(formData)},*** This is where the error is
dataType: 'json',
beforeSend: function(xhr){
},
success: function(msg){
console.log('sucess');
},
error: function(msg){}
thanks all for your concerns
Try this code:
var formData = {"username" : "username", "password" : "password"};
$.ajax({
type: "POST",
url: "http://localhost:8080/fivenet/mobile/api/login",
data: JSON.stringify(formData),
dataType: 'json',
contentType: 'application/json;charset=utf-8',
beforeSend: function(xhr){
},
success: function(data){
alert(data)
},
failure: function(errMsg) {
alert(errMsg);
},
error: function(errMsg){
alert(errMsg);
}

How to get the PHP var after Jquery $.ajax

I use $.ajax to send some data to testajax.phpenter code here where data are processing. Result of this proces is link. How to get access to this? I think about sessions or cookies. Set in session $test and get access in another files.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
success: console.log('success');
data: { json : jsonObj }
});
In testajax.php I have someting like this
echo "PDF: <a href=images/test.pdf>$dir.pdf</a>";
$test = "PDF: <a href=images/test.pdf>$dir.pdf</a>";
How to get the $test or output the echo after call $.ajax
You can use success' function to get request from PHP.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'html',
data: { json : jsonObj }
success: function(data) {
var request = data;
console.log(data);
$('#link_container').html(data);
}
});
Your console now holds PDF: <a href=images/test.pdf>($dir content).pdf</a>.
Also the variable request holds the same result that you can use anywhere in the script.
Result is appended to #link_container.
Use the success() method for display the result.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
success: function (data){ // <= define handler for manupulate the response
$('#result').html(data);
}
data: { json : jsonObj }
});
Use below code It may help you.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
data: { json : jsonObj },
onSuccess: successFunc,
onFailure: failureFunc
});
function successFunc(response){
alert(response);
}
function failureFunc(response){
alert("Call is failed" );
alert(response);
}

Categories

Resources