Server does not receive data from ajax call - javascript

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

Related

How to express != in URLs

I wrote the following ajax call to fetch data using the nb (number of document view) parameter:
if ($("#fetch").hasClass("active")) {
$.ajax({
url: "ServletAjaxController",
type: "POST",
dataType: "json",
data: "c=" + controller + "&nb=300",
success: onSuccess,
contentType: "application/x-www-form-urlencoded;charset=UTF-8"
});
}
Now I want to do the same thing but expressing nb != 300 instead of the equal expression. Any IDEAs?

Transmitting Form Data via Json

I believe I am making a very basic mistake somewhere.
I have a Form I want to transmit to a PHP page. I also want to send a parameter with that information so I have created a basic 2D array:
$fd['api'] -> contaning the parameter as a string
$fd['body'] -> containing the form data
I am struggling to transmit this array "$fd" as a json string and believe I am using the javascript syntax incorrectly somewhere as I do not often use Javascript.
Any Help would be appreciated.
function admin_statistics_form_send(){
var fd = []
fd['api'] = "refresh_all"
fd['body'] = new FormData(document.getElementById("admin_statistics_form"))
var jsonstring = fd
console.log(jsonstring)
$.ajax({
async: true,
beforeSend: function(){
},
url: "admin_statistics_api.php",
type: "POST",
data: jsonstring,
dataType: "json",
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function (data) {
console.log(data)
},
error: function(data) {
console.log(data)
}
})
}
You only want to send the FormData object. To add other key/value pairs you append to that object:
function admin_statistics_form_send(){
var fd = new FormData($("#admin_statistics_form")[0]);
fd.append('api',"refresh_all");
$.ajax({
//async: true, // redundant since it is default and should never use `false`
beforeSend: function(){
},
url: "admin_statistics_api.php",
type: "POST",
data: fd,
dataType: "json",
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function (data) {
console.log(data)
},
error: function(data) {
console.log(data)
}
})
}

Ajax JSON access array from the array JSON encode server respond

I have an array JSON encode respond when the ajax JSON throw a post request (refer below).
requestparser.php:
$array = array("phweb" => "yes", "phemail" => "yeeess");
echo json_encode($array);
And this Ajax JSON use for sending post request to requestparser.php and processing the return response.
$.ajax({
type: 'POST',
url: 'requestparser.php',
data: { "request" : "pull" },
contentType: "application/json; charset=utf-8",
dataType: 'json',
cache: false,
success: function(result) {
alert(result[0]);
alert(result[1]);
}
});
I want to get the value of array key phweb and the value of array key phemail yet when an alert box popup, it says undefined. What seems the problem? Any help, ideas, clues would be greatly appreciated.
So far what I tried is:
$.ajax({
type: 'POST',
url: 'requestparser.php',
data: { "request" : "pull" },
contentType: "application/json; charset=utf-8",
dataType: 'json',
cache: false,
success: function(result) {
alert(result[0]->phweb);
alert(result[1]->phemail);
}
});
And sadly, it doesn't work.
The result is a JSON object. You can access it like this
success: function(result) {
alert(result['phweb']);
alert(result['phemail']);
}

Accessing ajax POST response in javascript

I'm making ajax POST request from javascript function:
function UpdateMetrics() {
$.ajax({
type: "POST",
url: "MyHandler.ashx?Param1=value1",
data: "{}",
contentType: "text/json; charset=utf-8",
dataType: "text",
success: function (msg) {
var jsonUpdatedData = msg;
...
}
});
}
From my handler, I'm sending json string with:
context.Response.write(json);
I think I'll get it in msg.
I also want to send other string (count). So I'm trying to use header info along with json data. So I added this line:
context.Response.Headers.Add("MaxCount",Convert.ToString(tempList.Count));
If this is right way to do it, how can I access it in my success function?
To access headers in your success function, add in 2 more arguments to your function, the status code and the jqXHR object, which you can read the documentation for at api.jquery.com.
So, your function should look like:
success: function (msg, status, jqXHR) {
var jsonUpdatedData = msg;
...
}
However, as pointed out in comments, it's probably best not to use the header to send data. You should probably just include it in the json you send out.
You also need to tell jQuery to interpret the response as json by setting
dataType: "json"
Otherwise, it will just be returned to you as text.
Your requirement to get the header data in ajax post success can be achieved using getResponseHeader method please refer the below code snippet.
function UpdateMetrics() {
var callback = $.ajax({
type: "POST",
url: "MyHandler.ashx?Param1=value1",
data: "{}",
contentType: "text/json; charset=utf-8",
dataType: "text",
success: function (msg) {
var jsonUpdatedData = msg;
var headerdata = callback.getResponseHeader("MaxCount");
// Where MaxCount is name provided in the header.
...
}
});
}
Thanks

jquery Post , data object

I try to understand one thing.
I want to post an object with jquery Ajax POST , something like this:
var dataPostYear = {
viewType:GetViewType(),
viewDate:'2009/09/08',
languageId:GetLanguageId()
};
$.ajax({
type: "POST",
url: url,
data: dataPostYear,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnLoadYearListSuccess,
error: OnLoadYearListError
});
and it doesn't work.
But this one works fine:
var dataPostYear = "{viewType:'"+ GetViewType() + "',viewDate:'2009/09/08',languageId:'"+GetLanguageId()+"}";
$.ajax({
type: "POST",
url: url,
data: dataPostYear,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnLoadYearListSuccess,
error: OnLoadYearListError
});
GetViewType() return --'0'
languageId() return --'1'
it's just a string
there is a way to post an object, something what I try to do in my first way ? Or not ?
Thanks
Use jQuery.param(). Here is the documentation
You should look at .postJSON.
Essentially, you just add json as a 4th argument to the $.post
From the site:
// Send the request
$.post('script.php', data, function(response) {
// Do something with the request
}, 'json');
If you want the .ajax call version, you can convert it using the .post docs.

Categories

Resources