Call ajax in file .js - javascript

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.

Related

AJAX call fails with SyntaxError: Unexpected end of JSON input

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

Parsing BBCode on AJAX success

I am in a spot here trying to parse BBCode upon a AJAX success : item.message object. I am using jQuery 1.11. I have tried passing the var result in place of item.message, and only shows the [object] errors. I have tried wrapping item.message with XBBCODE and same thing.
Im not sure what to do, the script is great otherwise. We must parse bbcode to HTML or a method that can be managed PHP-side, but I don't think this is possible over JSON data.
Currently this is my jQuery code:
$(document).ready(function () {
$.ajax({
url: "/ajax/shoutbox.php",
method: "GET",
dataType: 'JSON',
success: function (data) {
var html_to_append = '';
$.each(data, function (i, item) {
// Object array repeated - not working
var result = XBBCODE.process({
text: 'item.message',
removeMisalignedTags: false,
addInLineBreaks: false
});
/*
currentPost = jQuery(this);
postHTML = bbcodeToHTML(currentPost.html());
currentPost.html(postHTML);
*/
html_to_append +=
'<div class="shoutbox-container"><span class="shoutDate">' +
jQuery.timeago(item.date) +
' <span style="color:#b3b3b3">ago</span></span><span class="shoutUser"><img src="' +
item.avatar +
'" class="shout-avatar" /></span><span class="shoutText">' +
item.message +
'</span></div><br>';
});
$("#shoutbox").html(html_to_append);
$(".shoutbox-container").filter(function () {
return $(this).children().length == 3;
}).filter(':odd').addClass('shoutbox_alt');
$(".shoutbox-container").each(function () {
$(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('shoutbox_alt');
});
}
});
});
As you see, I'm trying to make use of the following javascript:
https://github.com/patorjk/Extendible-BBCode-Parser
I've followed the instructions exactly, before moving into the JS above with no success either way. I get this:
[object][Object]
For each iteration of the message object coming back (its a custom AJAX shoutbox).
Commented, you can see another method I have tried to no success. Any help is appreciated!
Update: Working
Thank you, Quiet Nguyen for the suggestion for replacing item.message with result.html and updating text: object

Cant print validation errors values into view with jquery

So I'm trying to show validation errors after jquery ajax call, but for some reason instead of printing the actual messagge I'm getting either +value+ or +data.success+, am I appending the values wrong?
This is my code:
$.ajax({
url: '/contactar',/*{{ action('ContactController#contactar') }}*/
type: 'POST',
data:
{
'message_body': $("textarea[name='message']").val()
},
dataType: 'JSON',
success: function (data) {
$('.form_valid_container').append('<span class="form_valid_text">data.success</span>');
form.trigger("reset");
console.log(data.success, data.errors);
},
error: function (data){
var errors = data.responseJSON;
console.log(errors);
$.each(errors , function(key , value){
console.log('error pin');
$('.form_error_container').append('<span class="form_error_text">+ value +</span>')
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Yes you are appending the values incorrectly as shown by the syntax coloring: the whole text is in dark red.
Your String is starting with a single quote ' so you need to end the string with ' too before your + value + :
$('.form_error_container').append('<span class="form_error_text">' + value + '</span>')
Answer given by #pyb and original code will almost always work. However, I can see that the DIV will keep appending the errors even though the form has been reset or triggered multiple times.
Below is the code which I prefer:
NOTE: I have used html function in the success block container which will NOT append the success message always.
NOTE: I have cleared the form_error_container using html function before printing the error messages, so that it will not keep appending the error messages even though the form is reset or triggered multiple times.
$.ajax({
url: '/contactar',/*{{ action('ContactController#contactar') }}*/
type: 'POST',
data:
{
'message_body': $("textarea[name='message']").val()
},
dataType: 'JSON',
success: function (data) {
$('.form_valid_container').html('<span class="form_valid_text">data.success</span>');
form.trigger("reset");
console.log(data.success, data.errors);
},
error: function (data){
var errors = data.responseJSON;
console.log(errors);
$('.form_error_container').html("");
$.each(errors , function(key, value) {
console.log('error pin');
$('.form_error_container').append('<span class="form_error_text">' + value + '</span>')
});
}
});
Thanks.

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 :)

Can you handle both json and html datatypes in the same ajax call?

Is there anyway I can handle both json and html return types when posting jquery ajax:
For example, this ajax call expects html back
$.ajax({
type: "POST",
url: url
data: data,
dataType: "html",
success: function (response) {
var $html = "<li class='list-item'>" + response + "</li>";
$('#a').prepend($html);
},
error: function (xhr, status, error) {
alert(xhr.statusText);
}
});
but I wanted to modify it so that I can return a json object if there is a model error. so I can do something like this:
success: function (response) {
if (response.Error){
alert(response.Message);
} else {
var $html = "<li class='list-item'>" + response + "</li>";
$('#a').prepend($html);
}
Is this possible?
For you first case, just put the html in the response.Message field. It's not uncommon to return html wrapped inside a json object so that a status code can be easily added.

Categories