ReactJs Redirect on state variable change - javascript

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") {

Related

Problem jquery ajax call,success function is not behaving properly

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

JQuery Validation not posting data to backend

I have something weird going on that I am trying to work out. I have a simple submitHandle that passes one bit of data to my PHP file
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "form-process.php",
data: {
'customer': $("input[name='customer']:checked").val()
}
}).done(function (response) {
console.log(response)
}).fail(function (jqXHR, textStatus) {
console.log(textStatus)
});
return false;
}
If I output $("input[name='customer']:checked").val() I get the expected value of yes or no. Now in my PHP file, I am simply doing
echo json_encode($_POST["customer"]);
This seems to produce the error
Undefined index: customer
If I just check $_POST it returns an empty array.
Am I missing something here? Is there a reason this data isn't making it to the backend?
Try this method :
$.ajax({
method: "POST",
url: "form-process.php",
data: { customer: $("input[name='customer']:checked").val() }
}).done(function(response) {
console.log( "Data Saved: " + response);
}).error(function(error){
console.log(error)
});
You should use $("input[name='customer']:checked") ? true : false because if the input is not checked $("input[name='customer']:checked") will return null and then you will have null.val() which is not correct
data: {
customer: $("input[name='customer']:checked") ? true : false
}

setting state based on conditional in reactjs

I have a simple API call that sets the state of a list array with its response. I was wondering how I would go about implement a try/catch or error message if there is a bad search (i.e like a typo) or if the array is not set with the response. The code snippet is below:
componentDidMount() {
this.search('https://itunes.apple.com/search?term=modern_baseball');
}
search(URL) {
return $.ajax({
type: 'GET',
dataType: 'json',
url: URL,
success: function (response) {
this.showResults(response);
}.bind(this),
error: function() {
alert("Error handling request");
}
});
}
showResults(response) {
console.log(response);
this.setState({
searchResults: response.results,
moveResults: []
});
}
Try something like this:
componentDidMount() {
this.search('https://itunes.apple.com/search?term=modern_baseball');
}
search(URL) {
let self = this; //avoid the .bind call and store a ref to the current context for use inside the ajax handlers.
return $.ajax({
type: 'GET',
dataType: 'json',
url: URL,
success: function (response) {
self.showResults(response);
},
error: function() {
alert("Error handling request");
self.setState({error: "Error handling request", moveResults:[], searchResults:[]}); //set the state directly if there is an error
}
});
}
showResults(response) {
console.log(response);
this.setState({
searchResults: response.results,
moveResults: []
});
}
It sets a variable (self) to the current context (this) and then calls the setState directly in the error handler for the ajax call. Alternatively you could define a callback function just like you do for the success handler.

How to transform $.post to $.ajax?

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

How retrieve responseJSON property of a jquery $.ajax object [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have this javascript:
$ajax = $.ajax({
type: 'GET',
url: 'DBConnect.php',
data: '',
dataType: 'json',
success: function(data) {},
error:function (xhr, ajaxOptions, thrownError) {
dir(thrownError);
dir(xhr);
dir(ajaxOptions);
}
});
console.dir($ajax);
console.dir($ajax.responseJSON);
console.dir($ajax) shows it has a property named responseJSON, but when I try to access it with $ajax.responseJSON it returns undefined:
Well, of course it's undefined, because at the moment when you run console at last lines of your code, response hasn't yet came from the server.
$.ajax returns promise, which you can use to attach done() and fail() callbacks, where you can use all the properties that you see. And you have actually used callback error and success, and that's where you can run code and other functions that rely on data in the response.
You can use this trick to get the response out:
jQuery.when(
jQuery.getJSON('DBConnect.php')
).done( function(json) {
console.log(json);
});
It's late but hopefully will help others.
The response, is the "data", in success... so you can access to that writing data[0], data[1], inside the success.
For example:
success: function(data) {
alert(data[0]);
},
If you want this response, out of the success, you can set a variable outside, and try this:
success: function(data) {
myVar = data;
},
Hope, this help.
For those who don't really mind if it's synchronous, like I was, you can do this:
$('#submit').click(function (event) {
event.preventDefault();
var data = $.ajax({
type: 'POST',
url: '/form',
async: false,
dataType: "json",
data: $(form).serialize(),
success: function (data) {
return data;
},
error: function (xhr, type, exception) {
// Do your thing
}
});
if(data.status === 200)
{
$('#container').html(data.responseJSON.the_key_you_want);
}
});
It runs through the motions, waits for a response from the Ajax call and then processes it afterwards if the status == 200, and inside the error function if something triggered an error.
Edit the options to match your situation. Happy coding :)

Categories