AJAX request, redirect with params - javascript

$.ajax({
url: baseUrl,
type: "post",
contentType: "application/json",
dataType: "json",
success: function (data) {
window.location = ('http://localhost:9000/#/home.html?' + (data.search))
},
data: JSON.stringify(body),
});
return false;
}
};
this is my ajax request, it sends as JSON and it returns an object
ie. search = {firstName: km, lastname: b}
However, ajax isnt setting the content type to JSON for the params in the redirect. It is still sending as an object. JSON stringify does not work. Is there a way to set the content type to JSON inside the success/redirect function?
JSON.stringify just decodes the object into
%7B%22clientName%22:%blah%22,%22em%22:%22mLigDACsBihAL2RETse06351MuCNehZQ%22,%22partnercode%22:%blah%22%7D

You can use $.param:
var qs = $.param(data.search);
window.location = 'http://localhost:9000/#/home.html?' + qs;

This is probably because it trying to send an object to your window.location part.
What you probably need is this:
window.location = ('http://localhost:9000/#/home.html?firstName=' + data.search.firstName + "&lastname=" + data.search.lastname)

Related

How to pass query string parameter to ajax call from data

I'm using ajax call for hit the API & i want to send an query parameter, How can i send query parameter with ajax call. Here is my code. Any help on this will be appreciated, Thanks.
$("[id*=btnok]").click(function (e) {
e.preventDefault();
var obj = {};
obj = $.trim($("[id*=nodays]").val());
$.ajax({
url: "/apilink",
"data": {
"api": "api",
"params": "?userType=driver&type=true&count=" + obj
},
type: "post",
dataType: "json",
success: function (r) {
console.log(r)
}
});
});
As you're sending a POST request any properties in the data object will be added to the body of the request. To force a value to be sent in the querystring you need to manually append it to the string you provide to the url property.
Also note that defining obj as an empty object is redundant as $.trim() always returns a string.
$("[id*=btnok]").click(function (e) {
e.preventDefault();
var obj = $.trim($("[id*=nodays]").val());
$.ajax({
url: "/apilink?params=" + obj,
data: {
api: "api",
},
type: "post",
dataType: "json",
success: function (r) {
console.log(r)
}
});
});
As I see you make a post request so parameters are passed in params property in request body. But as an option you can add string params to your /apilink. Like that: /apilink?param1=val1&param2=val2

Cannot retrieve data from ajax with request

I'm having problems retrieving data from an ajax post in an easy aplication, just making some tests.
I'm working with something easy:
I have 2 classes:
Controller.java:
#RequestMapping(value = "/urlpost", method = {RequestMethod.GET, RequestMethod.POST} )
public urlPostTest(HttpServletRequest request, HttpServletResponse response) {
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("post_name");
String age = request.getParameter("post_age");
System.out.println("His name is: " + name);
System.out.println("His age is: " + age);
}
And
PostingClass.js
function posting(){
$.ajax({
url: 'urlpost',
method: 'POST',
data: {
'post_name': "Peter",
'post_age': "22"
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
console.log("Send data: SUCCES.");
}
});
}
The ajax goes correctly to the url, but the request is always null.
What could be the problem?.
Thanks.
request.getParameter("post_name"); // works on application/x-www-form-urlencoded
To get the data from a application/json request, use something like this:
String jsonStr = IOUtils.toString(request.getInputStream());
JSONObject jsonObj = new JSONObject(jsonStr);
String name = getString("name");

Pass Query String Parameters to WebService Using $.ajax POST

If I have a webservice that needs several querystring parameters in order to query the underlying DB, should I place them in the URL or can I place them into a variable which is then passed to the data parameter of the $.ajax request? Part of my question is simply - What exactly does the data parameter represent?
In the snippet below, targetURL is successfully passed in as the URL. However, when I try and passing 'parameters' as the data parameter(data: parameters), the call fails.
function JSONTest() {
//var targetURL = "http://localhost:49633/compass/compatability/webservices/SearchDatabase.ashx?mode=contact&searchvalue=" + encodeURI(document.getElementById("jsonInput").value) + "&format=json";
var targetURL = "http://localhost:49633/compass/compatability/webservices/SearchDatabase.ashx";
var parameters = "mode=contact&searchvalue=da&format=json";
document.getElementById("targetURL1").innerText = targetURL;
document.getElementById("ResultTable").innerHTML = "";
$.ajax({
type: "POST", //rest Type
url: targetURL,
data: parameters,
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (jqXHR, textStatus) {
jsonResponse = $.parseJSON(jqXHR.responseText);
for (i = 0; i < jsonResponse.length; i++) {
if (i % 2 == 0) {
createTableRow(i, "tableRow");
} else {
createTableRow(i, "tableRowAlternating");
}
}
document.getElementById("ReturnTest2").style.display = "block";
}
});
};
If you want json sent as your contentType implies then you need to change your data from urlencoded string to json by starting with an object then stringifying that object
var data = {
mode: 'contact',
searchvalue: 'da',
format: 'json'
}
var parameters = JSON.stringify(data);
If you are expecting standard form encoded data at server then remove:
contentType: "application/json; charset=utf-8",
Also never ever use async: false, it is deprecated and has always been a terrible practice

ajax post truncating leading zero's

I have the following code:
$.ajax({
type: "Post",
url: 'http://example.com/jambo',
contentType: "application/json",
data: String(' ' + $('InputTextBox').val()),
success: function (data) {
alert("success");
},
error: function (msg) {
var errmsg = JSON.stringify(msg);
alert("message: " + errmsg);
}
});
The value in InputTextBox has leading 0's but when this is posted to the url the leading 0's are truncated.
When sending json to a server, you should use the built-in JSON.stringify method to create json rather than creating it manually.
$.ajax({
type: "Post",
url: 'http://example.com/jambo',
contentType: "application/json",
data: JSON.stringify($('InputTextBox').val()),
success: function (data) {
alert("success");
},
error: function (msg) {
var errmsg = JSON.stringify(msg);
alert("message: " + errmsg);
}
});
This will result in sending "0005" instead of 0005, which when parsed, will be converted back into the string rather than a number which will lose the leading zeros.
Testing the code on this page;
$.ajax({
type: "Post",
url: '/test',
contentType: "application/json",
data: String(' 004'),
success: function (data) {
alert("success");
},
error: function (msg) {
var errmsg = JSON.stringify(msg);
alert("message: " + errmsg);
}
});
obviously alerts the 404 page but in the net tab of Chrome and Firefox shows the data is sent correctly ' 004'.
Please re ask your question with the code on the server, as the issue is not client side.
As Kevin B noted ' 004' is a type numeric according to the JSON specification
so if you want the zeros and want to use a JSON library on the server sent the data as '" 004"' or use JSON.stringify(' 004').
Removing contentType: "application/json", in my ajax call fixed the issue for me
Reason:-
contentType: "application/json", will get the values first converted to numbers as it tries to parse your data to JSON. Removing this line from your ajax call will stop the parsing of data.
Note : The parsing will happen not only in your data you are POSTing, but also it will parse the queryStrings in your URL when you use GET method

Server does not receive data from ajax call

I have a problem. I'm trying to send content of a textarea with an ajax call, but it doesn't seem to be working, and I don't know why.
There's the method called GetStatus(string statusText) which need to receive the content.
Here's the javascript code:
$("#btnSaveStatus").on("click", function () {
var statusText = $(".textareaEdit").val();
$.ajax({
type: "GET",
url: "Default.aspx/GetStatus",
data: "{statusText:'" + statusText + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// $('#littlbioID').text(result.d);
}
});
});
Please advise. You should also know that I'm new into web development.
You can't have a request body in a GET request, you have to use a POST request for that
The string you are constrcting is not valid JSON since:
Property names must be strings
You have no idea what the user will enter in the textarea - it might contain characters with special meaning in JSON
Generate your JSON programatically.
{
type: "POST",
url: "Default.aspx/GetStatus",
data: JSON.stringify({
statusText: statusText
}),
// etc
Obviously, the server side of the process needs to be set up to accept a POST request with a JSON body (instead of the more standard URL Form Encoded format) as well.
Try this:
$("#btnSaveStatus").on("click", function () {
var statusText = $(".textareaEdit").val();
var jsonText = new Object();
jsonText.statusText = statusText;
$.ajax({
type: "POST",
url: "Default.aspx/GetStatus",
data: JSON.stringify(jsonText);,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// $('#littlbioID').text(result.d);
}
});
});

Categories

Resources