$.ajax JSON not passing values on complete - javascript

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.

Related

Intercept and modify JSON string before jQuery.getJSON() does its thing

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.

error with split: split is not a function

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.

JS Post to Php Issue

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
});
});
});

Can ajax call on return add new javascript function to the page?

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.

jQuery Ajax HTTP Request INTO a click function - not working

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'

Categories

Resources