I am stuck on this one. I think this should be simple but I am have no success. I am just trying to post a variable in a href tag over to a php function on a separate file. I am trying to test my JS with an alert box on success. I am getting no alert box, 'Success alert box test!'.
Any idea what I am doing wrong? I am guessing it is the problem is with my success function.
Thanks again! Much appreciated.
HTML:
Click here
JS:
$(document).ready(function() {
$( ".target" ).click(function(e) {
e.preventDefault();
var review_id = this.data('review');
$.ajax({
url : "vote_add.php",
type : "POST",
dataType: "json",
data : {
reviewId : review_id
},
success : function(data) {
if (data == 'success') {
alert('Success alert box test!');
} else {
alert(data);
}
}
});
});
});
Vote_add.php:
<?php
echo "success";
?>
$(document).ready(function() {
$( ".target" ).click(function(e) {
e.preventDefault();
var review_id = $(this).data('review');
$.ajax({
url : "/echo/json/",
type : "POST",
dataType: "json",
data : {
reviewId : review_id
},
success : function(data, status) {
if (status == 'success') {
alert('Success alert box test!');
} else {
alert(data);
}
}
});
});
});
You have error on line 5th this should be $(this) - the jQuery object and also you should use 2nd parameter for success which is status.
For easier debug just use FireBug or DevTools.
A couple things to improve your code and to my experience, what I believe you should change:
$(this).data('review') should work.
The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.
As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.
Your callback functions on the $.ajax() options you provide should be like .done(), .fail(), .always() and .then()
The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise.
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8.
Depending on the way your web service was setup, you should be able to set a breakpoint in your server code (I assume you have access to it or built it yourself?). If not possible, check the data object returned by .fail() with Firebug or any other developer toolbar and look for xhr.statusText or xhr[0].statusText (again, depending on how your web service returns it.)
Success: Type: Function( PlainObject data, String textStatus, jqXHR jqXHR )
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method.
If you are using "POST" to the web service you might want to send it as a JSON string.
JSON.stringify() can assist with that. Some browser support is lacking but you can fix this with a polyfill
Last but not least, if you are sending json you want to expect json back. <? echo "success" ?> isn't going to cut it I'm afraid. Check out this post to see what I mean.
The json type parses the fetched data file as a JavaScript object and returns the constructed object as the result data. To do so, it uses jQuery.parseJSON() when the browser supports it; otherwise it uses a Function constructor. Malformed JSON data will throw a parse error (see json.org for more information). JSON data is convenient for communicating structured data in a way that is concise and easy for JavaScript to parse. If the fetched data file exists on a remote server, specify the jsonp type instead.
.
$(function () {
var ajaxOptions = {
url: "vote_add.php",
type: "POST",
dataType: "json"
};
$(".target").click(function (e) {
var options,
optionsData = {
reviewId: $(this).data('review')
};
e.preventDefault();
//options = $.extend({}, ajaxOptions, { data: optionsData });
options = $.extend({}, ajaxOptions, { data: JSON.stringify(optionsData) });
$.ajax(options).done(function (data) {
// success so use your data object
// are you looking for a property?
var myProperty = 'myProperty';
if (data.hasOwnProperty(myProperty)){
var myValue = data[myProperty];
}
}).fail(function (xhr) {
// do something on error
console.warn("myscript.js > " + xhr.statusText + ' ' + xhr.status);
}).always(function() {
// do something no matter what happens
});
});
});
Related
I use jQuery's getJSON call to rerieve the content from a file called my.json.
Now sometimes the JSON file contains a certain character, that would invalidate the syntax. Unfortunately, it is not in my power to change that.
I thought it would be easy to use the success thing to intercept the JSON string and dix it, before $.getJSON() reads it and fails because the syntax is invalid. Obviously, it's not as easy, as I thought.
I would appreciate, if someone could help me out fixing below code.
$.ajaxSetup({
beforeSend: function(xhr){
if (xhr.overrideMimeType) {
xhr.overrideMimeType("application/json");
}},
cache: false
});
$.getJSON("my.json", function(data){
// Do something with the JSON
console.log("JSON object: " + data);
}).success(function(data, textStatus, jqXHR) {
// Intercept JSON string and modify it.
var fixed_json = fix_json(jqXHR.responseText);
jqXHR.responseText = fixed_json; // Obviously not as simple as I thought.
});
You can use the success callback of $.ajax() to do the required check on the returned data. It would require you to set the dataType to text though, so that jQuery doesn't try and automatically parse it for you. Try this:
$.ajax({
url: "my.json",
dataType: 'text',
success: function(data) {
var obj;
try {
obj = JSON.parse(data);
}
catch(e) {
obj = fix_json(data);
}
// work with the object here...
})
});
Example fiddle
Depending on the work that fix_json does, and assuming that it always returns an object, you could call that directly and remove the try/catch.
I have this javascript code that performs an ajax request on button click.
$('#allinea').click(function(e){
e.preventDefault();
var password = $('#password').val();
$.ajax({
type: "POST",
url: "db_align.php",
data: {password:password},
complete: function(data){
data1=data.split("|");
if(data1[0]=="Successo"){
$("#per_all").fadeTo(200,0.1,
function(){
$(this).find('img').attr("src",'../images/ok.png');
$(this).find('.right').html(data1[1]).promise().done(function(){
$(this).fadeTo(900,1);
});
});
}else if(data1[0]=="Errore"){
$("#per_all").fadeTo(200,0.1,
function(){
$(this).find('img').attr("src",'../images/alert.png');
$(this).find('.right').html(data1[1]).promise().done(function(){
$(this).fadeTo(900,1);
});
});
}
}
}); //chiudo $.ajax
});
The php page returns "Successo|Allineamento riuscito" and I see it correctly in firebug but the js returns an error:
Type error: data.split is not a function
data1=data.split("|");
I use this code everywhere in my app without any inconvenient. What am I doing wrong this time?
For what I see btw this is not an array so this should work without any inconvenient!
jQuery will return a jqXHR here, which means that instead of accessing data directly, you will probably need to do data.responseText.
Exo's answer is perfect. It will allow you to edit the raw text.
If you know the type of data returning, you can (must) set it explicitly. jQuery will then programmatically convert data for you in the correct format.
dataType: json for JSON,
dataType: text for plain text
More can be found in the documentation.
You should update your complete method to done for success condition and fail for when the request fails.
complete is deprecated as of version 1.8, it's replaced with always, which returns a data or jqXHR object. When success complete will return a data object according to the functionality of done.
I found this site that allows to convert RSS feeds into json.
It also provides a way to specify a callback, so i think users are able to make jsonp calls to this web service.
However, i tried different ways to do that but none worked.
Here is my code:
$(document).ready(function () {
$.ajax({
type: "GET",
url: 'http://www.blastcasta.com/feed-to-json.aspx',
dataType: "jsonp",
jsonpCallback: "loadRSS",
data: {
feedUrl: 'http://xml.corriereobjects.it/rss/homepage.xml',
param: "callback"
},
success: function (data) {
var list = "";
for (var propertyName in data) {
list+=data[propertyName];
}
console.log(list);
},
error: function(xhr, ajaxOptions, thrownError){
alert(ajaxOptions)
}
});
});
Whatever i try, the success handler doesn't get executed. I get error handler instead.
I tried with jsonpCallbak: "callback", jsonpCallback: "?", param: "callback" and other values too but without success.
I have to use ONLY javascript without the support any server side scripting language (no aps, no php, etc.)
Did someone get this service working in his site?
Any suggestion would be really appreciated!
I find jQuery JSON API not suitable for this kind of JSON response that provides BlastCasta service. It assigns JSON to a custom variable, specified in URL, and doesn't uses callback functionality JSONP operates with. For example this URL:
http://www.blastcasta.com/feed-to-json.aspx?feedUrl=http%3A//xml.corriereobjects.it/rss/homepage.xml¶m=rssFeed will return following response:
rssFeed = { "rss": { "channel": /*...*/}}
So, script injection technic may be used:
/* URL of the BlastCasta service and his parameters:
feedUrl :== escaped URL of interest (RSS Feed service)
param :== javascript variable name which will receive parsed JSON object */
var url = "http://www.blastcasta.com/feed-to-json.aspx"
+"?feedUrl=http%3A//xml.corriereobjects.it/rss/homepage.xml"
+"¶m=rssFeed";
/* since the service declares variable without var keyword,
hence in global scope, lets make variable usage via window object;
although you can write param=var%20rssFeed" in the URL :) */
window.rssFeed = null;
$.getScript(url, function() {
/* script is loaded, evaluated and variable is ready to use */
console.dir(window.rssFeed);
/* some feeds are huge, so free the memory */
window.rssFeed = null;
});
Update:
here's an example that works for your code:
$.getJSON("http://www.blastcasta.com/feed-to-json.aspx?feedUrl=http://xml.corriereobjects.it/rss/homepage.xml¶m=?", function(data) {
console.dir(data);
});
problem is, that I get some javascript errors with returning json:
see this jsfiddle
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.
Here's the thing, I have a jquery click event handler, that calls a post on click.
The type that it expects (4th parameter of $.post()) is "json". However, on the
server side; there are two responses to the post: it's either json or html response. The problem is, if it returns html, the callback function isn't called (because the $.post expects a json?).
How can I react to this? I want something that if the server side script returns a json, execute callback, otherwise do another. Is that possible? Can I check the response type with $.post?
You'll most likely want to use the generic jquery.ajax function. In particular the dataType: 'text' property should allow you to parse your return value in whatever method works for you. You can also use the parseJSON function
$.ajax({
url: 'url',
type: 'post'
dataType: 'text',
success: function(text) {
if (json) {
var obj = $.parseJSON(text);
} else {
var html = $(text);
}
}
});