Following is my code :
function jsonpCallback(response){
//JSON.stringify(response)
alert(response);
}
$.ajax({
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert(error);
},
success: function(data) {
alert(data);
jsonpCallback(data);
}
});
Here my url variable is the link which contain the following data and as per I know it is in the JSON format:
[{"destination":"United States","destinationId":"46EA10FA8E00","city":"LosAngeles","state":"California","country":"United States"}] etc..
I want to call jsonpCallback function after passing successive data to it. But success argument of $.ajax is not calling the function thats why I am not getting any data into it. But my debugger window showing response there, so why its not coming $.ajax function?
Any help...thanks in advance.
Try to pass type of ajax call GET/POST.
$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) { alert(error); },
success: function(data) {
alert(data);
jsonpCallback(data);
}
});
function jsonpCallback(response){
//JSON.stringify(response)
alert(response);
}
The URL you are trying to load data from doesn't support JSONP, which is why the callback isn't being called.
If you own the endpoint, make sure you handle the callback GET parameter. In PHP, your output would look like this:
<?php
echo $_GET['callback'].'('.json_encode($x).')';
This will transform the result to look like this:
jsonp2891037589102([{"destination":"United States","destinationId":"46EA10FA8E00","city":"LosAngeles","state":"California","country":"United States"}])
Of course the callback name will change depending on what jQuery generates automatically.
This is required as JSONP works by creating a new <script> tag in the <head> to force the browser to load the data. If the callback GET parameter isn't handled (and the URL returns a JSON response instead of a JSONP response), the data gets loaded yes, but isn't assigned to anything nor transferred (via a callback) to anything. Essentially, the data gets lost.
Without modifying the endpoint, you will not be able to load the data from that URL.
One weird thing I've noticed about $.ajax is that if the content-type doesn't match exactly it's not considered a success. Try playing around with that. If you change success to complete (and fix the arguments) does it alert?
It's not working because your server does not render a JSONP response. It renders a JSON response.
For JSONP to work, the server must call a javascript function sent by the ajax request. The function is generated by jQuery so you don't have to worry about it.
The server has to worry about it, though. By default, this function's name is passed in the callback argument. For example, the URL to the server will be http://some.domain/ajax.php?callback=functionName (notice callback=functionName).
So you need to implement something like the following on the server side (here in PHP):
$callback = $_GET['callback'];
// Process the datas, bla bla bla
// And display the function that will be called
echo $callback, '(', $datas, ');';
The page returned will be executed in javascript, so the function will be called, so jQuery will call the success function.
First check in which event you are calling $.ajax function...
<script type='text/javascript'>
jQuery('#EnrollmentRoleId').change(function(){
alert("ajax is fired");
$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) { alert(error); },
success: function(data) {
alert(data);
jsonpCallback(data);
}
});
});
function jsonpCallback(response){
//JSON.stringify(response)
alert(response);
}
</script>
second try to replace $ with jQuery.
Try to give no conflict if you thinking any conflict error..
jQuery ajax error callback not firing
function doJsonp()
{
alert("come to ajax");
$.ajax({
url: url,
dataType: "jsonp",
crossDomain: true,
jsonpCallback:'blah',
success: function() { console.log("success"); },
error: function() { console.log("error"); }
});
}
Then check your json data if it is coming it is valid or not..
Thanks
Related
I am building a web app that displays data about flowers that is stored in my local server running bottle.
My front end is html, js with ajax;
My back end is python with bottle
In the browser there is an empty div in which the data is to be displayed.
Below it there is a row of images. When the user clicks on an image the data should display in the div above.
I tried using $.ajax instead of $.get, and I'm getting the same result.
This is my event listener in js:
$('.image').click((e)=>{
$('.selected').removeClass('selected');
$(e.target).addClass('selected'); // just a visual indication
$.get('/flowerdesc/'+$(e.target).attr('id')).done((data)=>{
flowerInfo = JSON.parse(data);
$('#flower-title').empty();
$('#flower-title').html(flowerInfo.name);
$('.desc-text').empty();
$('.desc-text').html(flowerInfo.description);
})
})
This is my handler for this request:
#get('/flowerdesc/<flower>')
def get_flower_desc(flower):
return json.dumps(data[data.index(filter(lambda f: f.name == flower, data)[0])])
(data is an array of dictionaries, each containing data of a single flower)
I am getting a 404 error (the function get_flower_desc is not executed at all) that possibly is happening because of the argument, because whenever I use a a function with no parameters and pass in no arguments I am getting the result that I'm expecting.
I found that I had to formulate an AJAX request quite precisely to get it to work well with Bottle in a similar scenario.
Here is an example with a GET request. You could attach this function to the event handler or move it directly to the event handler.
function getFlowerData(id) {
$.ajax({
type: "GET",
cache: false,
url: "/flowerdesc/" + id,
dataType: "json", // This is the expected return type of the data from Bottle
success: function(data, status, xhr) {
$('#flower-title').html(data['name']);
$('.desc-text').html(data['description']);
},
error: function(xhr, status, error) {
alert(error);
}
});
};
However, I found better results using a POST request from AJAX instead.
function getFlowerData(id) {
$.ajax({
type: "POST",
cache: false,
url: "/flowerdesc",
data: JSON.stringify({
"id": id,
}),
contentType: "application/json",
dataType: "json",
success: function(data, status, xhr){
$('#flower-title').html(data['name']);
$('.desc-text').html(data['description']);
},
error: function(xhr, status, error) {
alert(error);
}
});
};
For the POST request, the backend in Bottle should look like this.
#post("/flowerdesc") # Note URL component not needed as it is a POST request
def getFlowerData():
id = request.json["id"]
# You database code using id variable
return your_data # JSON
Make sure your data is valid JSON and that the database code you have is working correctly.
These solutions using AJAX with Bottle worked well for me.
I have a super simple JQuery ajax request below:
$.ajax("../ajax/data/items.json",
{ success: setContent, type: "GET", dataType: "json" });
function setContent(data, status, jqxhr) {
alert("Hello!");
}
The json loads on the page with a 200 response. The success function is set to setContent(). But the success function never runs and I cannot figure out why.
Questions:
Is my understanding of how the success function works incorrect? Why doesn't the function setContent() run for a 200 response on the Json?
Are the arguments for setContent() filled out behind the scenes by JQuery? Obviously I am not setting it anywhere in the code, but the video does not show adding arguments any place.
I am following Lynda.com's tutorial:
http://www.lynda.com/jQuery-tutorials/AJAX-made-simple/183382/368483-4.html
specifically the video AJAX made Simple.
The issue is most likely that you aren't getting back valid JSON. If you specify the data type as JSON and it returns something else, the success handler will not get called.
There is nothing wrong with the syntax:
As you can see, the console.log fires if you don't specify the dataType, as it doesn't care if it is JSON or not. If you do specify, nothing gets logged.
$.ajax(window.location.href,
{ success: setContent, type: "GET", dataType: "json" });
function setContent(data, status, jqxhr) {
console.log("It worked!");
}
You can copy that into dev tools on this site and see what happens when you remove the dataType parameter.
I'm new to ajax/jquery/javascript. So my iserver side uses oAuth. I need to obtain access code. So I'm sending request something like that :https:XXXX/OAuth.aspx?client_id=XXXXX&scope=full&response_type=code&redirect_uri=https%3A%2F%2Flocalhost%2F
If I'm logged I retrieve access code. So the issue is how to get this code with ajax, and how can I listen every time when it are changed. I wrote something like this, but it didn't work:
$.ajax({
url: "my-link",
data: {},
complete: function(xhr, statusText){
alert(xhr.status);
}
});
You can use the success parameter to grab your resulting response and do with it what you wish:
$.ajax({
url: "my-link",
data: {},
success: function (response){
alert(response);
}
complete: function(xhr, statusText){
alert(xhr.status);
}
};
You do have to fill in data properly and maybe you need other stuffs like processData and ContentType.
I rarely ever use “complete:”, mostly it’s “success:” and “error:” that handle everything I would need.
Been doing some playing call my service which is on a different domain using jQuery. The call to the service is successfully made (my debug point gets tripped), and the correct response is returned (I sniff the traffic).
My problem is mainly that the success and failure callbacks don't get fired. I have read some other posts on SO that indicate the error event is not fired when using JSONP. Is that the case with the success event (perhaps because it is assumed that I am providing my own callback function), as well, or is there a way to fire my success callback. Thanks in advance.
$.ajax({
type: "GET",
url: urlOnDiffDomain,
async: false,
cache: false,
dataType: 'jsonp',
data: {},
success: function(data, textStatus) {
alert('success...');
},
error: function(xhr, ajaxOptions, thrownError) {
alert('failed....');
}
});
Alright. In case anyone needs to know in the future...In hindsight, the solution probably should have been more obvious than it was, but you need to have the web-response write directly to the response stream. Simply returning a string of JSON doesn't do it, you need to someone construct it and stream it back. The code in my original post will work fine if you do indeed do that.
Example of service code:
public void DoWork()
{
//it will work without this, but just to be safe
HttpContext.Current.Response.ContentType = "application/json";
string qs = HttpContext.Current.Request.QueryString["callback"];
HttpContext.Current.Response.Write(qs + "( [{ \"x\": 10, \"y\": 15}] )");
}
Just for the sake of being explicit, this is the client-side code.
function localDemo(){
$.getJSON("http://someOtherDomain.com/Service1.svc/DoWork?callback=?",
function(data){
$.each(data, function(i,item){
alert(item.x);
});
});
}
If there is a better way to do this, I am all ears. For everyone else, I know there is some concept of native support in WCF 4.0 for JSONP. Also, you may want to do a little checking for security purposes - though I have not investigated much.
The success callback method is called when the server responds. The $.ajax method sets up a function that handles the response by calling the success callback method.
The most likely reason that the success method is not called, is that the response from the server is not correct. The $.ajax method sends a value in the callback query string that the server should use as function name in the JSONP response. If the server is using a different name, the function that the $.ajax method has set up is never called.
If the server can not use the value in the callback query string to set the function name in the response, you can specify what function name the $.ajax method should expect from the server. Add the property jsonpCallback to the option object, and set the value to the name of the function that the server uses in the response.
If for example the $.ajax method is sending a request to the server using the URL http://service.mydomain.com/getdata?callback=jsonp12345, the server should respond with something looking like:
jsonp12345({...});
If the server ignores the callback query string, and instead responds with something like:
mycallback({...});
Then you will have to override the function name by adding a property to the options object:
$.ajax({
url: urlOnDiffDomain,
dataType: 'jsonp',
data: {},
success: function(data, textStatus) {
alert('success...');
},
jsonpCallback: 'mycallback'
});
Try
$.getJSON(urlOnDiffDomain, function(data, textStatus){
alert('success...');
});
Works for me, usally. You need to add &callback=? to urlOnDiffDomain, where jQuery automatically replaces the callback used in JSONP.
The error callback is not triggered, but you can use the global $.ajaxError, like this
$('.somenode').ajaxError(function(e, xhr, settings, exception) {
alert('failed');
});
This is not a complete answer to your question, but I think someone who passes by would like to know this:
When you deal with JSONP from WCF REST try to use:
[JavascriptCallbackBehavior(UrlParameterName = "$callback")]
for your service implementation; this should give you JSONP out-of-the-box.
$.ajax({
url:' <?php echo URL::site('ajax/editing?action=artistSeracher') ?>',
dataType: "json",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
artist: request.term
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.artist,
value: item.artist,
id: item.id
}
}));
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
I have a registration form and am using $.ajax to submit it.
This is my AJAX request:
$(document).ready(function() {
$("form#regist").submit(function() {
var str = $("#regist").serialize();
$.ajax({
type: 'POST',
url: 'submit1.php',
data: $("#regist").serialize(),
dataType: 'json',
success: function() {
$("#loading").append("<h2>you are here</h2>");
}
});
return false;
});
});
In my submit1.php file I check for the existence of fields email address and username in the database.
I wish to display an error message if those value exist without a page refresh.
How can I add this to the success callback of my AJAX request?
The result is probably not in JSON format, so when jQuery tries to parse it as such, it fails. You can catch the error with error: callback function.
You don't seem to need JSON in that function anyways, so you can also take out the dataType: 'json' row.
Although the problem is already solved i add this in the hope it will help others.
I made the mistake an tried to use a function directly like this (success: OnSuccess(productID)). But you have to pass an anonymous function first:
function callWebService(cartObject) {
$.ajax({
type: "POST",
url: "http://localhost/AspNetWebService.asmx/YourMethodName",
data: cartObject,
contentType: "application/x-www-form-urlencoded",
dataType: "html",
success: function () {
OnSuccess(cartObject.productID)
},
error: function () {
OnError(cartObject.productID)
},
complete: function () {
// Handle the complete event
alert("ajax completed " + cartObject.productID);
}
}); // end Ajax
return false;
}
If you do not use an anonymous function as a wrapper OnSuccess is called even if the webservice returns an exception.
I tried removing the dataType row and it didn't work for me. I got around the issue by using "complete" instead of "success" as the callback. The success callback still fails in IE, but since my script runs and completes anyway that's all I care about.
$.ajax({
type: 'POST',
url: 'somescript.php',
data: someData,
complete: function(jqXHR) {
if(jqXHR.readyState === 4) {
... run some code ...
}
}
});
in jQuery 1.5 you can also do it like this.
var ajax = $.ajax({
type: 'POST',
url: 'somescript.php',
data: 'someData'
});
ajax.complete(function(jqXHR){
if(jqXHR.readyState === 4) {
... run some code ...
}
});
Make sure you're not printing (echo or print) any text/data prior to generate your JSON formated data in your PHP file. That could explain that you get a -sucessfull 200 OK- but your sucess event still fails in your javascript. You can verify what your script is receiving by checking the section "Network - Answer" in firebug for the POST submit1.php.
Put an alert() in your success callback to make sure it's being called at all.
If it's not, that's simply because the request wasn't successful at all, even though you manage to hit the server. Reasonable causes could be that a timeout expires, or something in your php code throws an exception.
Install the firebug addon for firefox, if you haven't already, and inspect the AJAX callback. You'll be able to see the response, and whether or not it receives a successful (200 OK) response. You can also put another alert() in the complete callback, which should definitely be invoked.
I was returning valid JSON, getting a response of 200 in my "complete" callback, and could see it in the chrome network console... BUT I hadn't specified
dataType: "json"
once I did, unlike the "accepted answer", that actually fixed the problem.
I had same problem. it happen because javascript expect json data type in returning data. but if you use echo or print in your php this situation occur. if you use echo function in php to return data, Simply remove dataType : "json" working pretty well.
You must declare both Success AND Error callback. Adding
error: function(err) {...}
should fix the problem
I'm using XML to carry the result back from the php on the server to the webpage and I have had the same behaviour.
In my case the reason was , that the closing tag did not match the opening tag.
<?php
....
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>
<result>
<status>$status</status>
<OPENING_TAG>$message</CLOSING_TAG>
</result>";
?>
I had this problem using an ajax function to recover the user password from Magento. The success event was not being fired, then I realized there were two errors:
The result was not being returned in JSON format
I was trying to convert an array to JSON format, but this array had non-utf characters
So every time I tried to use json_eoncde() to encode the returning array, the function was not working because one of its indexes had non-utf characters, most of them accentuation in brazilian portuguese words.
I tried to return string from controller but why control returning to error block not in success of ajax
var sownum="aa";
$.ajax({
type : "POST",
contentType : 'application/json; charset=utf-8',
dataType : "JSON",
url : 'updateSowDetails.html?sownum=' + sownum,
success : function() {
alert("Wrong username");
},
error : function(request, status, error) {
var val = request.responseText;
alert("error"+val);
}
});
I faced the same problem when querying controller which does not return success response, when modified my controller to return success message problem was solved.
note using Lavalite framework.
before:
public function Activity($id)
{
$data=getData();
return
$this->response->title('title')
->layout('layout')
->data(compact('data'))
->view('view')
->output();
}
after code looks like:
try {
$attributes = $request->all();
//do something
return $this->response->message('')
->code(204)
->status('success')
->url('url'. $data->id)
->redirect();
} catch (Exception $e) {
return $this->response->message($e->getMessage())
->code(400)
->status('error')
->url('nothing Wrong')
->redirect()
}
this worked for me
I had the same problem i solved it in that way:
My ajax:
event.preventDefault();
$.ajax('file.php', {
method: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({tab}),
success: function(php_response){
if (php_response == 'item')
{
console.log('it works');
}
}
})
Ok. The problem is not with json but only php response.
Before: my php response was:
echo 'item';
Now:
$variable = 'item';
echo json.encode($variable);
Now my success working.
PS. Sorry if something is wrong but it is my first comment on this forum :)
in my case the error was this was in the server side and for that reason it was returning a html
wp_nonce_field(basename(__FILE__), "mu-meta-box-nonce");
Add 'error' callback (just like 'success') this way:
$.ajax({
type: 'POST',
url: 'submit1.php',
data: $("#regist").serialize(),
dataType: 'json',
success: function() {
$("#loading").append("<h2>you are here</h2>");
},
error: function(jqXhr, textStatus, errorMessage){
console.log("Error: ", errorMessage);
}
});
So, in my case I saw in console:
Error: SyntaxError: Unexpected end of JSON input
at parse (<anonymous>), ..., etc.
The success callback takes two arguments:
success: function (data, textStatus) { }
Also make sure that the submit1.php sets the proper content-type header: application/json