AJAX call fails with SyntaxError: Unexpected end of JSON input - javascript

Sorry for making a post with a generic error but I just can't figure this out! I have an ajax call that for now sends an empty object and just returns json_encode(array('status' => 'success')); while I'm debugging. The ajax call is failing with Error in ajax call. Error: SyntaxError: Unexpected end of JSON input
I've tried sending just data['pid']='csv' in case the json needed to have something in it, but still get the same error.
AJAX call
function runDataDownload() {
var data = {};
// data['rawFiles'] = $('#projectIDs').val();
// data['metadata'] = $('#getData').val();
// data['type']= $('#submitType').val();
// data['pid']='csv';
// data['command']='data/qcTest';
console.log(data);
console.log(typeof data)
var qcRunId="csv" + Date.now();
var posturl = baseURL + "manage/ajax_runBg/csv/" + qcRunId;
$.ajax({type: "POST", url: posturl, data: data, dataType: 'json'})
.done(function(result) {
console.log(result);
if (result.status==='success'){
// begin checking on progress
checkRunStatus(qcRunId, loopIndex);
}
else if (result.status==='failed'){
$('#' + errorId + ' > li').remove();
$.each(result.errors, function(key, value) {
$('#' + errorId).append( "<li>" + value + "</li>" );
});
$('#' + statusId).hide();
$('#' + errorId).show();
}
else {
$('#' + errorId + ' > li').remove();
$('#' + errorId).append( "<li>Invalid return from ajax call</li>" );
$('#' + errorId).show();
// PTODO - may not be needed
// make sure it is visible
$('#' + errorId).get(0).scrollIntoView();
}
})
.fail(function(jqXHR, status, err) {
console.log(jqXHR + status + err);
$('#' + errorId + ' > li').remove();
$('#' + errorId).append( `<li>Error in ajax call. Error: ${status} (${err.name}: ${err.message})</li>`);
$('#' + errorId).show();
});
}
And my php code:
public function ajax_runBg($qcName, $runId) {
echo json_encode(array('status' => 'success'));
}
Thank you!

Making my comment an answer in case someone else runs into this-
The reason the code was working in my controller was that my colleague's controller had authentication checks in the constructor! So there must have been an authentication error returned, that was not JSON formatted, hence the error..

Something seems to clear the PHP output buffer after ajax_runBg has been called. Check this by adding ob_flush(); flush(); to ajax_runBg after the echo statement.

Sorry for making an answer, when i don't have a full one, I don't have enough reputation to comment.
I ran this code (i removed variables that i don't have) and did not get an error (nothing wrong with "echo json_encode(array('status' => 'success'));").
Here are some possible reasons why it fails:
Your problem could be that the php does not echo anything.
I once got this problem and fixed it by first making a variable out of json_encode("stuff to encode") and then doing echo on that variable.
Is there more to the php file that you did not show? There could be a problem if there are other things being echoed.

If i remember right, than you have to specify the key and the value in data attr. .
var data = {};
data['rawFiles'] =$('#projectIDs').val();
data['metadata'] = $('#getData').val();
data['type']= $('#submitType').val();
data['pid']='csv';
data['command']='data/qcTest'
... Ajax...
Data: {dataKey: data}
....
And in the API you can catch it with dataKey name.

When sending json you must first encode it as json, so:
$.ajax({type: "POST", url: posturl, data: JSON.stringify(data), dataType: 'json'})
JSON.stringify

Related

ajax data isn't the same in chrome vs firefox

Some reason I can return data fine from a POST in Chrome. The data returned looks like this when using Chrome:
{"email":"account#bytestand.com","customer_id":20413,"credit_amount":50.0,"currency_symbol":"$"}
But then when the same POST is completed on FireFox I get the following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
Somehow the data isn't being handled the same and I don't know why.
Here is the code that generates the ajax request
function getCustomerAndCredit() {
console.log("getCustomerAndCredit");
$(function() {
$("form[action='" + shopAddress + "/account/login']").submit(function(event){
console.log("this is past the submit event in Firefox");
var custEmail = $("form[action='" + shopAddress + "/account/login'] input[type=email]").val();
var pass = $("form[action='" + shopAddress + "/account/login'] input[type=password]").val();
sessionStorage.setItem('custEmail', custEmail);
sessionStorage.setItem('pass', pass);
sessionStorage.setItem('loggedIn', true);
debugger;
$.ajax({
url: "/apps/proxy/return_customer",
data: {email: custEmail},
type: "POST",
dataType: "js",
complete: function(data) {
debugger;
if(noCustomerInDB(data)){
if(data.responseJSON == undefined){
sessionStorage.setItem('customer_id', JSON.parse(data.responseText).customer_id);
sessionStorage.setItem('creditAmount', JSON.parse(data.responseText).credit_amount);
sessionStorage.setItem('currency', JSON.parse(data.responseText).currency_symbol);
}
else {
sessionStorage.setItem('customer_id', data.responseJSON.customer_id);
sessionStorage.setItem('creditAmount', data.responseJSON.credit_amount);
sessionStorage.setItem('currency', data.responseJSON.currency_symbol);
}
}
// console.log("What is the credit_amount here in getCustomerAndCredit " + sessionStorage.getItem('creditAmount'));
},
});
});
});
}
And then this is where the data is going:
function noCustomerInDB(data){
console.log("this is the todd variable " + data);
console.log("stringify data " + JSON.stringify(data));
console.log("what about just data?? " + JSON.parse(data));
console.log("this is the response down here in the no customer function" + data.responseText);
if(data.responseText == ""){
return false;
}
else{
if (JSON.parse(data.responseText).customer_id == "no_customer"){
sessionStorage.setItem('creditAmount', "null");
return false;
}
else{
return true;
}
}
}
I did some more digging and now its looking like the ajax isn't being called on FireFox. Because the data returned from the POST looks like this:
{"readyState":0,"status":0,"statusText":"error"}
This cannot be - dataType: "js"
Use dataType: "json" instead. Also make sure that "/apps/proxy/return_customer" has the proper header configured to deploy JSON:
"Content-Type: application/json"

How to POST with AJAX using just an a tag

I have an a tag that is dynamically generated with database content, it includes a data-target that I capture in javascript when it is clicked on, this is an example of one of the generated buttons:
Edit
Simple, right?
Now, what I do in the JS when it is clicked, is as so:
var $this = $(this),
$target = $this.data("target"),
$endpointURL = "";
$endpointURL = $target.split("?id=")[0];
$id = $target.split("?id=")[1];
This allows me to set the endpoint I want, in out example above, it would be "edit" and also set the id which is just a number at this point.
Now, I have to POST this ID to the edit endpoint to return the right info, correct?
So, here is my AJAX for that:
$.ajax({
type: "POST",
data: '{"id": ' + $id + ' }',
url: "../assets/scripts/php/" + $endpointURL,
success: function (data) {
$("#content-lockup").html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error: " + textStatus + ", error thrown: " + errorThrown);
}
});
This does not throw an error and does indeed output a var dump of the $_POST array as I have set it to, however it doesnt contain my ID that I passed over, here is the code on the endpoint and a screenshot of the output:
<?php
var_dump($_POST);
?>
Why would the vardump on $_POST not contain the id that I passed over in the apparently successful AJAX request?
What I expect is that I can say on the endpoint, something like:
$id = $_POST['id'];
Maybe its something obvious that i'm doing wrong but yeah, any ideas?
it's because you are passing a string to data that isn't form encoded
Make it an object and jQuery will encode it for you
data: {"id": $id },
If it's a string it needs to be in format
data: 'id=' +id + '&someOtherParam=' + somevar

Syntax difficulties in ajax

I have a function connected with onclick button.
It sends some data through ajax to another php file.
Actually everything was working fine, but I tried to add now to 'success' a simple IF statement, that would get true or false from external file.
I guess some of the syntax may be wrong here because the error message says that my main fuction is not defined.
Could someone find some mistakes here please?
main file (here in success: i have added if else statement only):
$.ajax({
type: 'get',
url: '/editcomment',
data: {newComment: newComment,
id: id,
userId: userId},
success:function(data){
if(data.success){
$(".newCommentForm" +id).replaceWith("<span id='" + id + "' class='limitedText'>" + newComment + "</span>");
$(thisId).data("PinComment", newComment);
}
else { alert('error');},
error:function(){
alert('error');
}
});
}
external file (i have added the return arrays here):
public function editComment(){
$userId = Input::get('userId');
if ( $userId == Auth::id() or Auth::user()->hasRole("admin")){
$id = Input::get('id');
$newComment = Input::get('newComment');
DB::update('UPDATE `comments` SET f_text = ? WHERE h_id = ?', array($newComment, $id));
return array('success' => true);
} else {
return array('success' => false);
}
}
You have a typo here else { alert('error');},, you need another closing brace to close the success function.
You are trying to access PHP array in JS that not possible. What you need to do is, either you need to return response as an string or JSON from PHP file
see: Get data from php array - AJAX - jQuery
Get rid of commas. Try this in else block
jAlert('No Success', 'alert box');

Call ajax in file .js

i have a problem with this :
function inicioConsultar(){
$(function(){
$('#serviciosU').change(function(){
if ($('#serviciosU').val()!= "-1")
{
$.ajax({
url: "#Url.Action("ObtenerCapas")",
data: {urlServicioUsuario:$("#serviciosU :selected").val()},
dataType: "json",
type: "POST",
error: function() {
alert("An error occurred.");
},
success: function(data) {
var items = "";
$.each(data, function(i, item) {
items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
});
$("#capas").html(items);
}
});
}
})
});
I put in my Index.cshtml "inicioConsultar()" and there is a problem with ajax, because if i delete the call ajax everything it is ok.
In loyout, i load jquery and the index it is inside layout.
Sorry for my english.
This is a syntax error:
"#Url.Action("ObtenerCapas")",
That isn't how strings work in JavaScript. You need to escape the inner double quotes, as they're terminating the string.
Try
"#Url.Action(\"ObtenerCapas\")",
However, that wont' solve your problem, unless #Url.Action(...) is a real URL on your server, or your AJAX set has some kind of ability to evaluate that string as a function call.

unable to execute javascript jquery function

I have a Jquery autocomplete function through callback method. However it doesn't seem to run.
Here is my code:
At Client-Side:
<script type="text/javascript">
$(document).ready(function() {
alert("hi");
$("#Text1").autocomplete({
minLength: 0,
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'BlissMaker.aspx/GetNames',
data: "{ 'sname':'" + request.term + "' }",
dataType: "json",
dataFilter: function (data) { return data; },
success: function (data) {
if (data.d != null) {
response($.map(data.d, function (item) {
return {
label: item.Name,
value: item.Id
}
}))
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
}
});
},
focus: function (event, ui) {
$("#Text1").val(ui.item.label);
return false;
}
})
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a><img src='" + item.icon + "' width='32' height='32' /> " + item.Name + "</a>")
.appendTo(ul);
};
}
</script>
At Code-Behind:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<States> GetNames(string sname)
{
List<States> sbStates = new List<States>();
con = new SqlConnection("Data Source=PRATEEK\\SQLEXPRESS;Initial Catalog=BD;Integrated Security=True;Pooling=False");
con.Open();
Me mee = (Me)Session["Me"];
qr = "SELECT FBFriends.FB_Id2, ActiveInfo.Name, ActiveInfo.Profile_Pic, ActiveInfo.Gender FROM [FBFriends],[ActiveInfo] WHERE FBFriends.FB_Id1='" + mee.Id + "' AND ActiveInfo.FB_Id=FBFriends.FB_Id2";
ds = new DataSet(qr);
da = new SqlDataAdapter(qr, con);
da.Fill(ds);
ds.Tables[0].Select(ds.Tables[0].Columns[1].ColumnName + " Like '%" + sname + "%' and " + ds.Tables[0].Columns[3].ColumnName + " = 'Female'");
foreach (DataRow row in ds.Tables[0].Rows)
{
States st = new States();
st.Id = row.ItemArray[0].ToString();
st.Name = row.ItemArray[1].ToString();
st.Value = row.ItemArray[1].ToString();
st.Icon = row.ItemArray[2].ToString();
sbStates.Add(st);
}
return sbStates;
}
It seems that autocomplete function is not getting called as well as Alert()..
Any suggestions on how to call it?
ADDED:
After checking the stack trace, it gives me an error
Unknown Method name GetNames
Any suggestions?
You forgot one closing at the end ")";
$(document).ready(function() {
})
After fixing that part check the response and request in console of firebug or such.
Try cleaning up the code errors and run it again:
Problem at line 19 character 43: Missing semicolon.
}
Problem at line 20 character 41: Missing semicolon.
}))
Problem at line 39 character 13: Expected ')' and instead saw ''.
}
Problem at line 39 character 13: Missing semicolon.
}
Is $(document).ready() getting called at all? If not, is you javascript in a separate file? If so, maybe the file itself is not reachable and the ready() function isn't even being called. Check the <script src=""></script> tags for including the JQuery files and your javascript file.
I'm not sure if this is causing your problem or not, but I noticed in your JQuery $.ajax call you had this line here:
data: "{ 'sname':'" + request.term + "' }",
I've found ajax calls to fail if I concat variables and strings in the data: field of the $.ajax call.
Try this:
declare a variable outside the call like this:
var dataToSend = "{ 'sname':'" + request.term + "' }";
then change the data: field to this:
data: dataToSend,
This may or may not solve your problem, but it looks nicer! Try it anyways!
Thank You everyone. I finally got my mistake.
The Web Method needed to be Static in order to call it and also ScriptManager included in the form must be EnablePageMethods=true
My code is working all fine now. Thanks a lot :)

Categories