I'm trying to get a data from server without refreshing the page using ajax, So the problem the data come like a text not like json data
my code:
$.ajax({
type: "GET",
url: "http://localhost:8080/search?key=" + QUERY + "",
success: function (reslt) {
console.log(reslt);
console.log(reslt.length);
}
});
and the data on the server:
im using nodejs and express framework the code:
router.get('/search', function (req, res) {
tab = ['08:00', '09:00', '10:00', '11:00'];
res.end(JSON.stringify(tab));
});
why when i do console.log(reslt[3]); it's give me 8 , should give me 10:00
Use
dataType: 'json'
If your response is JSON, always set the datatype to json. Do it like this
$.ajax({
type: "GET",
dataType: 'json',
url: "http://localhost:8080/search?key=" + QUERY + "",
success: function (reslt) {
console.log(reslt);
console.log(reslt.length);
}
});
You have to use dataType and contentType attribute in your ajax request
$.ajax({
type: "GET",
dataType: 'json',
contentType: "application/json",
url: "http://localhost:8080/search?key=" + QUERY + "",
success: function (reslt) {
console.log(reslt);
console.log(reslt.length);
}
});
Related
I would like to post Json to a web service on the same server. But I don't know how to post Json using JQuery. I have tried with this code:
$.ajax({
type: 'POST',
url: '/form/',
data: {"name":"jonas"},
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
But using this JQuery code the data is not received as Json on the server. This is the expected data at the server: {"name":"jonas"} but using JQuery the server receive name=jonas. Or in other words, it's "urlencoded" data and not Json.
Is there any way to post the data in Json format instead of urlencoded data using JQuery? Or do I have to use a manual ajax request?
You're passing an object, not a JSON string. When you pass an object, jQuery uses $.param to serialize the object into name-value pairs.
If you pass the data as a string, it won't be serialized:
$.ajax({
type: 'POST',
url: '/form/',
data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Base on lonesomeday's answer, I create a jpost that wraps certain parameters.
$.extend({
jpost: function(url, body) {
return $.ajax({
type: 'POST',
url: url,
data: JSON.stringify(body),
contentType: "application/json",
dataType: 'json'
});
}
});
Usage:
$.jpost('/form/', { name: 'Jonh' }).then(res => {
console.log(res);
});
you can post data using ajax as :
$.ajax({
url: "url",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: 'value1', email: 'value2' }),
success: function (result) {
// when call is sucessfull
},
error: function (err) {
// check the err for error details
}
}); // ajax call closing
I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data
$.fn.postJSON = function(url, data) {
return $.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json'
});
The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.
var Data = {
"name":"jonsa",
"e-mail":"qwerty#gmail.com",
"phone":1223456789
};
$.ajax({
type: 'POST',
url: '/form/',
data: Data,
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Using Promise and checking if the body object is a valid JSON. If not a Promise reject will be returned.
var DoPost = function(url, body) {
try {
body = JSON.stringify(body);
} catch (error) {
return reject(error);
}
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: url,
data: body,
contentType: "application/json",
dataType: 'json'
})
.done(function(data) {
return resolve(data);
})
.fail(function(error) {
console.error(error);
return reject(error);
})
.always(function() {
// called after done or fail
});
});
}
I am trying to get the File Id using the filename in graph API
I have tried the following thing but this is not working
https://graph.microsoft.com/v1.0/sites/ccc.sharepoint.com,dddddd,eeeeeeeeeeeeeeee/drive/root:/excelDir/filename.xlsx:/children
Got the answer
https://graph.microsoft.com/v1.0/sites/"+webAndSiteId+"/drives/"+folderID+"/root/search(q='filename.xlsx')
Below is the working javascript
var fileCollectionEndpoint = "https://graph.microsoft.com/v1.0/sites/"+webAndSiteId+"/drives/"+folderID+"/root/search(q='"+fileNamesArray[index]+"')"
$.ajax({
url: fileCollectionEndpoint,
async: false,
dataType: 'json',
type: "GET",
cache:false,
headers: {
'Authorization':'Bearer '+token,
},
success: function (json) {
console.log(json.value[0].id);
},
error:function(xhr)
{
}
});
I have a webform which has x number of textboxes and y number of dropdowns etc
I am using this code to send data to webmethod at the server:
$.ajax({
type: "POST",
url: "SupplierMaster.aspx/RegisterSupplier",
data: JSON.stringify({
id: $('#txtbidderid').val(),
bidamt: $('#txtbidamt').val()
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
Now the problem is that I also want to include file attachments on this form.
How do I add the files to data: of $.ajax method?
I do not want to use external plugins etc unless absolutely necessary.
Lets say I modify my data object to look like this :
var dataToSend = {};
dataToSend.id = $('#txtbidderid').val()
dataToSend.bidamt = $('#txtbidamt').val()
dataToSend.append( 'file', input.files[0] );
What would the webmethod armument look like?
For example lets suppose it looks like this as of now:
[WebMethod] public static string SubmitBid(string id, string bidamt.....)
You can try something like this. You may need to manipulate content type.
var dataToSend = new FormData();
dataToSend.append( 'file', input.files[0] );
$.ajax({
url: "SupplierMaster.aspx/RegisterSupplier",
data: dataToSend,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
You cannot send file as application/json; charset=utf-8 to the server and so i suggest you to use application/x-www-form-urlencoded as contentType and also data as FormData as below.
$.ajax({
url: "SupplierMaster.aspx/RegisterSupplier",
type: 'POST',
data: new FormData(formElement),//Give your form element here
contentType: false,
processData: false,
success: function () {
//do success
}
});
I have searched a lot and not been able to find a working solution to why my post request is not sending it's data to the server. I can send the request without data and I get my results from the server, but I just cannot send my data to the server. I have narrowed it down to the "data" attribute and assume I am just doing something wrong. Thank you.
Client
var scriptURL = "default/scripts/serverside/Scripts.aspx";
$.ajax({
type: "POST",
url: baseURL + scriptURL + "/SaveItem",
data: "{}", //works (to return a result)
//data: "{sendData: '" + dataPackage + "'}", //does not work
//data: dataPackage, //does not work
//data: { sendData: dataPackage }, //does not work
//data: { "sendData": dataPackage }, //does not work
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
de("server result:" +result);
}
});
Server
[WebMethod]
public static string SaveItem(string sendData)
{
string result = "received: " + sendData;
return result;
}
Please help, I just cant seem to get it working and know it has got to be a syntax issue...
Similar problems I have found (but no working answers):
https://stackoverflow.com/questions/7258933/jquery-ajax-data-parameter-syntax
https://stackoverflow.com/questions/7262940/webmethod-not-being-called?lq=1
Try this one:
$.ajax({
type: "POST",
url: baseURL + scriptURL + "/SaveItem",
data: $.toJSON({ sendData: dataPackage }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
de("server result:" +result);
}
});
The toJSON will convert your JS object into a proper JSON string. You could also use JSON.stringify
Try this:
var scriptURL = "default/scripts/serverside/Scripts.aspx";
$.ajax({
type: "POST",
url: baseURL + scriptURL + "/SaveItem",
data: {sendData: "string to send" }
dataType: "json",
success: function (result) {
de("server result:" +result);
}
});
Below is my jquery ajax call. I see from fire bug that I am getting the json response.
Content-Type application/json
{x:1363590711.97,y:0.277528026651}
However...I cant event pop up and alert of the data? How do I get the parsed json object so i cna start working iwth it?
$.ajax({
type: 'GET',
url: 'ajax_test',
crossDomain: false,
dataType: 'json',
success: function(responseData) {
alert(responseData);
//seriesJsonData[0]['data'].push({y: responseData.y, x: responseData.x});
}
});
Your return data is already parsed when you request dataType: 'json'
$.ajax({
type: 'GET',
url: 'ajax_test',
crossDomain: false,
dataType: 'json',
success: function(responseData) {
alert(responseData.x + " " + responseData.y);
seriesJsonData[0]['data'].push(responseData);
}
});