Why AJAX on retry sending different url request - javascript

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

Related

yii2 ajax request redirect not working

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

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"

I am passing an ajax to php with datatype as JSONP,but showing undefined index in php file

On submit button click,
I am passing a variable to sendmail.php.It's showing that contactname is undefined in php.
why is it happening ?
Here is my Code :
var name = document.getElementById('stream_cotactname').value;
alert(name);
$.ajax({
url: "sendmail.php",
async: false,
type:"POST",
data : "cotactname="+name+"file=" + formdata,
dataType: "jsonp",
contentType: false,
processData:false,
jsonp: "jsoncallback",
success: function(html){
alert("Thank you. We will be in touch with you");
},
error: function(){
alert("Thank you. We will be in touch with you");
}
});
My Php File:
<?php
$name =$_POST['cotactname'];die("A".$name);
?>
ALL gone well,Thanks.
Now let my introduce my exact code:
<script type="text/javascript">
var formdata = false;
(function () {
var input = document.getElementById("uploaded_file");
formdata = false;
formdata = new FormData();
input.addEventListener("change", function (evt) {
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (formdata) {
formdata.append("uploaded_file[]", file);
}
}
}, false);
}());
</script>
HOw can I get the form data information in php (like we do as $_FILES)
If you are not using cross domain call then you can call ajax like this:
$.ajax({
url: "sendmail.php",
async: false,
type:"POST",
data : {cotactname:name},
dataType: "json",
contentType: 'application/x-www-form-urlencoded',
success: function(html){
alert("Thank you. We will be in touch with you");
},
error: function(){
alert("Thank you. We will be in touch with you");
}
});
try to change your data sending for more https://api.jquery.com/jQuery.ajax/
data : {cotactname:name},
also try to check console for any error is post ok on that file or try with correct path of file
You are sending a string from ajax and getting value of variable.
Try this:
CHANGE
data : "cotactname="+name,
TO
data: {"cotactname" : name},

Send data to remote server using jsonp

Here is My code:
server A
$(function() {
var diffDomainUrl = 'http://domain_B.com/analtyics/cookie.php?jsoncallback=mycallback';
$('.idlink').on('click', function() {
$.ajax({
url: diffDomainUrl,
dataType: 'jsonp',
data: {},
success: function (data, textStatus) {
console.log(textStatus);
console.log(data);
},
jsonpCallback: 'mycallback'
});
});
});
and server B
<?php
$_GET['jsoncallback'];
if(isset($_GET['jsoncallback']))
{
setcookie("T_LNG",$_GET['jsoncallback'],strtotime('+30 days'));
echo $_COOKIE['T_LNG']."Welcome";
} ?>
in this code i m not getting anything. i don't know whthere its working or not or my method is wrong.
Your url contain call back already so dont set that in ajax remove and try remove this jsonpCallback: 'mycallback'
Try this
$(function() {
var diffDomainUrl = 'http://domain_B.com/analtyics/cookie.php?jsoncallback=mycallback';
$('.idlink').on('click', function() {
$.ajax({
url: diffDomainUrl,
dataType: 'jsonp',
data: {},
success: function (data, textStatus) {
console.log(textStatus);
console.log(data);
}
});
});
});
change
$_GET['jsoncallback'];
to
$_GET['callback'];
As per jQuery Docs
"jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of
your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.
Try
$(function() {
var diffDomainUrl = 'http://domain_B.com/analtyics/cookie.php?callback=?';
$('.idlink').on('click', function() {
$.ajax({
url: diffDomainUrl,
type: "POST",//if not specified get is the default
dataType: 'jsonp',
data: {}, //send data to server as key value pair if any eg {id:20}
jsonpCallback: 'mycallback'
});
});
});
And your callback function
function mycallback(responseJSON){
........
}

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