I had an ajax function, that needed to be converted to being called with Jquery for wordpress - but now the function doesn't get called?
function getCategories()
{
alert('getCategories test');
var fData = new Object();
fData.val = '';
jQuery(document).ready(
{
type: "POST",
contentType: "application/json; charset=utf-8",
url: "php_scripts/getdeals_php.php",
data: '{"action":"GetCats", "fData":' + JSON.stringify(fData) + '}',
dataType: "json",
success: function (msg)
{
alert('Success');
var offerList = msg;
var Cats = document.getElementById('CategoriesSelect');
document.getElementById("CategoriesSelect").options.length = 0;
var optn = document.createElement('option');
optn.text = "Select Category";
optn.value = "Select Category";
Cats.add(optn);
for(var i=0;i<offerList.length;i++)
{
var optn = document.createElement('option');
optn.text = offerList[i];
optn.value = offerList[i];
Cats.add(optn);
}
},
error: function (xhr, ajaxOptions, thrownError)
{
alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
});
}
I get my 'getCategories test' alert but I don't get the 'success' or the 'error' alert
So I do not think the jquery is running.
Before I started integrating this with wordpress I was using ajax like this
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "php_scripts/getdeals_php.php",
data: '{"action":"GetCats", "fData":' + JSON.stringify(fData) + '}',
dataType: "json",
success: function (msg)
{
$('#loadingmessage').hide();
var offerList = msg;
var Cats = document.getElementById('CategoriesSelect');
document.getElementById("CategoriesSelect").options.length = 0;
var optn = document.createElement('option');
optn.text = "Select Category";
optn.value = "Select Category";
Cats.add(optn);
for(var i=0;i<offerList.length;i++)
{
var optn = document.createElement('option');
optn.text = offerList[i];
optn.value = offerList[i];
Cats.add(optn);
}
},
error: function (xhr, ajaxOptions, thrownError)
{
alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
});
I would get an erorr that ajax was unknown, and it appears I should be using jquery for this instead...?
I get no errors in the console
Well, there are some different method for calling Ajax in WP. For instance, one way would be like
FOR JS Piece
jQuery(document).ready(function($) {
// We'll pass this variable to the PHP function example_ajax_request
var fruit = 'Banana';
// This does the ajax request
$.ajax({
url: ajaxurl,
data: {
'action':'example_ajax_request',
'fruit' : fruit
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
and PHP piece
function example_ajax_request() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$fruit = $_REQUEST['fruit'];
// Let's take the data that was sent and do something with it
if ( $fruit == 'Banana' ) {
$fruit = 'Apple';
}
// Now we'll return it to the javascript function
// Anything outputted will be returned in the response
echo $fruit;
// If you're debugging, it might be useful to see what was sent in the $_REQUEST
// print_r($_REQUEST);
}
// Always die in functions echoing ajax content
die();
}
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
// If you wanted to also use the function for non-logged in users (in a theme for example)
// add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );
Thanks to wptheming
In your case, first try to follow template for JS part and secondly always remember in WP to prevent conflict, you must always use
jQuery(document).ready(function($) {
// You JS functions
});
So I tried to modify your code now on the fly, hope it works for you.
jQuery(document).ready(function($) {
var fData = new Object();
fData.val = '';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "php_scripts/getdeals_php.php",
data: '{"action":"GetCats", "fData":' + JSON.stringify(fData) + '}',
dataType: "json",
success: function (msg)
{
$('#loadingmessage').hide();
var offerList = msg;
var Cats = document.getElementById('CategoriesSelect');
document.getElementById("CategoriesSelect").options.length = 0;
var optn = document.createElement('option');
optn.text = "Select Category";
optn.value = "Select Category";
Cats.add(optn);
for(var i=0;i<offerList.length;i++)
{
var optn = document.createElement('option');
optn.text = offerList[i];
optn.value = offerList[i];
Cats.add(optn);
}
},
error: function (xhr, ajaxOptions, thrownError)
{
alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
});
});
RF: AJAX in Plugins ( WP DOCS )
Related
please tell me where I am making a mistake in this code, all functions except the last one are being processed, I can not understand why. The first 3 functions correctly submit the form and receive a response, the latter also submits the form, but for some reason the response opens on a new page.
jQuery(document).submit(function(e){
var form = jQuery(e.target);
var id = form.attr("action");
var ret = id.replace('/changepswd/','');
if(form.is("#changepswd")){
e.preventDefault();
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
success: function(data) {
console.log(data);
document.getElementById("changepswdbtn" + ret).value = '';
alertTimeout(data,1000);
}
});
}
});
jQuery(document).submit(function(n){
var form = jQuery(n.target);
var id = form.attr("action");
var ret = id.replace('/changeemailpass/','');
if(form.is("#changeemailpass")){
n.preventDefault();
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
success: function(data) {
console.log(data);
document.getElementById("changeemailpassbtn" + ret).value = '';
alertTimeout(data,1000);
}
});
}
});
jQuery(document).submit(function(q){
var form = jQuery(q.target);
var id = form.attr("action");
var ret = id.replace('/changename/','');
var btns = document.getElementById("changenamebtn" + ret).value;
if(form.is("#changename")){
q.preventDefault();
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
success: function(data) {
console.log(data);
if (data == "Имя Успешно Изменено!"){
document.getElementById("changenamelbl" + ret).innerText = btns;
document.getElementById("changenamebtn" + ret).value = '';
alertTimeout(data,1000);
}
else{
alertTimeout(data,1000);
}
}
});
}
});
jQuery(document).submit(function(o){
var form = jQuery(o.target);
var id = form.attr("action");
var ret = id.replace('/changeemail/','');
var btns = document.getElementById("changeemailbtn" + ret).value;
if(form.is("#changeemail")){
o.preventDefault();
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
success: function(data) {
console.log(data);
if (data == "Email Успешно Изменен!"){
document.getElementById("changeemaillbl" + ret).innerText = btns;
document.getElementById("changeemailbtn" + ret).value = '';
alertTimeout(data,1000);
}
else{
alertTimeout(data,1000);
}
}
});
}
});
I am returning data to the model and then I recover it with JS but I see that they come in Null, I add my code where I recover the data and where I send it
C#
[HttpPost]
public JsonResult AjaxMethod(string type, int value)
{
CascadingModelGastos model = new CascadingModelGastos();
switch (type)
{
case "ProyectoID":
model.Recurso = PopulateDropDown("SELECT Id, Descripcion FROM [dbo].[Cat_Cuenta_Recurso] ", "Descripcion", "Id");
break;
case "RecursoID":
model.SubRecurso = PopulateDropDown("SELECT Id, DescripcionSubRecurso FROM [dbo].[Cat_Cuenta_SubRecurso] WHERE Id_Cuenta_Recurso = " + value, "DescripcionSubRecurso", "Id");
break;
case "SubRecursoID":
model.TipoPago = PopulateDropDown("SELECT ID, DescripcionTipoPago FROM[dbo].[Cat_TipoPago] WHERE ESTATUS = 'A'", "DescripcionTipoPago", "Id");
DataSet Tabla = new DataSet();
Tabla = BLL.BLL.Negocio.ConaultaImporte(value);
model.Programado = "$" + Tabla.Tables[0].Rows[0]["TotalProgramadoMensual"].ToString();
break;
}
return Json(model);
}
The data that returns in null is:
model.Programado = "$" + Tabla.Tables[0].Rows[0]["TotalProgramadoMensual"].ToString();
So I invoke the method:
$("select").change(function () {
var value = 0;
if ($(this).val() != "") {
value = $(this).val();
}
var id = $(this).attr("id");
$.ajax({
type: "POST",
url: "../AjaxMethod",
data: '{type: "' + id + '", value: ' + value + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var dropDownId;
var list;
switch (id) {
case "ProyectoID":
list = response.Recurso;
DisableDropDown("#RecursoID");
DisableDropDown("#SubRecursoID");
PopulateDropDown("#RecursoID", list);
break;
case "RecursoID":
dropDownId = "#SubRecursoID";
list = response.SubRecurso;
DisableDropDown("#SubRecursoID");
PopulateDropDown("#SubRecursoID", list);
break;
case "SubRecursoID":
dropDownId = "#TipoPagoID";
list = response.TipoPago;
DisableDropDown("#TipoPagoID");
PopulateDropDown("#TipoPagoID", list);
break;
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
var models = #Html.Raw(Json.Encode(Model));
document.getElementById("Programado").value = models.Programado;
});
});
So I try to recover my model data:
var models = #Html.Raw(Json.Encode(Model));
The final question is: At what time can I recover my model data???
You can't use #Html.Raw(). Instead, use below code. To explain what is different, the #Html.Raw() is run when your web server is serving the request by a View. However, in your case, you load data by ajax() which sends a request to server, the server then serves the request and send back the JSON (not a View), hence your #Html.Raw() in your view never executed.
$("select").change(function () {
var value = 0;
if ($(this).val() != "") {
value = $(this).val();
}
var id = $(this).attr("id");
$.ajax({
type: "POST",
url: "../AjaxMethod",
data: '{type: "' + id + '", value: ' + value + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var dropDownId;
var list;
switch (id) {
case "ProyectoID":
list = response.Recurso;
DisableDropDown("#RecursoID");
DisableDropDown("#SubRecursoID");
PopulateDropDown("#RecursoID", list);
break;
case "RecursoID":
dropDownId = "#SubRecursoID";
list = response.SubRecurso;
DisableDropDown("#SubRecursoID");
PopulateDropDown("#SubRecursoID", list);
break;
case "SubRecursoID":
dropDownId = "#TipoPagoID";
list = response.TipoPago;
DisableDropDown("#TipoPagoID");
PopulateDropDown("#TipoPagoID", list);
break;
}
// TRY THIS ONE
document.getElementById("Programado").value = response.Programado;
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
I am working on an java spring application that requires the controller to return json. By receiving that json in jquery success method, I want to make html out of it.
controller returns a json like below:
return "[{\"Id\": \"1\", \"Name\": \"Apples\"}, {\"Id\": \"2\", \"Name\":\"Mangoes\"}]";
jquery used to hit that controller and then receive the json in success method:
var content;
$(document).ready(function(){
$("#submitButton").click(function(e){
var formData = getFormData();
if(formData!=false){
$.ajax({
type: 'POST',
'url': 'http://localhost:8080/Test_ReportingUI/fieldMappingNext.htm',
data: {jsonData: JSON.stringify(formData)},
dataType: 'json',
success: function(response){
for (var x = 0; x < response.length; x++) {
content = response[x].Id;
content += "<br>";
content += response[x].Name;
content += "<br>";
$(content).appendTo("#Fruits");
}
},
timeout: 10000,
error: function(xhr, status, err){
if(response.status=='timeout')
{
alert('Request time has been out','');
}
console.log(status,err);
}
}); }
});
});
below is the HTML div where I want to use above content to append:
<div id="Fruits">
fruits :
</div>
it is reaching to the controller. and also returning json. but I am not able to use that json.
Replace your for loop with
for (var x = 0; x < response.length; x++)
{
content = "<div class='fruit'><div>" + response[x].Id + "</div>";
content += "<div>" + response[x].Name + "</div></div>";
$(content).appendTo("#Fruits");
}
Your error message correctly explained that you were not appending the correct expression into the fruits
try below code
$(document).ready(function() {
$("#submitButton").click(function(e) {
var formData = getFormData();
if (formData != false) {
$.ajax({
type: 'POST',
'url': 'http://localhost:8080/Test_ReportingUI/fieldMappingNext.htm',
data: {
jsonData: JSON.stringify(formData)
},
dataType: 'json',
success: function(response) {
for (var x = 0; x < response.length; x++) {
var fContent = $("<div></div>");
var id = $("<span></span>").text(response[x].Id);
var name = $("<span></span>").text(response[x].Name);
fContent.append(id)
fContent.append(name);
$("#Fruits").append(fContent);
}
},
timeout: 10000,
error: function(xhr, status, err) {
if (response.status == 'timeout') {
alert('Request time has been out', '');
}
console.log(status, err);
}
});
}
});
});
I have a 'ng-grid' table that have 2 types of data source. One is from my database using a function called getContributors(), and another one is from a list of api(s).
The getContributors function is like the default function in the ng-grid tutorial.
function getContributors() {
var deferred = $q.defer();
$http.get(contributorsFile)
.then(function(result) {
contributors = result.data;
deferred.resolve(contributors);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
My method for loading the multiple api data is to load the database data first, and then after all the database data is all loaded it will make a request to the api using a parameter from the database data
var ajax_wait_count = 0;
gridService.getContributors().then(function(data) {
// Looping each data with angular.forEach()
angular.forEach(data, function(value, key){
var this_uid = value['uid'];
// if(ajax_wait_count==0)
// {
$timeout(function(){
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getrank.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
data[key]['ranked_tier'] = json;
// console.log(json);
},
error: function () {
// alert("Error");
}
});
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getlevel.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
data[key]['level'] = json['level'];
// console.log(json);
},
error: function () {
// alert("Error");
}
});
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getsummonercreate.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
if (json != 0) {
var date_c = json[0]['create_date'];
date_c = date_c.replace(' ', 'T');
new_date = new Date(date_c);
// console.log(json);
var datestring = new_date.format("yyyy-mm-dd HH:MM:ss");
data[key]['summoner_create_date'] = datestring;
}
else if (json == 0) {
data[key]['summoner_create_date'] = "";
}
},
error: function () {
// alert("Error");
}
});
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getlastplayed.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
if (json != "null" && json != null) {
var datedatas = json;
var datearray = [];
var thedatestr = "";
var loopidx = 1;
now_date = new Date();
now_date.setHours(0);
now_date.setMinutes(0);
now_date.setSeconds(0);
now_date.setDate(now_date.getDate() - 2);
next_date = new Date();
next_date.setHours(23);
next_date.setMinutes(59);
next_date.setSeconds(59);
// next_date.setDate(next_date.getDate());
angular.forEach(datedatas, function (value3, key3) {
datearray[key3] = parseInt(value3['createDate']);
});
datearray.sort();
datearray.reverse();
var count_played_today = 0;
angular.forEach(datearray, function (value2, key2) {
if (loopidx == 1) {
thedatestr = value2;
}
date_compare = new Date(parseInt(value2));
if (date_compare.getTime() >= now_date.getTime() && date_compare.getTime() < next_date.getTime()) {
count_played_today++;
}
loopidx++;
});
// var date_c = json[0]['create_date'];
// date_c = date_c.replace(' ','T');
var dateinsert = parseInt(thedatestr);
new_date = new Date(dateinsert);
// console.log(json);
var datestring = new_date.format("yyyy-mm-dd HH:MM:ss");
data[key]['last_played_date'] = datestring;
this_date = new Date();
date_diff = dateDiff(new_date.toString(), this_date.toString());
data[key]['last_played_date_qty'] = date_diff.d + " days " + date_diff.h + " hours " + date_diff.m + " minutes";
data[key]['count_played'] = count_played_today;
}
else if (json == "null" || json == null) {
data[key]['last_played_date'] = "";
data[key]['last_played_date_qty'] = "";
data[key]['count_played'] = 0;
}
},
error: function () {
// alert("Error");
}
});
},1500);
ajax_wait_count=0;
// }
ajax_wait_count++;
});
$scope.myData = data;
});
Now, the problem that emerges is :
The loading time for the api data is very long, and because of ajax asynchronous request, I can't make a loading function to delay the data
It appends the api data after the database data, which sometimes confuses the user whether the data is loaded or not
Sometimes in Chrome, the request is too much and it returns "err_insufficient_resources"
My question is,
Can my method of loading the api data be changed so it will make the loading time much faster and more efficient?
To make users less confused about the high amount of data, how can I make the progressbar (angular progress bar) wait for the database data + the api (AJAX) data?
Thank you in advance
I have written following function which takes a json data from a url.
function getWeatherDataForCities(cityArray){
var arrAllrecords = [];
var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
for(var i in cityArray){
for(var j=1; j<=2; j++){
var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;
$.ajax({
url: jsonurl,
dataType: "jsonp",
mimeType: "textPlain",
crossDomain: true,
contentType: "application/json; charset=utf-8",
success: function(data){
arrAllrecords[j]["cityName"] = data.list[0].city.name;
arrAllrecords[j]["weather"] = data.list[0].weather[0].description;
} });
toDaysTimestamp = toDaysTimestamp - (24*60*60);
}
}
return arrAllrecords; //returning arrAllrecords
}
$(document ).ready(function() {
var cityArray = new Array();
cityArray[0] = "pune";
var arrAllRecords = getWeatherDataForCities(cityArray);
//Print All records returned by getWeatherDataForCities(cityArray);
});
I have written some comments in above code.I have called getWeatherDataForCities function which returns all records from url.I have declared getWeatherDataForCities array in function.I want to add all returned records in that array.I have tried as above but nothing is getting into array.
In console showing j and arrAllrecords are undefined.
How to get all records in array from callback function?
you response will be highly appreciated
Your getWeatherDataForCities function won't return anything because ajax operations are asynchronous. You need to use a callback for that.
Modify your function to accept a callback function:
function getWeatherDataForCities(cityArray, callback){
var arrAllrecords = [];
var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
for(var i in cityArray){
for(var j=1; j<=2; j++){
var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;
$.ajax({
url: jsonurl,
dataType: "jsonp",
mimeType: "textPlain",
crossDomain: true,
contentType: "application/json; charset=utf-8",
success: function(data){
arrAllrecords[j]["cityName"] = data.list[0].city.name;
arrAllrecords[j]["weather"] = data.list[0].weather[0].description;
// call the callback here
callback(arrAllrecords);
}
});
toDaysTimestamp = toDaysTimestamp - (24*60*60);
}
}
}
And use it like this:
$(document ).ready(function() {
var cityArray = new Array();
cityArray[0] = "pune";
getWeatherDataForCities(cityArray, function(arrAllrecords) {
// Do something with your data
});
});
You are trying to use the empty array. When fetching the values it will always return you undefined.
var arrAllrecords = [];
arrAllrecords[2]; //undefined
arrAllrecords[2]["cityname"]; //undefined
Better you should use array of objects.
I don't know why you have used variable j. The below code works for me.
var arrAllrecords = [];
function getWeatherDataForCities(cityArray){
var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
for(var i in cityArray){
var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;
$.ajax({
url: jsonurl,
dataType: "jsonp",
mimeType: "textPlain",
crossDomain: true,
contentType: "application/json; charset=utf-8",
success: function(data){
arrAllrecords.push({
"cityName" : data.list[0].city.name,
"weather" : data.list[0].weather[0].description
});
if(arrAllrecords.length === cityArray.length) {
callback(arrAllrecords);
}
} });
}
}
function callback(arrAllrecords) {
console.log(arrAllrecords);
}
$(document).ready(function() {
var cityArray = new Array();
cityArray[0] = "pune";
cityArray[1] = "mumbai";
cityArray[2] = "delhi";
getWeatherDataForCities(cityArray);
});