Status 200 OK, same domain, valid JSON data and no response (Ajax) - javascript

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.

Related

jQuery AJAX does not detect success

I have the following code.
$(".likeBack").on("click", function(){
var user = $(this).attr("user");
var theLikeBack = $(this).closest(".name-area").find(".theLikeBack");
$.ajax({
type: "POST",
dataType: "json",
url: "processes/rewind-knock.php",
data: "user="+user+"&type=likeback",
success: function(json){
alert("SUCCESS");
},
error: function(jqXHR, textStatus, errorThrown){
alert("XHR: " + jqXHR + " | Text Status: " + textStatus + " | Error Thrown: " + errorThrown);
}
});
});
Here, everything is functional. Network tab shows request and response well received as required. However, the success part is not getting executed. I tried adding beforeSend and complete and both are getting executed but success part (nothing inside the success blog is getting executed). I don't understand the reason why.
UPDATE
Add error part. It returns:
XHR: [object Object] | Text Status: parsererror | Error Thrown: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
UPDATE 2
Screenshot
give data in ajax like this and check,
data : {'user':user,'type':'likeback'},
In your Php code when you return the data, place all data in a array then use this,
echo json_encode($arr); //return the array in json form
now in your success function use
console.log(JSON.parse(json));
hope may help you. Thank you

SyntaxError: Unexpected token s in JSON at position 1

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){ ... }.

Uncaught TypeError: Cannot read property 'results' of undefined

I'm a complete newby to JS. Trying to use SharePoint REST API to display a link list in a footer. Keep getting this error no matter what I do. It is for this line LoadFooterLinks(results.d.results);
function GetFooterLinks() {
var url = _spPageContextInfo.siteAbsoluteUrl + "/_api/lists/getbytitle('Footer Links')/items/?$orderby=Display_x0020_on_x0020_Homepage";
$.ajax({
url: url,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (results) {
LoadFooterLinks(results.d.results);
},
error: function (error) {
console.log("Error in getting List: " + listName);
}
});
}
A few things:
How do you know you have an "error"?
Is is a Javascript Exception?
WHAT IS the error or Exception?
How do you know the error isn't with your LoadFooterLinks() function?
Most likely your results are NOT what you are expecting. You're obviously:
Successfully making a connection and request
But, you can't be sure what's coming back. It could be:
empty string
null
malformed
Hitting F12 in most browsers will bring up that browser's Developer mode/built-in JS console
My code changes below should help you debug by outputting to the console for you.
Things to NOTE about the code changes:
The difference between:
catching a JavaScript runtime exception/error using try-catch vs.
outputting the string variable arbitrarily named "error" in the failure callback method of the $.ajax object
Print an exception to to the console doesn't require console.err()
If you want to show a string as an error in the console use console.err(), not console.log.
Null is an object, not a datatype or primitive like the other ones in JavaScript. For Example,
boolean
string
undefined
number
New Code
function GetFooterLinks() {
var url = _spPageContextInfo.siteAbsoluteUrl +
"/_api/lists/getbytitle('Footer Links')/items/?
$orderby=Display_x0020_on_x0020_Homepage"
;
$.ajax({
url: url,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (results) {
if (!results) { // should handle null and empty strings
try{
LoadFooterLinks(results.d.results);
}
catch (e){ // catch any JavaScript runtime exception (error)
console.log(e); // print the error to the console
// (hit F12 in most browsers to see
// the console BEFORE you refresh
// the page to run your code)
}
}
else {
var msg = "The 'results' variable is ";
var varType = typeof(results);
if (varType == "object") {
msg += "NULL";
}
else {
msg += varType;
}
}
},
error: function (error) {
// this 'error' variable can be named
// anything you'd like and is a string
// description of the AJAX error.
// This description comes from $.ajax -
// which is part of jQuery (a JS library).
// This "error" is not a native JS
// exception; therefore, you wouldn't
// use a TRY-CATCH. Also, since it's
// only a string, if you want to show it
// as an error in the console, you should
// use `console.err`, not `console.log`.
console.err("Error in getting List: (0)", error);
}
});
}
What you are basically doing is making a request to the "/_api/lists/getbytitle" method.
When that method returns a response, it will do so as an object named "results", as you can see under the "success" callback.
What you are doing afterwards is reading a property called "d" and within "d" you are trying to obtain the value of property called "results".
What the error is saying is that "d" is undefined therefore it cannot retrieve the value of "results" from "d".
I suggest you check what is inside the object "results" of the success callback.
For SharePoint API result, you would need to parse the JSON response to convert it to Javascript object. I've modified your code a bit to make it work in this case.
function GetFooterLinks() {
var url = _spPageContextInfo.siteAbsoluteUrl + "/_api/lists/getbytitle('Footer Links')/items/?$orderby=Display_x0020_on_x0020_Homepage";
$.ajax({
url: url,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (response) {
var svcData = JSON.parse(response.data).d.results;
LoadFooterLinks(svcData);
},
error: function (error) {
console.log("Error in getting List: " + listName);
}
});
}

JSON.parse give me an error but JSONLint say it's a valid json

I'm trying to make a graphic with jqplot extracting the values vía mysql ajax, I have read so much information about this, i'm IT and to me it's a little embarrasing making this question. It's causing me a big headache :(
I've spent 20 days resolving this but i can't alone myself, anyone can help me please? I have tried almost everything (json.parse, parsejson, getjson, datatype html, datatype json, method get and post.....)
I know it will be easy...
Why crash when i try to do JSON.parse(resultado) ?
http://jsonlint.com/ say it's a Valid Json, but when I try to do JSON.parse he give me an exception saying ("JSON.parse: unexpected character at line 1 column 1 of the JSON data")
It seems is the [ character
Here is the php:
<?php include('conex.php');
$datos=mysql_query("SELECT * FROM Meteorologia");
$arrDatos = array();
while ($rs=mysql_fetch_assoc($datos))
$arrDatos[] = array_map('utf8_encode', $rs);
echo json_encode($arrDatos);
?>
I obtain:
[{"FECHA":"2015-01-01","OZONO":"3","KT":"2","VV":"4"},{"FECHA":"2016-03-03","OZONO":"68","KT":"86","VV":"78"}]
The js is:
try
{
var strHtml = "";
$.ajax({
global: false,
dataType: "html",
async: false,
type: "POST",
url: $("#form").attr('action'),
data: $("#form").serialize(),
success: function(resultado){
alert('success!!'+resultado);
console.log(typeof resultado);
console.log(resultado);
//var datosRecibidos = JSON.parse(resultado);
//var datosRecibidos = jQuery.parseJSON(resultado);
var lista = "";
$.each( resultado, function( key, value ) {
if(value.FECHA == "2015-01-01")
{
alert('si!!');
}
else
{
alert('sino!!');
}
});
},
error: function(data){
alert('Error!!: '+data);
}
});
}
catch(ex)
{
alert("catch!!"+ex);
}
With the $each key value ... can i move inside the array?
After trying a lot of things (changing datatype json,html,..., method get, post...)
I debugging with the address file:///C:/xampp/htdocs/traerdatos/index.html
instead of http://localhost/traerdatos/index.html
So the solution is to CHANGE THE ADDRESS TO LOCALHOST
(Thanks to reformed that helps me with his vision)
Novel error =)

Ajax error with the same data (parsererror: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data)

I've got two pages that use the same js-file to call certain PHP-file and get data from there in JSON format. Although the data that gets in the PHP-file AND data that gets out is exactly the same, Ajax on the second page returns 'parsererror' SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data.
$.ajax({
type: 'POST',
dataType: "json",
data: {objtyp: this.objtyp, objid: this.objid},
url: '/admin/getfieldsadd.php',
success: function(data) {
//not going to happen
},
error: function (xhr, status, text) {
switch (status) {
case 404:
alert('File not found');
break;
case 500:
alert('Server error');
break;
case 0:
alert('Request aborted');
break;
default:
alert('Unknown error: ' + status + " " + text);
}
}
So have anybody encountered the same problem?
This sounds reminiscent of the dreaded BOM. Excerpt from that link:
At the beginning of a page that uses a Unicode character encoding you
may find some bytes that represent the Unicode code point U+FEFF BYTE
ORDER MARK (abbreviated as BOM).
The BOM, when correctly used, is invisible.
Perhaps check that the file's encoding is set to UTF8 Without BOM.
Maybe a mime type error.
Try to add the beforeSend property like this in your AJAX call :
$.ajax({
type: 'POST',
dataType: "json",
data: {objtyp: this.objtyp, objid: this.objid},
url: '/admin/getfieldsadd.php',
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json");
}
},
...
}
It appears the trouble was in jQuery version. Now that it's updated all seems to work fine.

Categories