I made ajax call with jquery to get some information from database with php,but the problem is that when i am using $.ajax it is not working,it doesn't show any errors,it doesn't console.log('success') and i can't figure out why,while when i do the same thing with $.post it works.Any idea what is happening here?
function get_all_chats()
{
$.ajax({
url: "get_previous_chats.php",
type: "POST",
succes: function(data){
console.log(data);
console.log("succes");
},
error: function(xhr, status, error) {
console.log(error);
}
})
$.post("get_previous_chats.php", {}, function(data){
console.log(data);
})
}
You are using ajax properly but there are properties that needs to be checked and apply. First is your 'success' where yours is 'succes' with a single S in the end. Next is you must throw request using 'data' property. So this is how it looks.
function get_all_chats()
{
$.ajax({
url: "get_previous_chats.php",
type: "POST",
data: { data: YOUR_DATA },
success: function(data){
console.log(data);
console.log("succes");
},
error: function(xhr, status, error) {
console.log(error);
}
})
}
Related
I am pretty new to javascript where I am trying with ajax to make an get request. I am trying to get the password from the response.
Javascript code:
$(document).ready(function () {
$("#LoginUser").click(function () {
$.ajax({
url: 'http://website/api/user/Mikkel1337',
dataType: 'json',
type: 'GET',
contentType: 'application/json',
error: function () {
alert("An error had occurred");
},
success: function (data) {
var jsonStr = JSON.stringify(data);
alert(jsonStr['password']);
}
});
});
})
The response JSON code looks like this:
{"userId":16,"firstName":"mojn","lastName":"mojn","email":"mojn#mojn.dk","accountName":"Mikkel1337","password":"123","userRoleId":1,"active":false,"userRole":null,"competetion":[],"judge":[],"team":[]}
When im running this I only get the error function. Any suggestions or solution is appreciated :)
Basically you are converting the JSON to string and trying to access the string as object. Please don't stringify the data, and for JSON why using long code, your code should be:
$(document).ready(function () {
$("#LoginUser").click(function () {
$.getJSON( "http://website/api/user/Mikkel1337", function( data ) {
// do something on success
alert(data.password);
});
});
});
Cheers !!!
dont need to JSON.stringify of data simple use
$(document).ready(function () {
$("#LoginUser").click(function () {
$.ajax({
url: 'http://website/api/user/Mikkel1337',
dataType: 'json',
type: 'GET',
contentType: 'application/json',
error: function () {
alert("An error had occurred");
},
success: function (data) {
alert(data.password);
}
});
});
})
You should pass two argument for error:function(jqXHR, exception) as below.
And check once your API Url using proper way, may be your API is not show you proper result and you not get any of data from that API so that may be a reason you get error message.
$(document).ready(function () {
$("#LoginUser").click(function () {
$.ajax({
url: 'http://website/api/user/Mikkel1337',
dataType: 'json',
type: 'GET',
contentType: 'application/json',
success: function (data) {
var jsonStr = JSON.stringify(data);
//also try this way to get JSON data:
// var jsonStr =JSON.parse(data);
alert(jsonStr['password']);
},
error: function (jqXHR, exception) {
alert("An error had occurred");
},
});
});
});
I have the below ajax call and sometimes the request stops the page from loading as the data being passed is undefined.
I there a way to put a condition to handle the request if it has values that are undefined?
Can it be wrapped with a if condition?
newuser is not defined
$.ajax(
{
url: 'sample.aspx,
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data){
...
} ,
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
});
Simplest way would be to use a pipe:
$.ajax({url: 'sample.aspx',
data: newuser || {},//continue here...
If your variable was not initialized, empty object will be sent instead.
That's if and only if you can handle empty "newuser" for some reason.
I'm assuming that not closed URL is just a mistake in copy-paste, and not actually part of your code.
how about
if(newuser)
{
$.ajax(
{
url: 'sample.aspx,
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data){
...
} ,
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
});
}
If you are unable to handle an empty newuser you can try something like this:
if (newuser) {
$.ajax({
url: 'sample.aspx',
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data) {
...
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}
I am trying to get json via ajax and if my response variable is acceptable redirect using react router. How can I achieve that?
successRedirect(){
if (this.responseCode.equals("what I need")) {
router.transitionTo('/')
}
}
createCheckout() {
$.ajax({
url: "someurl",
dataType: 'json',
type: 'POST',
cache: false,
data: this.data,
success: function(response) {
this.setState({
response: response,
responseCode: response.result.code
});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
})
}
Function must be called after response is taken. For example I have this code and in render response is taken and shown after some time:
render(){
return (
<div>
<div>Response - {this.state.responseCode}</div>
</div>
);
}
It appears the issue was with this line:
if (this.responseCode.equals("what I need")) {
Items that get added via this.setState are available on the this.state object. Also JavaScript does not supply an equals function, but you can do comparisons with ===
if (this.state.responseCode === "what I need") {
I'm using ajax successives requests and I need do a callback when all the successives requests are done
function doAjaxRequest(data, id) {
// Get payment Token
return $.ajax({
type: "POST",
url: 'exemple1.php',
data: data
success: function(msg){
$.ajax({
type: "POST",
url: 'exemple2.php',
data: msg,
success: function(msgr) {
document.getElementById(id).value=msgr;
},
error:function (xhr, status, error) {
//Do something
}
});
},
error:function (xhr, status, error) {
//Do something
}
});
}
$.when(
doAjaxRequest(data, "input-1"),
doAjaxRequest(otherData, "input-2")
).done(function(a1, a2){
//Need do something when both second ajax requests (example2.php) are finished
}
With this code, the done function is call before my calls to "exemple2.php" are succeeded.
How can I wait for that?
Thanks for answering!
function doAjaxRequest(data, id) {
// Get payment Token
return new Promise(function(resolve,reject){
$.ajax({
type: "POST",
url: 'exemple1.php',
data: data
success: function(msg){
$.ajax({
type: "POST",
url: 'exemple2.php',
data: msg,
success: function(msgr) {
document.getElementById(id).value=msgr;
resolve();
},
error:function (xhr, status, error) {
//Do something
reject();
}
});
},
error:function (xhr, status, error) {
//Do something
reject();
}
});
});
}
Promise.all([
doAjaxRequest(data, "input-1"),
doAjaxRequest(otherData, "input-2")])
.then(function(values){
//Need do something when both second ajax requests (example2.php) are finished
}
Your sub ajax request is independant of the first ajax result, then the call to example2 is completely separated from the $.when() promise.abort
Just try to use the fact that jquery $.ajax return promise like object
Here my code from plnkr
// Code goes here
function doAjaxRequest(data, id) {
// Get payment Token
return $.ajax({
type: "GET",
url: 'example1.json',
data: data
}).then(function(msg, status, jqXhr) {
return $.ajax({
type: "GET",
url: 'example2.json',
data: msg
});
}).done(function(msgr) {
console.log(msgr);
return msgr;
});
}
var data = {foo:'bar'};
var otherData = {foo2:'bar2'};
$.when(
doAjaxRequest(data, "input-1"),
doAjaxRequest(otherData, "input-2")
).done(function(a1, a2) {
console.log(a1, a2);
//Need do something when both second ajax requests (example2.php) are finished
});
Attention, I replace POST by GET and use exampleX.json files for my tests on plnkr
You can test it here : https://plnkr.co/edit/5TcPMUhWJqFkxbZNCboz
Return a custom deferred object, e.g:
function doAjaxRequest(data, id) {
var d = new $.Deferred();
// Get payment Token
$.ajax({
type: "POST",
url: 'exemple1.php',
data: data
success: function(msg){
$.ajax({
type: "POST",
url: 'exemple2.php',
data: msg,
success: function(msgr) {
document.getElementById(id).value=msgr;
d.resolveWith(null, [msgr]); // or maybe d.resolveWith(null, [msg]);
},
error:function (xhr, status, error) {
//Do something
d.reject();
}
});
},
error:function (xhr, status, error) {
//Do something
d.reject();
}
});
return d;
}
Now, i'm not sure what is your expected datas passed to $.when().done() callback.
I have this $.post peace of code:
$.post("../admin-login",
{
dataName:JSON.stringify({
username:uname,
password:pass,
})
}, function(data,status){
console.log("Data:"+data);
answer = data;
}
);
and I wont to transform it to $.ajax. On the servlet side I am demanding request.getParamter("dataName") but I do not know how to write data: section in $.ajax so that I can get parameters like that(request.getParamter("dataName"))? Also, it seems to be problem with this type of code, I am asuming cause of async, that I cannot do this:
var answer="";
function(data,status){
console.log("Data:"+data);
answer = data;
}
And that answer is keeping empty(""), even though in console is written in deed "true" or "false" as my server answers. What is this about?
Thanks in advance.
I found out that problem is in the click() event. Ajax finishes when click() finishes, so I am not able to get data before event is done. What is bad in that is that I cannot fetch data because it is finished. Does anyone know how to solve this?
$.post("../admin-login",
{
dataName:JSON.stringify({
username:uname,
password:pass,
})
}, function(data,status){
console.log("Data:"+data);
answer = data;
}
);
becomes
function getResult(data) {
// do something with data
// you can result = data here
return data;
}
$.ajax({
url: "../admin-login",
type: 'post',
contentType: "application/x-www-form-urlencoded",
data: {
dataName:JSON.stringify({
username:uname,
password:pass,
})
},
success: function (data, status) {
getResult(data);
console.log(data);
console.log(status);
},
error: function (xhr, desc, err) {
console.log(xhr);
}
});
You need to see how the information os arriving to your servlet as query parameter or payload.
See this HttpServletRequest get JSON POST data
You could try structuring your AJAX request like the below:
var dataName = username:uname, password:pass;
$.ajax({
url: "../admin-login",
data: JSON.stringify(dataName),
type: "POST",
cache: false,
dataType: "json"
}).done(function(data, status) {
console.log("Data:"+data);
answer = data;
});