How to use variable for url parameter in jquery ajax call? - javascript

$.ajax({
type:"POST",
url:"hostname/projfolder/webservice.php?callback=statusReturn&content="+str_table,
contentType: "application/json; charset=utf-8",
crossDomain:true,
dataType:'jsonp',
success:function statusReturn(data)
{
alert("in success");
var parsedata=JSON.parse(JSON.stringify(data));
var stats=parsedata["Status"];
if("1"==stats)
{
alert("success");
}
else
{
alert("failed");
}
}
});
How can I display the contents of the "url" parameter in an alertbox to check what the parameter is containing?
It does not even enter in the "success" parameter. Please suggest me how can I do that.

You can put you url parameter in a variable like so:
var targetUrl = "hostname/projfolder/webservice.php?callback=statusReturn&content="+str_table";
//log your output
console.log(targetUrl, str_table);
Then use it in your ajax call:
$.ajax({
type:"POST",
url: targetUrl,
...
See this fiddle for full example

Try this.url if need to access within event of ajax call. All parameters of ajax call can be accessed via this object. So final statement will be
alter(this.url);

You can see your request parameter in firbug plugin of chrom or firefox

Related

Using JSON data retrieved with AJAX outside success function

I have a problem with storing JSON that I get with AJAX, to an outside variable for further usage. Ive checked this answer (load json into variable) which is really basic, but I'm doing wrong something else. My code is below.
function showZone() {
var data=null;
$.ajax({
url: 'http://localhost/gui/templates/tracking/show_zones.php',
//data: 'userid='+ uid ,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "json",
type: "POST",
success: function(json) {
data=json;
$( '#res1' ).html( data[0].swlat );
}
});
return data;
}
function showZones() {
var data=showZone();
$( '#res2' ).html( data[0].swlat );
}
For clearer picture of my problem I have two divs (#res1 & #res2), where I print the data. In #res1 I get the result as wanted, but #res2 doesnt print anything and I get an error 'Uncaught TypeError: Cannot read property '0' of null'. So the data is returned before ajax stores it in a variable. Is this the problem, or should I be storing json to a variable differently?
Any help appreciated :)
You can use callback(). Consider following snippet:
function showZone() {
var data = null;
$.ajax({
url: 'http://localhost/gui/templates/tracking/show_zones.php',
//data: 'userid='+ uid ,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
dataType: "json",
type: "POST",
success: function(json) {
data = json;
showZones(data);//callback
}
});
//return data; No need to return data when we have async ajax
}
showZone(); // call when you want to make ajax call
function showZones(data) { // This function will call after ajax response
$('#res2').html(data[0].swlat);
}
$.ajax returns immediately return data which is executed before the function you passed as success callback was even called.So its return as undefined .Its means you can't return ajax data .
For more example How do I return the response from an asynchronous call?
But why can't you use simply like
success: function(json) {
data=json;
$( '#res1' ).html( data[0].swlat );
$( '#res2' ).html( data[0].swlat );
}

Design to block asynchronous javascript

var flow;
$.ajax({
url: "qa/version.json",
dataType: "json",
success: function( response ){
flow = response.Version;
}
});
$(".flow").append(flow);
Due to the nature of JS asynchronous design, the append would will be execute before it is being assigned a value in ajax call. What is the best way to tell the script to wait until flow gets assigned in ajax call, then do the append? I do not want to put append right below the success, I would like to keep them separate.
The "best way" is to perform the action in response to the asynchronous action:
$.ajax({
url: "qa/version.json",
dataType: "json",
success: function(response){
$(".flow").append(response.Version);
}
});
If you want to "keep them separate" then you can define a function to call in the response:
var appendFlow = function (flow) {
$(".flow").append(flow);
};
$.ajax({
url: "qa/version.json",
dataType: "json",
success: function(response){
appendFlow(response.Version);
}
});
Separating the code into its own function is simply a matter of organizing your code into re-usable components. Either way, by design the response can't be processed until it's received, so you'd perform your actions in response to the asynchronous call.
Anything wrong with:
$.ajax({
url: "qa/version.json",
dataType: "json",
success: function( response ){
flow = response.Version;
$(".flow").append(flow);
}
});
I have no idea why you don't want to put your success handler in the spot for a success handler, but here's an alternative that may help you.
jQuery returns a Deferred instance when you make AJAX requests. You can use its .done() method to set up a callback later.
var dfd = $.ajax( /* your code here, without the success handler */);
// later on...
dfd.done(function (response) {
$('.flow').append(response.Version);
});
See also:
https://api.jquery.com/deferred.done/
https://api.jquery.com/jquery.deferred/
Or:
var request = $.ajax({
url: "qa/version.json",
dataType: "json"
});
request.done(function(response){
$(".flow").append(response.Version);
});

unable to show record using webservice

this code is working fine but not showing records. in alert if i am getting record from file its working fine.
$j().ready(function(){
var result =$j.ajax({
type: "GET",
url: "webService address",
dataType :'json',
contentType:'application/json; charset =utf-8',
success:function(data)
{
$j.each(data, function(index,element){
alert("Successful here: "+element);
});
}
});
alert("result"+result);
});
Welcome to the wonderful world of asynchronous ...
First of all, jQuery get doesn't return the data, that needs to be handled by the callback (which is working as from your post)
var result = null;
$j(document).ready(function(){
$j.ajax({
type: "GET",
url: "webService address",
dataType :'json',
contentType:'application/json; charset =utf-8',
success:function(data)
{
result = data;
$j.each(data, function(index,element){
alert("Successful here: "+element);
});
}
});
alert("result"+result);
});
This might not work as well since jQuery ajax is asynchronous and the alert may pop up while the GET is still reading data and not yet ready !!!!
Check Jquery ajax doc:
$.ajax({
type: "GET",
url: "webService address",
dataType :'json',
contentType:'application/json; charset =utf-8'
}).done(function(data) {
console.log(data);
});
The javascript is not waiting AJAX to finish, it moves on. That is why its called asynchronous . If you need synchronous call, use async: false.

Jquery - parse XML received from URL

I have this URL, that I supposedly should receive an XML from. So far I have this:
function GetLocationList(searchString)
{
$.ajax({
url: "http://konkurrence.rejseplanen.dk/bin/rest.exe/location?input=" + searchString,
type: "GET",
dataType: "html",
success: function(data) {
//Use received data here.
alert("test");
}
});
Tried to debug with firebug, but it doesn't go into the success method.
Though, in DreamWeaver it is able to post a simple alert, which is inside the success method.
I tried writing xml as dataType, but it doesn't work (in DreamWeaver) when I write alert(data).
But it shows an alert with the entire XML, when I write html as dataType.
How do I get the XML correctly, and how do I parse and for example get the "StopLocation" element?
Try to add an Error function as well.
See enter link description here
This will give you all the informations you need to debug your code with Firefox.
$.ajax({
url: "http://konkurrence.rejseplanen.dk/bin/rest.exe/location?input=" + searchString,
type: "GET",
dataType: "html",
success: function(data) {
//Use received data here.
alert("test");
},
error: function(jqXHR, textStatus, errorThrown ){
// debug here
}
});
you need to parse it first, and then you can search for the attributes. like this.
success: function(data) {
var xml = $.parseXML(data)
$(xml).find('StopLocation').each(function()
{
var name = $(this).attr('name');
alert(name);
}
);
this will give you the name of each StopLocation.
hope this helps, you can use the same method for all other attributes in the document also.

load view using ajax symfony2

I'm very new to symfony2 and I'm getting some problems to load a view using ajax when the user clicks on a div. Using firebug I can see the data is returned but I can not append the result in the page.
My Code:
//Default Controller
public function indexAction($num, Request $request)
{
$request = $this->getRequest();
if($request->isXmlHttpRequest()){
$content = $this->forward('PaginationBundle:Default:ajax');
$res = new Response($content);
return $res;
}
return $this->render('PaginationBundle:Default:index.html.twig', array('num' => $num));
}
public function ajaxAction()
{
return $this->render('PaginationBundle:Default:page.html.twig');
}
}
My Js:
When clicking on #target, I'd like to load page.html.twig in my div
$("div#target").click(function(event){
t = t +1;
$.ajax({
type: "POST",
cache: "false",
dataType: "html",
success: function(){
$("div#box").append(data);
}
});
});
I'm using isXmlHttpRequest() in my controller to detect if it's an ajax request to load ajaxAction. I get that view on firebug but it's not appended in my div#box. div#box exists in index.html.twig
Thanks everybody in advance
In your
$("div#target").click(function(event) event you didn't specify the url parameter in ajax call, and another thing is you must specify an argument inside the 'success'
parameter of ajax call.
$("div#target").click(function(event){
t = t +1;
$.ajax({
type: "POST",
url: "{{path('yourpath-means header name in routing.yml')}}",
cache: "false",
dataType: "html",
success: function(result){
$("div#box").append(result);
}
});
});
Hope this helps...
Happy coding
This has nothing to do with symfony but with your ajax options. Pece is right though: You can use the return from §this->forward directly as it is a Response object.
The problem lies within your ajax options. You must pass the data object within your inner function or data is simply null. Try this:
success: function(data){
$("div#box").append(data);
}
I don't get your forward to treat AJAX call. Try this :
if($request->isXmlHttpRequest()){
return $this->forward('PaginationBundle:Default:ajax');
}
Controller::forward() already returns a Response object ;)

Categories

Resources