Posting JSON with variable using Ajax in [duplicate] - javascript

This question already has answers here:
jQuery posting valid json in request body
(2 answers)
Closed 4 years ago.
I was trying to put variable into JSON. I want to post it using Ajax.
My code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var user_Details = "1528205024";
function checkUserForDashboard(){
$.ajax({
url: "api comes here",
type: "POST",
data: {"user_id": user_details },
dataType: "json",
crossDomain : true,
success: function (data) {
console.log(data);
}
})};
</script>
The post request gives: bad request error.

Enclose your JSON object into JSON.stringify() to ensure your json object is serialized in a safe string.
Also, set the content-type property.
$.ajax({
url: "api comes here",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({"user_id": user_details }),
dataType: "json",
crossDomain : true,
success: function (data) {
console.log(data);
}
})};

Related

can't get any file data, It shows file data empty [duplicate]

This question already has answers here:
jQuery AJAX file upload PHP
(5 answers)
Closed 5 years ago.
I did this for uploading files via ajax.
But I can't get any file data. It shows file data empty.
Here is my ajax part.
$("#personal_image").on('click',function(event) {
event.preventDefault();
var datastring = $("#personal_image").serialize();
console.log(datastring);
$.ajax({
type: "POST",
url: location.origin+"/user/parsonal_image_submit/",
secureuri :false,
fileElementId :'user_image',
data: datastring,
dataType: "json",
success: function(data) {
//success },
error: function() {
//error
}
});
})
Check below code. Hope it will work for you. Please use on form submit rather then using on click.
$('#your_form_id').on('submit',function(e){
e.preventDefault();
var formdata = new FormData($(this)[0]);
var url = $('#personal_image').attr('action');
$.ajax({
url: url,
type: 'post',
data: formdata,
dataType: 'json',
processData: false,
contentType: false,
//async: false,
success: function(data){
//success
}
});
});

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

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

How to post multiple sets of data as a single variable in an ajax request?

I currently have a jQuery ajax function which posts a multi-dimensional array to my server.
$.ajax({
type: "POST",
url: "Default.aspx/SaveQuoteProcesses",
data: "{'items':" + JSON.stringify(jaggedArray) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg){
console.log('Success');
},
error: function (){
console.log('Fail');
}
});
Here is an example of the dataset I'm currently posting to the server:
[
{"QpcOpsID":"22","QpcQitID":"63"},
{"QpcOpsID":"20","QpcQitID":"63"},
{"QpcOpsID":"26","QpcQitID":"63"},
{"QpcOpsID":26,"QpcQitID":"63","QpcPprID":6,"PprQuestion":"How many colors?","AnswerValue":"4"}
]
I now need to send a regular array to the server in the same AJAX request.
["22", "20", "26"]
How can I include this new array in the existing javascript object?
var data = {
items: jaggedArray,
newArray: ["22", "20", "26"]
};
And then just JSON.stringify(data).
You could add the array as another property of the sent JSON -
data: "{'items':" + JSON.stringify(jaggedArray) + ",'additionalArray':"+JSON.stringify(YOUR_ARRAY)+"}",

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