I'm making a plugin. I'm trying to simply update post meta in Wordpress, by posting an array/object/json array to this php code:
public static function save_settings_fields(){
$myArray = json_decode($_POST['to_save']);
wp_send_json(var_dump($_POST['to_save']));
//i can't even get to this point.
$saved_content = json_decode($_POST['to_save']);
$post_id = $saved_content['post_id'];
$this_count = (int)$saved_content['index'];
$foobar = new POB_Save_Settings;
$isdone = $foobar->update_static_content($post_id, $this_count, $saved_content);
if ( is_wp_error( $isdone ) ) {
wp_send_json_error( $isdone );
} else {
wp_send_json( $isdone );
}
}
my script is:
var SaveOptionSettings = function(postid, count){
var save_array = new Array();
save_array[0]= {};
save_array[0]['post_id'] = postid;
save_array[0]['content_count'] = count;
save_array[1] = {};
for(var i=0; i<$('#settings input').length; i++){
save_array[1][$('#settings input').eq(i).attr('id')] = $('#settings input').eq(i).val();
}
for(var i=0; i<$('#settings textarea').length; i++){
save_array[1][$('#settings textarea').eq(i).attr('id')] = $('#settings textarea').eq(i).val();
}
for(var i=0; i<$('#settings select').length; i++){
save_array[1][$('#settings select').eq(i).attr('id')] = $('#settings select').eq(i).val();
}
console.log(save_array, JSON.stringify(save_array));
var pva_ajax_url = pva_params.pva_ajax_url;
$.ajax({
type: 'POST',
url: pva_ajax_url,
dataType: 'json',
data: {
action: 'save_settings_fields',
'to_save': JSON.stringify(save_array)
}, success: function (result) {
M.toast({html: 'Saved!'})
},
error: function(xhr,textStatus,err)
{
console.log("readyState: " + xhr.readyState);
console.log("responseText: "+ xhr.responseText);
console.log("status: " + xhr.status);
console.log("text status: " + textStatus);
console.log("error: " + err);
}
});
}
The wp_send_json pretty much just sends me back what $_POST is getting, which apparently is:
readyState: 4
responseText:
string(202) "[{\"post_id\":15404,\"content_count\":1},{\"label\":\"Options <span>(please select one)</span>\",\"use_conditionals\":\"on\",\"classes\":\"form-buttons\",\"style_id\":\"options\",\"subtitle\":\"test\"}]"
null
status: 200
text status: parsererror
error: SyntaxError: Unexpected token s in JSON at position 1
What I've Tried:
using json_decode on that posted info
adding contentType: "application/json" to the AJAX
all combinations of removing Stringify, dataType, changing dataType to Text
making every variable get .pushed into an array
making the array an object, and vice versa
Am I doing something wrong?
your server response start with string (202) ,
and this is not valid json
string(202) "[{\"post_id\":15404,\"content_count\":1},{\"label\":\"Options <span>(please select one)</span>\",\"use_conditionals\":\"on\",\"classes\":\"form-buttons\",\"style_id\":\"options\",\"subtitle\":\"test\"}]"
null
and
error: SyntaxError: Unexpected token s in JSON at position 1
this s from String
you responseText shall be something like
[{
"post_id": 15404,
"content_count": 1
}, {
"label": "Options <span>(please select one)</span>",
"use_conditionals": "on",
"classes": "form-buttons",
"style_id": "options",
"subtitle": "test"
}]
// update
#lawrence-cherone php-side mention
var_dump()
wp_send_json(var_dump($_POST['to_save']));
this line need to be removed or comment
thanks for #lawrence-cherone
Also, if you'd like to debug content, you may have better success using echo or print_r.
Using one of these prints the contents of whatever you enter onto the page, which is then returned as result in the AJAX success: function(result){ ... }.
Related
I am running into an interesting issue that is throwing me for a loop. I am doing a Sharepoint RestAPI call that returns data correctly, when I run a for loop over the data it builds out the html but still tosses the error that I used as the title. Code is below. If I console log each loop it will return the value. The HTML also works fine. The issue is that error still comes up.
function getSlideData() {
var query = "$expand=AttachmentFiles&$select=Title,Team,State,Location,Hobbies,Favorite,Askme,GreatPlace,imageFact,ImageText,Attachments,AttachmentFiles&$expand=AttachmentFiles&$top=1000&$orderby=Created desc&$filter=Display eq 'Active'";
var svcUrl = SITE_URL + "_api/web/lists/getbytitle('"+LIST_NAME+"')/items?"+query;
var employeeData;
$.ajax({
url: svcUrl,
type: "GET",
headers: { "Accept": "application/json; odata=verbose" },
async: false,
success: function (data) {
employeeData = data.d.results;
},
error: function (xhr) {
alert("Can't get list items.", xhr.status + ": " + xhr.statusText);
}
});
return employeeData;
}
function buildSlides() {
var slideData = getSlideData();
var sliderWrapper = $('#slider-wrapper');
var sliderWrapperContent = "";
for(i=0;i<=slideData.length;i++) {
sliderWrapperContent += '<div><h2>'+slideData[i].Hobbies+'</h2></div>';
sliderWrapper.html(sliderWrapperContent);
}
}
The error is that you are trying to access an index that does not exist in the array because of <= in the for loop, try to use < when you use .length of an array.
I am working on my webdesign assignment based around ajax. I am having a problem with the JSON.parse() function. The problem goes as follows, I perform a get request on my JSON database using ajax:
artist_list = $.ajax({
dataType: "json",
async: false,
method: "GET",
url: "/database/artists.json",
error: function (xhr) {
console.log("AJAX error:", xhr.status);
},
success: function(xhr, responseText) {
console.log("Ajax operation succseded the code was:", xhr.status);
console.log("This is the output", responseText);
response = responseText;
console.log("Parsing artist list");
JSON.parse(response);
console.log("Artist list parsed");
},
done: function(data, textStatus, jqXHR){
console.log("data:", data);
console.log("Response text",jqXHR.responseText);
}
})
The console log of the responseText matches what the JSON file I wanted but,
when I run response text through a for loop the log returns the JSON file char by char:
artist_list = artist_list.responseText;
JSON.parse(artist_list);
console.log(artist_list);
for(var i = 0; i < 1; i++) {
console.log("generating artist,", i);
console.log("which is:", artist_list[i]);
index = parseInt(i);
index = new artist_lite(artist_list[i]);
artist_lite_dict.push(index);
}
The console returns:
generating artist, 0
which is: {
The list is limited to one because of the lenght of the JSON object which I am trying to pass through. The JSON can be found here https://github.com/Stephan-kashkarov/Collector/blob/master/main/database/artists.json along with the whole code for testing purposes.
Thanks for your help!
- Stephan
You need to save the result of JSON.parse(artist_list); into some variable. I guess in your code you would like to solve it like this:
artist_list = JSON.parse(artist_list);
When I check console in Chrome, the Sharepoint page behaves as it is supposed to when data is Object {d: Object} and d is an Array of the items of want.
When data is #document, the page does not load as I append html based on data.
I understand #document appears because of jQuery's Intelligent Guess, but am not sure why it is getting returned.
function getItems() {
var url = hostWebURL + "_api/web/lists('" + guid + "')/items/";
var items;
$.ajax({
url: url,
type: "GET",
headers: { "Accept": "application/json;odata=verbose "}, // return data format
success: function (data) {
//items is iterable ListItemCollection
console.log(data);
items = data.d.results;
...
},
error: function (error) {
var errorMsg = "";
if (error.status == "403" || error.status == "401") {
errorMsg = "You do not have Authorization to see Site Permissions - ErrorCode(" + error.status + ") Error Details: " + error.statusText;
}
else {
var errorMsg = "Failed - ErrorCode(" + error.status + ") Error Details: " + error.statusText;
}
reportError(errorMsg);
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json; odata=verbose");
Added this parameter to the call and it's working!
Taken from: http://ratsubsharewall.blogspot.com/2017/02/rest-call-returns-xml-instead-of-json.html
Here's my ajax call:
$.ajax({
url : hostGlobal + "site/modulos/prefeitura/acoes-jquery.php",
type: "POST",
dataType : "JSON",
data: {
acao: "filtrarCidades",
estado_id: $(".estados:chosen").val()
},
success: function(json) {
console.log("worked");
$(".cidades").html('');
var options = "<option value=\"\"></option>";
$.each(json, function(key, value) {
options += '<option value="' + key + '">' + value + '</option>';
});
$(".cidades").html(options);
if (!filterThroughCEP) {
$(".cidades").trigger("chosen:updated");
}
},
error: function(e) {
console.log(e.responseText);
}
});
Here's the php action:
if ($acao == 'filtrarCidades') {
$estado_id = $_POST['estado_id'];
$cidade->where = "estado_id = '".$_POST['estado_id']."'";
$cidade->LoadFromDB();
for ($c=0; $c<count($cidade->itens); $c++) {
$cidades[$cidade->itens[$c]->id] = $cidade->itens[$c]->nome;
}
echo json_encode($cidades);
die();
}
json_encode($cidades) is valid json data (UTF8), here's one example using debug:
{"1778":"Bras\u00edlia"}
This {"1778":"Bras\u00edlia"} goes as e.responseText (Error), even with Status OK, and the URL is on the same domain (No need for JSONP). I have no idea why I can't reach success.
EDIT: I've set the contentType:
contentType: "application/json",
And the call still can't "reach" success. Here's the third error argument:
SyntaxError: Unexpected token
at parse (native)
at ajaxConvert (http://localhost/sisconbr-sistema-novo/site/visual/js/jquery.js:7608:19)
at done (http://localhost/sisconbr-sistema-novo/site/visual/js/jquery.js:7363:15)
at XMLHttpRequest.<anonymous> (http://localhost/sisconbr-sistema-novo/site/visual/js/jquery.js:7835:9)
It is indeed related to unicode characters inside the strings that come from the database.
EDIT2: I wrote the whole thing again, and now it's clearer:
function getCitiesByState() {
$.ajax({
url : hostGlobal + "site/estrutura/ajax.php",
type: "POST",
dataType : "text",
data: {
action: "getCitiesByState",
state_id: $(".estados option:selected").val()
},
success: function(json, textStatus, jqXHR) {
console.log($.parseJSON(json));
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}
PHP:
if ($_POST["action"] == "getCitiesByState") {
$cities = getResults("SELECT * FROM tbl_cidades WHERE estado_id = ".$_POST["state_id"]);
echo json_encode($cities, JSON_UNESCAPED_UNICODE);
die();
}
Output:
[{"id":"1778","estado_id":"7","nome":"BrasÃlia","cep":"","loc_no_abrev":"BrasÃlia"}]
Error:
Uncaught SyntaxError: Unexpected token
I think that the problem is the object property
{"1778":"Bras\u00edlia"}
means an object with an invalid property name, thus json decoding fails;
to prove if this is right try either
use plain text as dataType and log it, it should work [but of course you will not be able to convert it to json]
changeLoadFromDB method so that property name is valid [starts with letter, _ or $], you will have a valid JSON response, but you will need to change the way you use it
it 1778 is an ID, a proper structure should be
{id:"1778",property:"Bras\u00edlia"} and work flawless
give it a try and let us know
EDIT:
as jcaron kindly suggested, i have to fix, this answer: the "1778" is indeed a valid property name, but invalid identifier if dot notation is used.
Since I don't know how jQuery manage this i would suggest to test as above, and see if one of the tests gives results.
When this function is hit , it does not call my function in code behind? Why could it be doing this? How can I fix this error.
$(document).ready(function() {
$('[id$=btn_Update]').click(function() {
var reten = $('[id$=txt_Reten]').val();
var i=0;
var selectValues = "";
var ProdID = new Array();
$("#lst_ProdId option").each(function() {
selectValues = selectValues + $(this).text() + ",";
ProdID[i] = $(this).text();
i++;
});
for(var j=0; j < ProdID.length;j++)
{
// alert(ProdID[j]);
}
var params = "{'ProdID':'" + ProdID + "','RetenP':'" + reten + "'}";
$.ajax({
type: "POST",
url: "/ProductPricing/Products/RetenPeriod.aspx/UpdateRetenPeriod",
data: params,
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function(result) {
alert("sucess");
},
error:function(e) {
alert(e.statusText);
// if(errorThrown != null)
// alert(textStatus+ ":"+errorThrown);
// else
// alert("fail");
}
});
return false;
});
return false;
});
This is my webmethod in code behind:
[WebMethod]
public static bool UpdateRetenPeriod(string[] ProdID,string RetenP)
{
for (int i = 0; i < ProdID.Length; i++)
{
update(ProdID[i],RetenP);
}
return true;
}
You're passing your parameters as a string instead of as an object literal:
var params = "{'ProdID':'" + ProdID + "','RetenP':'" + reten + "'}";
should (almost certainly) be:
var params = {'ProdID': ProdID,'RetenP': reten};
Also, how do you know that the ajax request is not making it to the server? Have you tried tracing the HTTP requests with something like TamperData (for Firefox) or Firebug (also Firefox)?
Does it call the error method?
You need to return JSON. Not a boolean. Perhaps something like {success: true}.
Then:
success: function(data) {
if(data.success) {
...
}
else {
...
}
}
jQuery expects JSON and will throw an error if it doesn't receive well-formed JSON. Also, what is the exact response you're getting back? You can use something like Firebug to figure this out.
One more thing. Can you verify that you can successfully hit that URL? Are you able to successfully point your browser to http://your.url.here/ProductPricing/Products/RetenPeriod.aspx/UpdateRetenPeriod?
Also look at Pointy's solution. Your request is unlikely to succeed since you aren't passing in an actual object literal.
Do you have a ScriptManager defined in the markup with EnablePageMethods set to true?
Also, I believe your params line should be:
var params = "{ProdID:'" + ProdID + "', RetenP:'" + reten + "'}";
I have several functions in my own apps that do it this way. You want the value of params to look like this: "{ProdID:'1,2', RetenP:'undefined'}"
Can you place a breakpoint at alert(e.statusText); to see what the error message is?
Have u got error message.. please, try to get the error message
I think, u can use this by replacing error block
error:
function(XMLHttpRequest, textStatus, errorThrown){
alert( "Error Occured!" + errorThrown.toString());
}
I think, problems occurred in code behind method.. if in [web method] has any problem, then ajax doesn't call the method..