Reputation: 89
I have the following ajax and php. I want to redirect the user to a another page depending on the result i output with a php script. Php successfully returns the json to browser, but i am somehow not able to get the response url back into the js ajax to make the redirection. It always redirects me to /undefined. What is wrong with my code?
jQuery.ajax({
type: "POST",
url: "../custom_scripts/anmeldung_zurueckziehen.php",
data: { anmeldung_id: anmeldung_id },
success: function(response){
//alert (response.redirect);
if (response.redirect) {
window.location.href = response.redirect;
}else {
// Process the expected results...
}
}
})
This is the php.
$arr = array ('redirect'=>true,'redirect_url'=>'https://mypage.de/no-
access/');
echo json_encode($arr);
Upvotes: 1
Views: 1708
Reputation: 1850
Two ways to do this
First way is - Either use JSON headers in Php like below
header('Content-Type: application/json');
Above will return JSON string with json headers and jquery will automatically parse it for you and your callback function will have proper object.
Second Way is - in javascript use JSON.parse like below
JSON.parse(response);
Above will basically parse your json string into Javascript object
Make sure you don't parse when you have set JSON headers from backend.
Upvotes: 0
Reputation: 978
You are missing dataType
property for ajax
to decode the response:
jQuery.ajax({
type: "POST",
dataType: "json",
url: "../custom_scripts/anmeldung_zurueckziehen.php",
data: { anmeldung_id: anmeldung_id },
success: function(response) {
//console.log(response.redirect);
if (response.redirect) {
window.location.href = response.redirect_url;
} else {
// Process the expected results...
}
}
})
Upvotes: 0
Reputation: 545
Wish this helps:
jQuery.ajax({
type: "POST",
url: "../custom_scripts/anmeldung_zurueckziehen.php",
data: { anmeldung_id: anmeldung_id },
success: function(response){
response = JSON.parse(response);
if (response.redirect) {
window.location.href = response.redirect_url;
}else {
// Process the expected results...
}
}
})
Upvotes: 1