Highcharts Ajax - javascript

This was something that I struggled with, and found the answer on stackoverflow, so I thought I should share it.
This is Jquery syntax.
$.ajax({
url: 'AjaxPHPScript.php'
type: 'POST',
data: "chartdata="+chartdata, // this is what I pass to the Ajax call
success: function(result) {
// this is when it comes back from Ajax
// this will NOT work
$("#"+contentdiv).highcharts(result);
// this will
// the parentheses around the JSON results inside the eval function is the key!
var chartstuff=eval("("+result+")");
$("#"+contentdiv).highcharts(chartstuff);
// I did not discover this on my own, I got the lead from this post:
// http://stackoverflow.com/questions/13718326/javascript-string-to-object
},
error: function(e) {
console.log(e);
console.log(JSON.stringify(e));
}
});

Related

How to send a POST request with Advanced Custom Fields data

I'm trying to send a post request to the rest api with some custom fields. THis is my code
let newCharacter = {
'title': $('.create-char-name').val(),
'acf': {
'char_class': $('#char-class').val(),
'char_subclass': $('#char-subclass').val(),
'char_level': $('#char-level').val()
},
'status': 'publish'
}
$.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader('X-WP-Nonce', spbk_data.nonce);
},
url: spbk_data.root_url + '/wp-json/wp/v2/character/',
method: 'POST',
data: newCharacter,
success: (response) => {
console.log("congrats");
console.log(response);
},
error: (response) => {
console.log("Sorry");
console.log(response);
}
});
The request goes through without any problems, but when I check the json, the "acf" field returns false.
I'm using the acf to wp api plugin, if that information is useful.
The only info I found about this issue was this post, but I don't really understand what the answer meant. I tried adding xhr.setRequestHeader('Content-Type', application/json); (I also tried with lower case initials), below the nonce, like the post seems to suggest, but that returns this error:
"{"code":"rest_invalid_json","message":"Invalid JSON body passed.","data":{"status":400,"json_error_code":4,"json_error_message":"Syntax error"}}"
Try something like below:
function NewCharacter(){
this.title;
this.acf;
this.status;
}
function CharInfo(){
this.char_class;
this.char_subclass;
this.char_level;
}
var charInfo = new CharInfo();
charInfo.char_class=$('#char-class').val();
charInfo.char_subclass=$('#char-subclass').val();
charInfo.char_level=$('#char-level').val();
var newCharacter = new NewCharacter();
newCharacter.title=$('.create-char-name').val();
newCharacter.acf=charInfo
newCharacter.status="publish";
$.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader('X-WP-Nonce', spbk_data.nonce);
},
url: spbk_data.root_url + '/wp-json/wp/v2/character/',
method: 'POST',
data: JSON.stringify(newCharacter),
success: (response) => {
console.log("congrats");
console.log(response);
},
error: (response) => {
console.log("Sorry");
console.log(response);
}
});
Yeah, I'm kinda dumb. I tried another plugin to make the bridge between acf and the rest api, and it worked.
It came to my mind many times to try another plugin, but I thought "they do the same thing, there's no point in trying that". It goes to show that you shouldn't just brush off solutions that seem too obvious or stupid.

MVC javascript ajax call results in xmlhttprequest warning

When running the following code I get the desired results updating my view on success, but I also get a warning in the console and certain items on the page don't work any more. I though putting the async option in would have sorted it but obviously not.
Can anyone suggest how I should change this?
xmlhttprequest on the main thread is deprecated because of its
detrimental effects to the end user's experience
$("#addSelectedModules").on("click", function () {
event.preventDefault();
$('#createLearningPathForm').validate();
if ($('#createLearningPathForm').valid()) {
var request = $.ajax({
async: true,
type: "POST",
url: "/umbraco/Surface/CreateLearningPath/SetSelectedList",
data: $('#createLearningPathForm').serialize(),
success: function (data) {
$("#top").html(data);
},
error: function (data) {
//$('#failModal').removeClass("d-none").addClass("d-block");
}
})
}
}
);

jQuery.when() doesn't seem to be waiting

I need to make a server side call when a user does something in the DOM (click a checkbox, select a dropdown, etc. This is the series of events:
User clicks a checkbox (or something)
A spinner fades in and the UI becomes unavailable
The server side call is made, and gets back some JSON
A label in the UI is updated with a value from the JSON
The spinner fades out and the UI becomes available again
The problem I'm having is that 4 and 5 often get reversed, and the spinner fades out sometimes 2 or 3 seconds before the label is updated.
I'm trying to use .when() to make sure this isn't happening, but I don't seem to be doing it right. I've been looking at this thread, and this one, and jquery's own documentation.
Here's where I'm at right now...
function UpdateCampaign() {
$('#overlay').fadeIn();
$.when(SaveCampaign()).done(function () {
$('#overlay').fadeOut();
});
}
function SaveCampaign() {
var formData =
.... // get some data
$.ajax({
url: '/xxxx/xxxx/SaveCampaign',
type: 'GET',
dataType: 'json',
data: { FormData: formData },
success: function (data) {
var obj = $.parseJSON(data);
.... // update a label, set some hidden inputs, etc.
},
error: function (e) {
console.log(e)
}
});
}
Everything works correctly. The server side method is executed, the correct JSON is returned and parsed, and the label is updated as expected.
I just need that dang spinner to wait and fade out until AFTER the label is updated.
The issue is because you're not giving $.when() a promise. In fact you're giving it nullso it executes immediately. You can solve this by returning the promise that $.ajax provides from your SaveCampaign() function like this:
function SaveCampaign() {
var formData = // get some data
return $.ajax({ // < note the 'return' here
url: '/xxxx/xxxx/SaveCampaign',
type: 'GET',
dataType: 'json',
data: { FormData: formData },
success: function (data) {
var obj = $.parseJSON(data);
// update a label, set some hidden inputs, etc.
},
error: function (e) {
console.log(e)
}
});
}
I know its answered by Rory already. But here's mine promise method, it works fine always and instead of using success and error uses done and fail
var jqXhr = $.ajax({
url: "/someurl",
method: "GET",
data: {
a: "a"
});
//Promise method can be used to bind multiple callbacks
if (someConditionIstrue) {
jqXhr
.done(function(data) {
console.log('when condition is true', data);
})
.fail(function(xhr) {
console.log('error callback for true condition', xhr);
});
} else {
jqXhr.done(function(data){
console.log('when condition is false', data);
})
.fail(function(xhr) {
console.log('error callback for false condition', xhr);
});
}
Or if I want a common callback other than conditional ones, can bind directly on jqXhr variable outside the if-else block.
var jqXhr = $.ajax({
url: "/someurl",
method: "GET",
data: {
a: "a"
});
jqXhr
.done(function(data) {
console.log('common callback', data);
})
.fail(function(xhr) {
console.log('error common back', xhr);
});

Should you check ajax return data or let javascript throw a error on empty data?

So when handling, for example, the success data in jquery, should you check if the return data has the necessary data like this:
success: function (data) {
if (data.new_rank !== undefined) {
$('._user_rank').html(data.new_rank);
}
}
Or let it fail when it is not present?
success: function (data) {
$('._user_rank').html(data.new_rank);
}
in the previous example you can check if something has changed and needs to be fixt because of the error.
What approach is the best?
It's better you check it, for other code that may be you have in complete or other event. If you didn't, they will not run after error. You can check it this too:
success: function (data) {
if (data.new_rank) {
$('._user_rank').html(data.new_rank);
}
}
jQuery ajax requests provide you a way to handle request errors.
$.ajax(url, {
success: function(data) {
// success
},
error: function() {
// error
}
});
If it's not a request error that you are trying to catch you still should handle error by yourself and not let javascript throw them all the way.
One solution I would say is follow strict data type in $.ajax like dataType: json.
Use success and error handler. And if the return data is anything other than json type it will be handled through error handler.
$.ajax(url, {
dataType: 'json'
success: function(data) {
// success
},
error: function() {
// error
}
});

Prototype conversion ajax.updater

I have got a website that currenty uses prototype that im trying to get away from. These are the only 3 functions that use it.
I have been trying all morning to convert these but as my understanding of jquery isnt great im so struggling.
function GetCountries() {
new Ajax.Updater('country_list','site_countries.php', {parameters: '&onchange=1', onComplete: GetRegions});
}
function GetRegions() {
new Ajax.Updater('region_list','site_regions.php', {parameters: '&regionID='+$('regionID').value+'&countryID='+$('countryID').value+'&onchange=1', onComplete: GetTowns});
}
function GetTowns() {
new Ajax.Updater('town_list','site_towns.php', {parameters: '&regionID='+$('regionID').value+'&countryID='+$('countryID').value});
}
this is what i have come up with but it doesnt work:
function GetCountries() {
$.ajax({
type: "POST",
url: "site_countries.php",
data: '&onchange=1',
success: function( transport ){
$('#country_list').html(transport.responseText)
GetRegions
}
});
}
the page that is calls just returns a select dropdown list that replaces one within span called country_list on the page then it calles GetRegions which does the same.
Any assistance would be greatly received!
Steve
It is possible that the way you are providing the data field might be the issue here.
Try something like the following:
$.ajax({
type: "POST",
url: "site_countries.php",
data: {onchange: 1},
success: function( transport ){
$('#country_list').html(transport.responseText)
GetRegions
}
});
OR
function GetCountries() {
$("#country_list").load("site_countries.php", {onchange: 1}, function(){
// call your GetRegions() here
});
}

Categories

Resources