Tabulation added to returned ajax call data - ajax

my problem is that whenever I do an ajax call and console.log the returned data, there is a tabulation in front of my returned data. Is this normal? If so, is there a way to strip the tabulation from the data variable? My code is below.
function search_rhymes_get_rhyme_content() {
echo 'Test';
die();
}
$.ajax( {
url: rhymes_ajax_obj.ajaxurl,
data: {
'action': 'search_rhymes_get_rhyme_content'
},
success: function( data ) {
console.log( 'Test:' + data );
},
error: function( error ) {
console.log( error );
}
} );
Thanks

I got it working. Output: https://ibb.co/QQHGgXV
I added the following line before my console.log:
data = data.trim();
Here's the updated code with the solution:
function search_rhymes_get_rhyme_content() {
echo 'Test';
die();
}
$.ajax( {
url: rhymes_ajax_obj.ajaxurl,
data: {
'action': 'search_rhymes_get_rhyme_content'
},
success: function( data ) {
console.log( 'Test1:' + data );
data = data.trim();
console.log( 'Test2:' + data );
},
error: function( error ) {
console.log( error );
}
} );

Related

A simple Ajax call in wordpress doesn't give the expecetd output

Here is my javascript file:-
jQuery(document).ready( function($) {
$('#test_button').click(function(e){
alert("test");
$.ajax({
url : my_ajax_object.ajaxurl ,
type : 'post',
dataType : 'json',
data : {
action : 'do_ga'
},
complete: function(res, status) {
if( status == 'success' ) {
console.log("success "+res);
} else {
console.log("fail "+res);
}
}
});
});
});
here is my php code in functions.php:-
function do_ga() {
die("test" );
}
add_action( 'wp_ajax_do_ga', 'do_ga' );
add_action( 'wp_ajax_nopriv_do_ga', 'do_ga' );
//this is the script en queuing
function my_enqueue() {
wp_enqueue_script( 'ga-loadmore', get_template_directory_uri() . '/pl-custom/front-end-assets/js/ga-loadmore.js', array('jquery') );
wp_localize_script( 'ga-loadmore', 'my_ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
So,upon the click of the button with id "#test_button" , instead of outputting success [object][object] , it outputs fail [object][object]. What needs to be done here. Precisely , i want "success test". please add the json_encode and decode wherever required in the solution.Thanks
I've separated the PHP code in another file and included it in functions.php and also separated the enqueuing, and changed the syntax of the request a little. I hereby attach my code and it works:
function do_ga() {//server code
$x="test";
wp_die( $x);
exit;
}
add_action( 'wp_ajax_do_ga', 'do_ga' );
add_action( 'wp_ajax_nopriv_do_ga', 'do_ga' );
client side(already enqueued):-
jQuery(document).ready( function($) {
$('#test_button').click(function(e){
url = window.location.origin + '/wp-admin/admin-ajax.php?action=do_ga';
alert("test");
$.ajax({
async: true,
type: 'POST',
url: url,
data: {
'my_number':1 //you need not pass data
},
complete: function(res, status) {
if( status == 'success' ) {
alert("success "+ res.responseText);
} else {
alert("unable to process request");
}
}
})
});
});

Not resolved promises with File objects after POST form requests

I'm using fetch Web API to retrieve file content from a couple of URLs and send it to a form. However, when sent to the backend from a form POST ajax request, instead of having the actual File Objects there, I'm retrieving Promise objects (which cannot be handled at the backend).
What is wrong in the code below that prevents infile and mapfile variables when sent to $.ajax to have a File object?
let formData = new FormData();
let exampleb2pPromise = fetch( fileHash["infile"].fileURL).then(function(response) {
fileHash["infile"].blob = response.blob();
return fileHash;
}).then(function(fileHash) {
let infile = new File( [ fileHash["infile"].blob ], fileHash["infile"].filename, { type: fileHash["infile"].filetype } );
return infile;
});
let exampleCSVPromise = fetch(fileHash["mapfile"].fileURL).then(function(response) { ...
Promise.all([exampleb2pPromise, exampleCSVPromise]).then(function(values) {
let infile = values[0];
let mapfile = values[1];
if ( infile && mapfile ) ) {
console.log( infile );
formData.append( "infile", infile, "input.tsv" );
if ( mapfile ) {
console.log( mapfile );
formData.append( "mapfile", mapfile, "mapfile.txt" );
}
}
return formData;
}).then( function( formData ) {
let exec = "/submit";
console.log( formData );
$.ajax({
url : exec,
type: "POST",
data : formData,
processData: false,
contentType: false,
success:function(data, textStatus, jqXHR){
if ( data && data.session ) {
...
}
},
error: function(jqXHR, textStatus, errorThrown){
//if fails
// TODO: To be handled
}
});
});
response.blob() returns a Promise - you'd need to rewrite your code something like
let exampleb2pPromise = fetch( fileHash["infile"].fileURL).then(function(response) {
return response.blob();
}).then(function(blob) {
fileHash["infile"].blob = blob;
return fileHash;
}).then(function(fileHash) {
let infile = new File( [ fileHash["infile"].blob ], fileHash["infile"].filename, { type: fileHash["infile"].filetype } );
return infile;
});
Although, it's far easier to write it like:
let exampleb2pPromise = fetch( fileHash.infile.fileURL)
.then(response => response.blob())
.then(blob => new File(fileHash.infile.blob = blob, fileHash.infile.filename, { type: fileHash.infile.filetype } ));

How do you pass ajax success data out of a container function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
Having this function :
var mapdata={};
console.log( mapdata[0].phones );
function fetchSteeringRecs()
{
$.ajax({
url : "./php/ajxcontrol.php",
type : "POST",
data : { dorecs:1 },
dataType : "json",
async : false,
//success : successHandler,
success : function(data) {
mapdata = data;
// console.log( data[0].phones );
}
});
}
/*
function successHandler(data, status ) {
console.log( data[0].phones );
}
*/
i would like to use the returned data after assigning it to 'mapdata' object - but i keep getting error in console:
Uncaught TypeError: Cannot read property 'phones' of undefined
As can be seen i have tried accessing the data from within a callback successHandler function and it works ok - also i can access the returned data directly in the ajax success func (both commented out) - but i really need it in the 'global object 'mapdata'
Is this possible or is my technique here wrong?
One simple way is create a function that will process the returned data and call that function in the success callback (should be using promises) like so:
function doStuffWithMapData(mapdata){
console.log(mapdata);
}
...
...
success : function(data) {
mapdata = data;
doStuffWithMapData(mapdata);
// console.log( data[0].phones );
}
Likewise, you could just use the global variable:
var mapdata = {};
function doStuffWithMapData(){
console.log(mapdata);
}
...
...
success : function(data) {
mapdata = data;
doStuffWithMapData();
// console.log( data[0].phones );
}
You should do
success : function(data) {
console.log( data );
}
to find the output data structure.
EDIT
use this
var mapdata;
function fetchSteeringRecs()
{
$.ajax({
url : "./php/ajxcontrol.php",
type : "POST",
data : { dorecs:1 },
dataType : "json",
async : false,
success : function(data) {
mapdata = data;
successHandler();
}
});
}
function successHandler() {
console.log( mapdata[0].phones );
}

AJAX response match any status

I have the following code:
$.ajax(
{
url: "control/" + id + ".php",
data: $("auth-form").serialize(),
statusCode:
{
200: function( response )
{
},
401: function( response )
{
},
401: function( response )
{
},
}
}
);
I need to set callback to 'any' status, whether it's 200 or 404 I need it to trigger the same callback function, something like this:
$.ajax(
{
url: "control/" + id + ".php",
data: $("auth-form").serialize(),
response = function( r )
{
alert('got ' + r.status);
}
}
);
Closest solution I found was using success/fail, but I need to combine them somehow. Any suggestions? Thanks!
Try with complete:
$.ajax({
url: "control/" + id + ".php",
data: $("auth-form").serialize(),
complete: function( r ) {
alert('got ' + r.status);
}
}
);

Kill an ajax process

GET_DATA()
GET_DATA() contains this:
var xhr;
...
function get_data( phrase ) {
xhr = function get_data( phrase ) {
$.ajax({
type: 'POST',
url: 'http://intranet/webservice.asmx/GetData',
data: '{phrase: "' + phrase + '"}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function( results ) {
$("#div1").empty();
if( results.d[0] ) {
$.each( results.d, function( index, data ) {
$("#div1").append( data.Group + ':' + data.Count + '<br />' );
});
} else {
alert( "results.d does not exist..." );
}
},
error: function(xhr, status, error) {
$('#spanLoading').empty();
var err = eval("(" + xhr.responseText + ")");
alert(err.Message) ;
}
});
}
function get_default() {
$('#div1').empty().append("default stuff goes here");
}
UPDATE 2 CODE
I've also tried this, which doesn't work either, no error messages, just returns the results of when the textbox had 2 characters when it finishes processing even if I delete everything before the process has finished:
$('#TextBox1').keyup( function() {
if(xhr && xhr.readystate != 4){
xhr.abort();
}
if ($("#TextBox1").val().length >= 2) {
get_data( $("#TextBox1").val() );
} else {
get_default();
}
});
UPDATE 1 CODE:
$('#TextBox1').keyup( function() {
if ($("#TextBox1").val().length >= 2) {
get_data( $("#TextBox1").val() );
} else {
if(xhr)
{
xhr.abort();
}
get_default();
}
});
ORIGINAL QUESTION:
I have the following code:
$('#TextBox1').keyup( function() {
if ($("#TextBox1").val().length >= 2) {
get_data( $("#TextBox1").val() );
} else {
get_default();
}
});
This has a slight glitch where if I type something really fast and then I delete it equaly fast, I see the data from get_default() flash on the screen, then it gets replaced by a previous ajax request where the value in the textbox was 2 which had not finished processing.
So basically, what I think is happening is that when the textbox has 2 characters in it, the ajax request starts which takes a second or 2. While this is happening, if I delete the 2 characters, I see the get_default() being successful, but it seems to replace it with the ajax data when the ajax data finishes.
How do I stop this from happening?
Thank you for posting get_data.
The reason why your AJAX call is not getting aborted is that xhr is not defined in the appropriate (window) scope; therefor, xhr.abort() doesn't do anything (and quite probably throws an error if you take a look at your console).
Please try the following:
var xhr = false;
function get_data( phrase ) {
xhr = $.ajax({ /* ... etc */
}
The rest should work as is.
Place a time delay before you execute your ajax request.
function pausecomp(ms) {
ms += new Date().getTime();
while (new Date() < ms){}
}

Resources