yii2 ajax request redirect not working - javascript

I tried to redirect the user after he click on a button.
But the redirection is not working.
This is my js code for handling the button click.
$('#MyButton').click(function() {
$.ajax({
url: '<?php echo Url::to(['configurator/compare']) ?>',
type: 'POST',
data: {
Ref : Ref,
searchname: $("#searchname").val() ,
searchby:$("#searchby").val() ,
_csrf : '<?=Yii::$app->request->getCsrfToken()?>'
},
success: function (data) {
}
});
The http request image
The request is executed but i'm not redirected to the url.
I stay on the same page when i click in the button.

The code you have posted does not perform a redirect.
All it does is make an ajax POST request to the url: ('configurator/compare') and passes the parameters in data:
To perform a redirect you could do it in the success: callback, e.g.
success: function (data) {
window.location.href = 'http://google.com';
}
You can either hardcode the URL in above, or base it on the output of the script you posted to, which is available by accessing data inside the success callback.

If you don't want return any data to you 'success' function, than in your controller 'configurator', in method 'compare', after handling your data you can make redirection to 'view' which you want:
$data = Yii::$app->request->post();
// do what you want with data
return $this->redirect(['controller/action']);

Try Below way.
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type:"POST",
data:{id:id},
url : '<?php echo Yii::$app->getUrlManager()->createUrl("/property/favourite"); ?>',
success: function(response){
window.location.href = '<?php echo Yii::$app->getUrlManager()->createUrl("/site/chat"); ?>';
}
});
});
</script>

You can set the path in the controller and send the url back to the page.
public function actionAjaxMethod() {
//my logic
//if everything is successfulget the url path you want to redirect to.
$url = Yii::$app->getUrlManager()->createUrl("/controllerName/methodName");
return \yii\helpers\Json::encode([
'status' => true,
'url' => $url,
]);
}
In your view page all you do is
success: function (data) {
if (data.status) {
//redirect the page to url.
window.location.href = data.url;
}
},

Related

Why AJAX on retry sending different url request

I have very stange problem: I have product list and when you click on product to edit the product you go to product form. On this product form I have AJAX that is sending request to getFiltersGroup. I want to resend this AJAX on error, but for some reason on error AJAX is start sending url request for product form not for getFiltersGroup.
Any ideas what is wrong, why is not sending request to getFiltersGroup?
This is what happen on retry:
This is the code:
var retry;
$('#filters-ajax').on('click', function(){
var product_id = "<?php echo isset($set_id) ? $set_id : NULL; ?>";
var ajaxConfig = $.ajax({
url: "index.php?route=catalog/product/getFiltersGroup&token=<?php echo $token ?>",
type: "POST",
data: '&product_id='+product_id,
dataType: 'json',
beforeSend: function(){
$('#btn-product-filter-groups').prop('disabled', true);
},
success: function(data){
clearInterval(retry);
$('#btn-product-filter-groups').prop('disabled', false);
},
error: function(xmlhttprequest, textstatus, message) {
retry = setInterval(function(){
$.ajax(ajaxConfig);
}, 6000)
}
});
})
UPDATE
I fix the url request but now I can't reset the setInverval(). Also I'm never getting alert message. Any ideas what wrong?
var retry;
$('#filters-ajax').on('click', function(){
var product_id = "<?php echo isset($set_id) ? $set_id : NULL; ?>";
$.ajaxSetup({
url: "index.php?route=catalog/product/getFiltersGroup&token=<?php echo $token ?>",
type: "POST",
data: '&product_id='+product_id,
dataType: 'json'
});
var ajaxConfig = $.ajax({
beforeSend: function(){
$('#btn-product-filter-groups').prop('disabled', true);
},
success: function(data){
alert('WTF')
clearInterval(retry);
$('#btn-product-filter-groups').prop('disabled', false);
},
error: function(xmlhttprequest, textstatus, message) {
retry = setInterval(function(){
$.ajax(ajaxConfig);
}, 6000)
}
});
})
$.ajax() returns a jqXHR object, which you are later passing to $.ajax() as a configuration object for a new call:
var ajaxConfig = $.ajax({ ... });
// ...
$.ajax(ajaxConfig);
But that jqXHR object is not an $.ajax() config object, and it will not have a url: ... key/value pair (nor any of your other settings). Checking the docs for the $.ajax() config object it says (emphasis mine):
jQuery.ajax( [settings ] )
settings
Type: PlainObject
A set of key/value pairs that configure the Ajax request. All settings are optional.
And regarding the url setting:
url (default: The current page)
So since there is no URL specified in the config object, it will default to the current page. Your new $.ajax() request will request the current page, your edit page.
If you want to make your AJAX call a callable function, just put it in a function and call it:
function ajaxCall() {
$.ajax({
url: "index.php?route=catalog/product/getFiltersGroup&token=<?php echo $token ?>",
type: "POST",
// ... your code
error: function(xmlhttprequest, textstatus, message) {
retry = setInterval(ajaxCall, 6000)
}
});
}
$('#filters-ajax').on('click', function(){
// ...
ajaxCall();
});
This approach sends off all kinds of recursive alarm bells for me though, I would consider trying another approach.
I dont know why but this one is working if anyone can explain why this code is working and previous code is not working i will accept his answer
$('#filters-ajax').on('click', function(){
var product_id = "<?php echo isset($set_id) ? $set_id : NULL; ?>";
$('#btn-product-filter-groups').prop('disabled', true);
$(function callAjax(){
$.ajax(`index.php?route=catalog/product/getFiltersGroup&token=<?php echo $token ?>&product_id=${product_id}`)
.success( function(data) {
$('#btn-product-filter-groups').prop('disabled', true);
})
.error(function() {
setTimeout ( function(){ callAjax() }, 6000);
});
})
}
})

Ajax: conflict in client between two functions

For a university homework, I have to create a little e-commerce website.
After the login, the user is redirected to the homepage. In this homepage, the client will recive a JSON object from the server (containing some product to be loaded) to generate the DOM of the homepage dynamically.
Note: I must use AJAX and JSON
I have this client.js file:
$(document).ready(function() {
// AJAX request on submit
$("#login_form").submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "submit.php",
data: {
Email: document.getElementById('login_email').value, // Email in the form
Password: document.getElementById('login_password').value // // Password in the form
},
cache: false,
success: function(){
window.location.href = "home.php"; // load the home.php page in the default folder
}
});
});
});
$(document).ready(function() {
// AJAX request to open a channel between php and client
function (e) {
e.preventDefault();
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
var data = JSON.parse(data);
alert(data); // debug
showProducts(data);
});
});
});
});
function showProducts(data){
alert(data);
// Insert object into the page DOM
}
I don't know why, but I can't access after the login if the second Ajax request (the AJAX request to open a channel between php and client) is not commented, and I don't know why, because the code seems right... Any suggestion?
after login action you need to set to cookie token in response
success: function(response){
console.log(response)
// then set to cookie response.token
window.location.href = "home.php";
}
after set token to cookie, you need to send this token to next ajax request url: "queries.php",
You need to wrap your anonymous function in parenthesis and add () at the end if you want to execute it:
(function (e) {
// I don't know why you need this:
e.preventDefault();
// etc.
})();
You should also check the contents of that function as you seem to have too many closing parentheses and you don't need to parse the returned value if you set the dataType to json.
In the end I think this is about all you need for that function:
(function () {
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
})();
or just:
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
To get it directly on page load.

AJAX error 303 handling

I'm using ajax to send values to another form. There, I insert in DB and return the table as html to update instantly. So far it's a simple ajax refresh the table.
The problem is, I check the session to be logged in and do that things. when i delete the cookie (the session timeout) the login page shows in the partial form that should shows the returned table.
I checked... it seems has the "303 see other!" error.
I need it to redirect to login page when the session is times out.
Here is my ajax code:
function save(){
var value = {
//values
};
$.ajax({
type: 'POST',
url: '<?php echo site_url('admin/test'); ?>',
data: value,
success: function(resp){
$('#sample_1').html(resp);
},
});
}
I check the session in the admin controller.
You can try to use jQuery ajax() statusCode handler like so:
$.ajax({
type: 'POST',
url: '<?php echo site_url('admin/test'); ?>',
data: value,
success: function(resp){
$('#sample_1').html(resp);
},
statusCode: {
303: function() {
...do stuff you want to do when 303 happens...
}
}
});

jQuery: Ajax get request does not work with PHP

I created a simple script in order to pass a value in a PHP file.
This is the .js script:
$("#test").click(function () {
var id = 34;
$.ajax({
method: "POST",
url: "ajax.php",
data: {
id: id
},
success: function (data) {
alert("data sent");
},
error: function (data) {
alert("Data sending failed");
}
});
});
And this is the code included in the PHP file:
if (isset($_POST['id'])) {
$id = $_POST['id'];
echo $id;
}
The Ajax request works, but in the PHP file I receive an empty variable.
Check your $_GET global, if it's set there, you'll need to change method: "POST" to type: "POST"

How do I send an ajax post request to a specific module in Drupal6?

I want to send an ajax post request to a module named sampleTest in Drupal6.
I have tried some bits of codes but I do not know how to put the module url in the jquery ajax function.
<script type="text/javascript">
$(function(){
$("#one").click(function(){
$.ajax({
type: 'POST',
url: 'http://localhost/drupal/www/admin/build/modules/module/get/contact',
dataType: 'json',
data: "test",
success:function(data) {
alert("123");
},
complete: function(data){
alert("complete");
}
});
});
});
</script>
You can't send an AJAX request to a module as such, rather you implement a path in your module (using hook_menu()), provide a page callback for that path that outputs the AJAX response, and then call that path in your AJAX call. This is a very basic example:
function mymodule_menu() {
$items['ajax-test'] = array(
'access callback' => TRUE,
'page callback' => 'mymodule_ajax_callback',
'type' => MENU_CALLBACK
);
}
function mymodule_ajax_callback() {
$post_data = $_POST;
// Do something with the post data
$output = array('status' => 'OK');
// For Drupal 6
drupal_json($output);
exit();
// Or for Drupal 7, just in case you want to know
drupal_json_output($output);
drupal_exit();
}
Then your JS would look like this:
$(function(){
$("#one").click(function(){
$.ajax({
type: 'POST',
url: '/drupal/ajax-test',
dataType: 'json',
data: "test",
success:function(data) {
alert(data.status);
},
complete: function(data){
alert("complete")
}
});
});
});

Categories