I have made a simple code for ajax to call a page but it does not seem to be working. can anyone tell me the error?
function toggledisp(val)
{
$.ajax({
url: 'ads/xyz.php?a=' + val + '&b=2' ,
});
}
Also if we want to output the response text then how do we do so by using this method??
I would highly recommened and invite you to take a look at basic ajax tutorial using jQuery
jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery
Also if we want to output the response text then how do we do so by
using this method??
You would use success or complete handler:
$.ajax({
url:'url here',
data: {foo:'foo', bar:'bar'}, // example of data you want to send
success: function(response) {
alert(response);
}
});
For more info, see above tutorial first.
function toggledisp(val)
{
$.ajax({
url: '/ads/xyz.php' ,
data:{a:val,b:2},
success:function(output){ alert(output); }
});
}
Related
Ive been checking out how to add variables to a ajax request which I can use in my server side script. I checked this stackoverflow post here and checked the jquery api docs here for a ajax request. I am getting error variable in my code is not defined.
I have this line in my code
return $.ajax({
type: 'GET',
url: '/users/show',
data: {'currentusershow': variable},
});
I was wanting it to do something like this with the results so I can keep all my different script in the one file.
if ($.get("currentusershow")) {
// do something here
}
else if...
i am not sure how to add the value to my code?
Also my url does not work going to the show.js.erb where my code is kept.
You need to declare and assign some value to the variable before the request.
Also you need to change the method type from GET to POST.
var variable = 'some data';
/*$.ajax({
type: 'POST',
url: '/users/show',
data: {currentusershow: variable},
success: function (response) {
// Do something with respsone
},
error: function () {
alert("error");
}
});*/
$.get( "/users/show", {currentusershow: variable} )
.done(function( response ) {
//do something with the response here.
});
Mamun was kind of right here as I did not explain myself very well in my question but I thought I would post this and clarify my question with what I was trying to do. The ajax call should be
return $.ajax({
type: 'GET',
url: '/users/show',
data: { currentusershow: 'variable'},
});
where the key is currentusershow and the value variable is a string and leave out defining the variable else where in the code. That way the url comes through correctly to the server being /users/show?currentusershow=variable. And in my destination file add my ruby code there to use the variables. In my question that code was more a php type code as I did not know what I was doing at the time.
I have a javascript function.
I'm making a AJAX call, and in that recieved content there is a link that I want to call the javascript function with.
MyJavascriptFunction(bla){
alert (bla);
}
Result from ajax = "Click
Do I have to do anything special with the result from AJAX to get this to work or should it just work.
I have tried it like this but with no success with clicking the link.
The AJAX call:
function doSearch() {
var form = $('form');
$.ajax({
url: "doSearch.php",
type: "GET",
data: form.serialize(),
success: function(result){
document.getElementById("result").innerHTML=result;
}
});
}
In the php I'm printing out
Click
First of all, try it. But yes you have to do something with the AJAX result. It has to be put somewhere in the DOM or the user won't be able to click on it.
Plus, make sure that the javascript function is a top level. I would suggest you use event handlers instead though.
Change your <a> tag to:
Click
You are mixing jQuery and DOM. that is not pretty
try this - assuming you do not have more than one link in the html
success: function(result){
$("#result").html(result).find("a").on("click",function() {
MyJavascriptFunction(bla);
return false;
};
}
I have a jQuery ajax call that returns html of a table. Now I need to let user to do some javascript action on the table.
Can the return ajax response contain the javascript code or do I have to load the javascript code in the page on the first load of the page?
The user has the option of triggering the 'new' javascript. It doesn't have to triggered on ajax call.
To answer the actual question, the return response can contain the script. Simplest is to place it after the html, as the ready event has already fired in page it is being loaded into
You can use the success (or other event) callbacks provided with jQuery .ajax() to perform this JS action. Something like this:
$.ajax({
success: function(){
// Perform JS action
}
}
The jQuery API lists all such event callbacks available for AJAX calls. Check this for more info.
The returned ajax response can contain javascript code as a string. Then you can eval(response).
If you want to request a script with ajax that will be run when retrieved, then you can use jQuery's getScript() method to retrieve it and then execute it.
Per the jQuery doc, getScript() is a shorthand for:
$.ajax({
url: url,
dataType: "script",
success: success
});
Which shows that jQuery's ajax command will handle a returned script for you automatically if you set the data type appropriately.
You can make your request a variable and extend upon it after the set up.
// Make the request to the server
var dataID = $("#WhatINeedForAParameter").val();
var request = $.ajax({
url: "PageOrControllerOrWebApi/MethodName",
type: "POST",
data: { id : dataID },
dataType: "json"
});
// When the request is done process
// what you need done
request.done(function(msg) {
alert('You got this ' + msg);
});
// If the request failed you can
// see what the problem was and
// handle the situation accordingly
request.fail(function(jqXHR, textStatus) {
alert( "Your request failed: " + textStatus );
});
you can do it using success callback i think this can be a way please try
$.ajax({
.....,
.....,
success:
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = url;
$("#tableID").append( script );
});
i hope it should help.
I'm having an annoying issue, on complete i get undefined when trying to make simple url validation. success working fine.
i get a valid json response:
{"error":"some error"}
and this is my jQuery
$("#myform").submit(function(){
dataString = $("#myform").serialize();
$.ajax({
type: "GET",
url: "myform.php",
data: $.URLDecode(dataString), //fixing url problem
dataType: "json",
beforeSend: function(){
$('#search').append('<img src="images/ajax-loader.gif" />'); //loader
$('.error').remove(); //removes every submit
},
success: function(data){
$('<span class="error">' + data.error + '</span>').appendTo($('#search'));
},
complete: function(data){
$('#search img').fadeOut(); //removes loader
alert(data.error);
}
});
return false; //force ajax submit
});
Any hint please?
If you look at the docs:
complete(XMLHttpRequest, textStatus)
A function to be called when the
request finishes (after success and
error callbacks are executed). The
function gets passed two arguments:
The XMLHttpRequest object and a string
describing the status of the request.
This is an Ajax Event.
Data is not a return value from your method.
If you're using firebug, use console.log(XMLHttpRequest) and you'll see what it includes.
You can also do this (quick - using eval here - not recommended.)
var err = eval("(" + XMLHttpRequest.responseText + ")");
alert(err.Message);
As per the docs, the complete event doesn't hold your json response.
Why do you need to define the complete handler and the success handler? Just define success.
maybe $.URLDecode() returns not JSON key/value structure
I think you want URLEncode not URLDecode? Either way I'd recommend fiddler for debugging issues like this - it'll show you exactly what's being sent to/from the server.
My question is:
Is it possible to do an Ajax request WITHIN a click function, with jQuery? (see example below), If so, what am I doing wrong? Because I'm not being able to do any request (I'm alerting the data through my success function and nothing is being retrieved).
Thank you very much in advance for any help! :)
function tracker(){
this.saveEntry = function(elementTracked, elementTrackedType){
var mode = "save";
var dataPost = "mode="+mode+"&elementTracked="+elementTracked+"&elementTrackedType="+elementTrackedType;
$.ajax({
type: "POST",
url: 'myURL',
data:dataPost,
success:function(msg){
alert(msg);
},
beforeSend:function(msg){
$("#trackingStatistics").html("Loading...");
}
});
return;
},
this.stopLinksSaveAndContinue = function(){
var fileName;
$("a[rel^='presentation']").click(function(e){
fileName = $(this).attr("rel").substring(13);
this.saveEntry(fileName,"Presentation");
})
}
}
If your anchor is linked with the href attribute, then this may be interrupting your AJAX request. A similar problem was recently discussed in the following Stack Overflow post:
window.location change fails AJAX call
If you really want to stick to using AJAX for link tracking, you may want to do the following:
Link
With the following JavaScript logic:
function tracker(url) {
$.ajax({
type: 'POST',
url: 'tracker_service.php',
data: 'some_argument=value',
success: function(msg) {
window.location = url;
}
});
}
Have you considered the possiblity that the request might be failing. If so, you're never going to hit the alert.
Can you confirm that the beforeSend callback is being fired?
Also, I'm assuming 'myURL' isn't that in your real-world source code?
There may also be something awry in the }, that closes your function.
Im guessing some sort of error is being generated. Try adding
error:function(a,b){
alert(a);
},
After 'success'