parseerror SyntaxError: Unexpected token < in JSON at position 1 - codeigniter

I have an error: Unexpected token and uncaught in the promise in my code below.
function getReportData(type,shutdown,period){
var applyButton = $("#apply-filter");
var textApplyButton = applyButton.html();
applyButton.attr("disabled", true);
applyButton.html("Loading...");
startStamp = new Date().getTime();
$("#title-card").text("Loading Data..");
timerInterval = setInterval(updateInterval, 1000);
gridOptions.api.showLoadingOverlay();
$.ajax({
method: "POST",
url: "<?php echo base_url();?>api/reportApi/getPRLinesAll",
data: {type:type,shutdown:shutdown,period:period},
dataType : 'json',
headers:{api_key:"#scm-report#123"},
success : function(data){
var resData = data.data;
var columnsData = resData.columns;
var rowsData = resData.rows;
var lastUpdate = data.last_update;
var excelStyleData = resData.excelStyle;
totalData = rowsData.length;
gridOptions.api.setColumnDefs(columnsData);
gridOptions.api.setRowData(rowsData);
gridOptions.excelStyles = excelStyleData;
autoSizeAll();
if(totalData<=0){
gridOptions.api.showNoRowsOverlay();
}
fileNameExcel = generateFileName(lastUpdate);
$("#update-progress").html("Last Update on : <span class='font-strong'>"+lastUpdate+"</span>");
},
complete: function(jqXHR,textStatus){
gridOptions.api.hideOverlay();
applyButton.attr("disabled", false);
applyButton.html(textApplyButton);
clearInterval(timerInterval);
},
error: function(httpRequest, textStatus, errorThrown){
console.log("Error: " + textStatus + " " + errorThrown + " " + httpRequest);
$("#update-progress").html("Something Error, Please Try Again");
$("#title-card").text("Error happened...");
}
});
}
Error: parsererror SyntaxError: Unexpected token < in JSON at position 1 [object Object]
10.35.2.199/:1 Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received
10.35.2.199/:1 Uncaught (in promise) {message: 'A listener indicated an asynchronous response by r…age channel closed before a response was received'}

Related

Ajax post call seems to work, still throws error?

Although the code works as expected it throws
"An error occurred whilst trying to contact the server: 200 parsererror SyntaxError: Unexpected end of JSON input"
The success branch is never called but the data arrives to the api.
Should I be concerned and solve it or it probably won't cause problems elswhere? Thank you for your help.
<script>
$(document).ready(function () {
$("#Save").click(function () {
var data2send = JSON.stringify("test");
$.ajax({
url: 'https://localhost:44348/api/products/PostProduct',
type: 'POST',
data: data2send,
contentType: 'application/json',
dataType: 'json',
success: function (data2send) {
console.log(data2send);
},
error: function (jQXHR, textStatus, errorThrown) {
console.log("An error occurred whilst trying to contact the server: " + jQXHR.status + " " + textStatus + " " + errorThrown);
console.log(data2send);
}
});
});
});
</script>
Controller
[HttpPost]
[Route("PostProduct")]
public void Post([FromBody] string obj)
{
Product.prod.Add(new Product() { ProductId = 12, ProductName = obj, Price = 12 });
}

Json issue: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

I have a problem with Ajax call. I get this error in console:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data.
What is the reason of this error?
My code is:
function _save(action) {
var dataObj = {
"offer_id": offer_id,
"user_id": user_id
};
$.ajax({
url: Base_URL + "/offers/" + action + "/",
type: "POST",
data: dataObj,
success: function (data) {
//console.log(data);
var obj = JSON && JSON.parse(data) || $.parseJSON(data);
if(obj.action === 'success') {
MessageBoxOK("<?php echo __('Saved successfully'); ?>");
window.location.href = Base_URL + 'offers/view/' + obj.offer_id;
} else {
MessageBoxError("<?php echo __('Error'); ?>");
}
},
error: function (data) {
MessageBoxError("<?php echo __('Error'); ?>");
}
});
}
In my controller I have:
<?php
$offer = Model_Offers::updateOffer($_POST['offer_id'], $offerArr);
$view = json_encode(array('action'=>'success', `offer_id`=>$_POST['offer_id']), JSON_FORCE_OBJECT);

Unexpected token < while using ajax and codeigniter

I have wasted my day finding solution for this.
This is my jquery function
And this is the error I get "Uncaught SyntaxError: Unexpected token <"
Please Help
Thanks
$('#post_comment').click(function(){
var question_id=$('#question_id').val();
var comment=$('#comment').val();
var user_id=$('#user_id').val();
$.ajax({
type : 'POST',
url : 'questions/update_question',
data : {question_id:question_id,comment:comment,user_id:user_id},
success:function(response) {
$('#comment_textarea').toggleClass("hidden");
// alert(response);
var result=JSON.parse(response);
var div1="<div class='row comment_rows>";
var div2="<div class='col-sm-9 comment_description_column'></div>";
var div3="<div class='col-sm-3 comment_description_userinfo'></div></div>";
$('.comment_rows:last').append(div1,div2,div3);
$('.comment_description_column:last').text(result.comment_description);
$('.comment_description_userinfo:last').text(result.user_id);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("Status: " + xhr.status);
console.log("Message: " + thrownError);
}
});
});
in your ajax you forgot to close a class with ==> '
$('#post_comment').click(function(){
var question_id=$('#question_id').val();
var comment=$('#comment').val();
var user_id=$('#user_id').val();
$.ajax({
type : 'POST',
url : 'questions/update_question',
data : {question_id:question_id,comment:comment,user_id:user_id},
success:function(response) {
$('#comment_textarea').toggleClass("hidden");
// alert(response);
var result=JSON.parse(response);
var div1="<div class='row comment_rows>";
// you forget to close the class -----^
var div2="<div class='col-sm-9 comment_description_column'></div>";
var div3="<div class='col-sm-3 comment_description_userinfo'></div></div>";
$('.comment_rows:last').append(div1,div2,div3);
$('.comment_description_column:last').text(result.comment_description);
$('.comment_description_userinfo:last').text(result.user_id);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("Status: " + xhr.status);
console.log("Message: " + thrownError);
}
});
});

Parse JavaScript SDK Query Not Working

I would like to know why could you get this error:
Error code: 102, error message: $in requires an array
I'm using Parse JavaScript SDK.
The data structure it this one:
The source code of the function is this one:
Parse.Cloud.define(
"unfollow",
function(request, response) {
var currentUserID = request.params.currentuser;
var followedUserID = new Array(request.params.followeduser);
var queryRemoveFollower = new Parse.Query("userRelation");
queryRemoveFollower.containedIn("userObjectId", followedUserID);
queryRemoveFollower.find({
success: function(result) {
for(var i=0; i<result.length; i++) {
result[i].remove("followers", currentUserID);
result[i].save();
}
var stopFollowingQuery = new Parse.Query("userRelation");
stopFollowingQuery.equalTo("userObjectId", currentUserID);
stopFollowingQuery.find({
success: function(result) {
for(var i=0; i<result.length; i++) {
result[i].remove("following", followedUserID);
result[i].save();
}
response.success("Unfollow succesful!");
},
error: function(error) {
response.success("Something went wrong. Error code: " + error.code + ", error message: " + error.message);
}
});
},
error: function(error) {
response.success("Something went wrong. Error code: " + error.code + ", error message: " + error.message);
}
});
}
);
I know that the data is being currently sent:
fn_unfollow.parse_data_user_id = ruWNYycty7
fn_unfollow.idOfTheUserToUnfollow = KcCNa39sgk
Thanks in advance for the help!!
The problem in your code is the line:
var followedUserID = new Array(request.params.followeduser);
JavaScript's Array constructor has two possible constructors:
new Array(element0, element1, ..., elementN)
new Array(arrayLength)
Since request.params.followeduser is an integer, folowedUserID is being initalized as a EMPTY array with length of request.params.followeduser.
The fix is to use either of the following (untested...):
var followedUserID = new Array(1, request.params.followedUser);
or (preferred):
var followedUserId = [request.params.followedUser];

Error: 101 object not found for update

I've got the follwing parse.com cloud code
Parse.Cloud.afterSave("Action", function (request) {
var BookStatus = Parse.Object.extend("BookStatus");
var Book = Parse.Object.extend("Book");
var book = new Book();
var actionType = request.object.get("actionTypePointer").id;
var bookId = request.object.get("bookPointer").id;
var queryBook = new Parse.Query("Book");
var newBookStatus;
queryBook.get(bookId,{
success: function (gottenBook) {
newBookStatus = "idOfTheBookStatus";
book.id = bookId;
book.set("bookStatus", new BookStatus({id: newBookStatus}));
gottenBook.set("bookStatus", new BookStatus({id: newBookStatus}));
//OPTION 1
gottenBook.save(null,{
success: function(data) {
console.log("Bookstatus updated1");
},
error: function (data,error) {
// error is a Parse.Error with an error code and description.
console.log("Error: " + error.code + " " + error.message);
}
});
//OPTION 2
book.save(null,{
success: function(data) {
console.log("Bookstatus updated2");
},
error: function (data,error) {
// error is a Parse.Error with an error code and description.
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and description.
console.log("Error: " + error.code + " " + error.message);
}
});
OPTION1
I try to save the queried book after setting the bookStatus to the returned book.
OPTION2
I try to save the new book object after setting the book.Id
book.id = bookId;
book.set("bookStatus", new BookStatus({id: newBookStatus}));
However with any of the 2 options I end up getting in the parse.com logs:
Error: 101 object not found for update
Error: 101 object not found for update
Any idea of what I am doing wrong?
Thanks in advance!
--EDIT
New implementation with fetch:
Parse.Cloud.afterSave("Action", function (request) {
var BookStatus = Parse.Object.extend("BookStatus");
var Book = Parse.Object.extend("Book");
var book = new Book();
var actionType = request.object.get("actionTypePointer").id;
var bookId = request.object.get("bookPointer").id;
book.id = bookId;
console.log("before fetch book.id" + book.id);
var newBookStatus;
book.fetch({
success: function (book) {
newBookStatus = "XMFkXS9NVv";
book.set("bookStatus", new BookStatus({id: newBookStatus}));
console.log("book" + book);
console.log("book.id" + book.id);
console.log("book.isValid()" + book.isValid());
book.save(null,{
success: function(data) {
console.log("Book Status updated to:" +newBookStatus);
},
error: function (data,error) {
// error is a Parse.Error with an error code and description.
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and description.
console.log("Error: " + error.code + " " + error.message);
}
});
});
With result:
Input: {"place":{"__type":"GeoPoint","latitude":41.354643806134625,"longitude":2.121594674804572},"bookLocationDescription":"sad","bookPointer":{"__type":"Pointer","className":"Book","objectId":"kWcALge4az"},"actionTypePointer":{"__type":"Pointer","className":"ActionType","objectId":"kJC954w9iO"},"userPointer":{"__type":"Pointer","className":"_User","objectId":"6xpiAHX9Ju"},"createdAt":"2013-05-16T13:59:33.810Z","updatedAt":"2013-05-16T13:59:33.810Z","objectId":"PwlXhKL51l","ACL":{"6xpiAHX9Ju":{"read":true,"write":true},"*":{"read":true}}}
Result: Success
I2013-05-15T20:52:19.170Z] before fetch book.idc1iKxw3NLD
I2013-05-15T20:52:19.273Z] book[object Object]
I2013-05-15T20:52:19.273Z] book.idc1iKxw3NLD
I2013-05-15T20:52:19.273Z] book.isValid()true
I2013-05-15T20:52:19.325Z] Error: 101 object not found for update
Your afterSave hook is overwriting the fetched Book's object id. Even if you're setting the same object id on it, the object now thinks it's dirty and it's no longer a valid reference.
Avoid this by using the book returned by get() and not updating it's id:
Parse.Cloud.afterSave("Action", function (request) {
var BookStatus = Parse.Object.extend("BookStatus");
var Book = Parse.Object.extend("Book");
var book = new Book();
var actionType = request.object.get("actionTypePointer").id;
var bookId = request.object.get("bookPointer").id;
var queryBook = new Parse.Query("Book");
var newBookStatus;
queryBook.get(bookId,{
success: function (book) {
newBookStatus = "idOfTheBookStatus";
book.set("bookStatus", new BookStatus({id: newBookStatus}));
book.save(null,{
success: function(data) {
console.log("Bookstatus updated1");
},
error: function (data,error) {
// error is a Parse.Error with an error code and description.
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and description.
console.log("Error: " + error.code + " " + error.message);
}
});
});
Since you already know the id for this book, instead of using a query, you can create a pointer and fetch it directly.
Final afterSave hook:
Parse.Cloud.afterSave("Action", function (request) {
var BookStatus = Parse.Object.extend("BookStatus");
var Book = Parse.Object.extend("Book");
var book = new Book();
var actionType = request.object.get("actionTypePointer").id;
var bookId = request.object.get("bookPointer").id;
book.id = bookId;
var newBookStatus;
book.fetch({
success: function (book) {
newBookStatus = "idOfTheBookStatus";
book.set("bookStatus", new BookStatus({id: newBookStatus}));
book.save(null,{
success: function(data) {
console.log("Bookstatus updated1");
},
error: function (data,error) {
// error is a Parse.Error with an error code and description.
console.log("Error: " + error.code + " " + error.message);
}
});
},
error: function (object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and description.
console.log("Error: " + error.code + " " + error.message);
}
});
});
Here's how I did it after some running around
ParseCrashReporting.enable(this);
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
// Add your initialization code here
Parse.initialize(this, "*******", "******");
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
ParseACL.setDefaultACL(defaultACL, true);
// save the installation
ParseInstallation.getCurrentInstallation().saveInBackground();
More info on the issue in my blog post here:
http://aprogrammersday.blogspot.com/2015/02/fix-parse-101-error-object-not-found.html
Whilst looking for this error I found this thread the most useful. I wanted to add that object not found for get can also essentially mean foreign key reference not found.
The not found for get error can be incredibly unhelpful; for me it wasn't even giving a line number where the error was occurring, the error message is very vague and I could not find reference to the phrase in any of the documentation.
If you are getting this error, you will find a lot of reference to permissions issues, but if you are already using the master key then you need to find the object that is being referenced by a foreign key on your selected object.

Resources