jQuery ajax, url property does't work correctly - javascript

I use this trivial code, but it doesn't work correctly (for my mind):
$(document).on("click", "#summary_and_tables #tables ul li a", function() {
var url = "index.php/table/show/"+this.hash;
console.log(url);
$.ajax({
type: "POST",
url: url,
dataType: 'json',
success: function(response) {
if(response.status == 'ok') {}
}
});
});
Output in console is:
index.php/table/show/#summary
But ajax request sent to:
http://test.loc/st_base/index.php/table/show/

Unfortunately/luckily, nothing is wrong. Things work as expected. Browsers just do not send hash to the server.
If you really need to pass it, put it into data:
var url = "index.php/table/show/";
var hashOnly = this.hash;
$.ajax({
type: "POST",
data: {myhash: hashOnly},
url: url,
dataType: 'json',
success: function(response)
{
if(response.status == 'ok')
{
}
}
});

You are using relative url, this will append index.php/table/show/"+this.hash to current location of your script.
It appears that your script is located at "http://test.loc/st_base/"
Try specifying full url, starting with "http://mycorrectsite.com/blah/index.php/table/show..."

Related

Display page only if ajax call succeeds?

I have a subdomain protected by a service similar to cloudflare. It checks if a visitor is human or not. To save bandwidth usage I want only one file to be loaded from this subdomain as indicator if the visitor is a bot or not. If it is not loaded, the service has blocked it as bot, and nothing should be shown.
I already thought of an ajax request before the page loads to check this.
var success = 0;
function myCall() {
var request = $.ajax({
url: "sub.example.com/hello.php",
type: "GET",
dataType: "html"
});
request.done(function() {
// Load page, because the request was successfull
$.ajax({
url: 'content.php', //This is the current file
type: "POST",
dataType:'json', // add json datatype to get json
data: ({load: true}),
success: function(data){
console.log(data);
}
})
});
Is there a better way to do this?
You may try this:
var success = 0;
function myCall() {
var request = $.ajax({
url: "sub.example.com/hello.php",
type: "GET",
dataType: "html",
success: function(){
$.ajax({
url: 'content.php', //This is the current file
type: "POST",
data: dat,
success: function(data){
console.log(data);
},
error: function(data){
console.log('Error!');
}
});
},
error: function(data){
console.log('Error!');
}
});
}

Calling controller function from JS file

Im using Yii framework, i want to call controller function from JS file,
My ajax code in JS file:
$.ajax({
type: "POST",
url: "operator/checkDisabledDates",
data: {
id: 1
},
success: function(data) {
alert('success');
},
error: function(data) {
alert("Fail");
}
});
where checkDisabledDates is my controller method name, and operator is my controller name.
i got wrong formation of url something like,
www.example.com/operator/agent/id/4/operator/checkDisabledDates
my ajax url just appends at last position of existing url,
i tried different combinations like,
url: "/operator/checkDisabledDates"
url: "../operator/checkDisabledDates"
url: "../checkDisabledDates"
nothing worked,
but when i use in below syntax it worked,
url: "../../checkDisabledDates"
Is there anyway to do this without hardcoding dots(.) like this???
I would suggest not using a relative path to call your controller.
Try using your domain as context
var domainName = 'yourSite.com'
url: domainName+"operator/checkDisabledDates"
I'm using in my project and it's working for me, please try this -
Define a Global Variable in JS file eg. -
var url_path = document.location.origin+document.location.pathname;
so now you can use like this
url: url_path+'?r=operator/checkDisabledDates'
or
url: url_path+'operator/checkDisabledDates'
Use this:
data = {};
data.r = 'operator/checkDisabledDates';
data.id = 1;
$.ajax({
type: "POST",
url: "index.php",
data: data,
success: function(data) {
alert('success');
},
error: function(data) {
alert("Fail");
}
});
Always works for me.

Jquery AJAX posting variable to server file

Using Jquery AJAX to read a number from a server file, increment the number, and write the number back to the server file.
I can read the file fine, I just can't post to the file.
<script>
var counter = -1;
$.ajax({
type: "GET",
url: "counter.txt",
success: function(text) {
counter = text;
counter++;
$("#count").html(counter);
},
error: function() {
$("#count").html("Error!");
}
});
$.ajax({
type: "POST",
url: "counter.txt",
data: counter,
success: function() {
},
});
</script>
Ajax being a client-side method can't write to a file on the server.
You would need some middleware in PHP, ASP, Python etc to take the amends as posted data and write to the file.
Since Ajax is asynchronous, this piece of code
$.ajax({
type: "POST",
url: "counter.txt",
data: counter,
success: function() {
},
});
will be executed before you will get first number from server. You need to put this code inside "success" function
$.ajax(
type: "GET",
url: "counter.txt",
success: function(text) {
counter = text;
counter++;
$("#count").html(counter);
$.ajax({
type: "POST",
url: "counter.txt",
data: counter,
success: function() {
},
});
},
error: function() {
$("#count").html("Error!");
}
});
Also, you should just call some server side php method through Ajax, since you can't set anything through JavaScript on server.
So "post" Ajax URL should looks like
url: 'http://www.server.ca/set_vars?var=var_title&value=' + encodeURIcomponent(counter)

Setting request header in ajax

I have trouble with a piece of ajax code. This is the error message I get from mod security:
/ajaxController.php?mod=catalog&op=ajaxSeenProducts HTTP/1.1
Access denied with code 400 (phase 2). Operator EQ matched 0 at
REQUEST_HEADERS. [file "/usr/local/apache/conf/modsec2.user.conf"]
[line "12"] [id "960012"] [msg "POST request must have a
Content-Length header"] [severity "WARNING"] [tag
"PROTOCOL_VIOLATION/EVASION"]
There is a module in the web shop I am working on, which shows the last viewed products, and the jquery code I have is this:
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});
While searching for the solution, I have found in various places that I need to set the
Content-length
parameter, but all I have found is in this format:
xmlHttp.setRequestHeader("Content-length", params.length);
Is there any way to set the request header in the code format I have provided above? I have already tried something like:
headers: {
"Content-Length": params.length
}
but with no result. Any help would be appreciated.
use code like:
var url = '{HOME}ajaxController.php?';
var data = "mod=catalog&op=ajaxSeenProducts";
$.ajax({
url: url,
data: data,
dataType: "html",
type:'post',
success:function(seenProducts){
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
},
error:function(response){
}
});
you can use the beforeSend function to set the headers
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
beforeSend: function (request)
{
request.setRequestHeader("Authority", authorizationToken);
},
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});
or other way you can do it like
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
headers: {"X-Test-Header": "test-value"},
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});

Jquery: how to send one ajax request and save the JSON string for another calls

in my code i have the following
var response = "";
function send_ajax(){
if(response == ""){
$.ajax({
url: url
type: 'POST',
dataType: "JSON",
success: function(data){
response = data;
}
});
}
}
my problem is that send_ajax function is called several times in my script, and sometimes alot of ajax calls is send together and no need for that. so i'm searching for a solution in which if one ajax request is send other calls should wait until that function saves the data in the response var and use it.
how can i do that ?
If you set the async flag to false, no other calls are made until the first call is done.
$.ajax({
url: url
type: 'POST',
dataType: "JSON",
async: false,
success: function(data){
response = data;
}
});
if(response == ""){
response = 'waiting';
will do the trick, no ?
Another solution if you want the $.ajax to be async, but only allow one ajax request at any time. You could take a look at $.ajaxStart and $.ajaxStop global event
var ajaxLock = false;
$.ajaxStart(function(){ajaxLock = true;});
$.ajaxStop(function(){ajaxLock = false;});
var ajaxRequest = function(url, data) {
if (!ajaxLock) {
$.ajax({
url: url
type: 'POST',
dataType: "JSON",
async: false,
success: function(data){
response = data;
}
});
}
}

Categories

Resources