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);
}
});
});
Related
I'm trying to retrieve data from my controller function but this very simple example fails and sends me nothing back. The ajax function is successfully executed but the data is empty.
function company_select() {
var data;
var username = $('[name="username"]').val();
var url = base_url+'/admin/user/get_companies2';
alert(url);
$.ajax({
url: url,
type: 'POST',
dataType: 'text',
success: function(data){
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) { alert(textStatus + " " + errorThrown) }
});
}
codeigniter function
public function get_companies2(){
echo 'test';
}
You Should Use "data" instead of "dataType" Or Passed your require variables one by one as into curli braces of data (as data:{variable1:})
function company_select(){
var data;
var username = $('[name="username"]').val();
var url = base_url+'/admin/user/get_companies2';
alert(url);
$.ajax({
url: url,
type: 'POST',
data: {username :username},
success: function(data){
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) { alert(textStatus + " " + errorThrown) }
});
}
I get an error in the console saying "Uncaught ReferenceError: e is not defined" The button I am clicking has the name "sendtxt". I made sure it has function(e) on it
<script type="text/javascript">
$(document).ready(function() {
$('input[name="sendtxt"]').click(function(e) {
sendText();
});
});
/************ FUNCTIONS ******************/
function sendText() {
e.preventDefault();
var phonenum = $('input[name="phonenum"]').val();
var provider = $('select[name="provider"]').val();
$.ajax({
type: 'POST',
data: {
provider: provider,
phonenum: phonenum
},
url: 'send.php',
success: function(data) {
console.log('Success');
},
error: function(xhr, err) {
console.log("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
console.log("responseText: " + xhr.responseText);
}
});
};
You're not passing on e.
$(document).ready(function() {
$('input[name="sendtxt"]').click(function(e) {
sendText(e); // <<<
});
});
/************ FUNCTIONS ******************/
function sendText(e) { // <<<
e.preventDefault();
}
But really, that's easier written as:
$(function() {
$('input[name="sendtxt"]').click(sendText);
});
/************ FUNCTIONS ******************/
function sendText(e) {
e.preventDefault();
}
jQuery event handlers expect a function, and sendText is a function. No need to wrap it in another function.
I am trying to load soundcloud likes (used to be favorites), but I am not getting any results from the ajax query.
This is the url I am trying to load: http://soundcloud.com/gazebo-fm/likes
function soundCloudTrackData(linkUrl) {
var url = soundCloudApiUrl(linkUrl, soundcloudApiKey);
$.ajax({
url: url,
dataType: 'jsonp',
cache: false
}).done(function( data ) {
console.log(data);
}).fail(function(jqXHR, textStatus, errorThrown) {
alert('Soundcloud process error: ' + jqXHR.responseText);
});
}
function soundCloudApiUrl(url, soundcloudApiKey) {
var useSandBox = false;
var domain = useSandBox ? 'sandbox-soundcloud.com' : 'soundcloud.com'
return (/api\./.test(url) ? url + '?' : 'http://api.' + domain +'/resolve?url=' + url + '&') + 'format=json&consumer_key=' + apiKey +'&callback=?';
};
change the url to http://soundcloud.com/gazebo-fm/favorites
/likes is used in new soundcloud's api, which is not yet documented.
I'm trying to use the Instagram API and I'm making AJAX requests in a do-while loop until the next_url is null. All I want this code to do is to fetch all the followers by making continuous requests until it's done. What is wrong in this code?
When I remove the do-while loop it doesn't gives me an error, but as soon as a I use the AJAX request within a loop, it never stops. Clearly the $next_url string is not changing to the newly fetched next_url - why? What is wrong?
$(document).ready(function(e) {
$('#fetch_followers').click(function(e) {
var $next_url = 'https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100';
var $access_token = '{access-token}';
var $is_busy = false;
var $count = 0;
do {
while($is_busy) {}
$.ajax({
method: "GET",
url: $next_url,
dataType: "jsonp",
jsonp : "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$is_busy = true;
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
$next_url = data.pagination.next_url;
},
error: function(jqXHR, textStatus, errorThrown) {
$is_busy = true;
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
},
complete: function() {
++$count;
$is_busy = false;
}
});
} while($next_url !== '' || $count <= 50);
});
});
After I failed in my logic, I added the $count variable that can break the do-while loop, because the do-while loop was running infinitely. After adding it, it still runs infinitely, and I have no idea why.
Have the function call itself in the ajax success callback with the new url as a parameter:
$(document).ready(function() {
$('#fetch_followers').click(function() {
var $access_token = '{access-token}';
pollInstagram('https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100');
});
});
function pollInstagram(next_url, count) {
$.ajax({
method: "GET",
url: next_url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
// If the next url is not null or blank:
if( data.pagination.next_url && count <=50 ) {
pollInstagram(data.pagination.next_url, ++count);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
}
});
}
I am in the process of learning how to convert MVC Ajax to jquery ajax so I can do more.
This is the old ajax, I took out the loading stuff
#Ajax.ActionLink("Update Tweets", "Index", "Home",
new AjaxOptions
{
UpdateTargetId = "TweetBox",
InsertionMode = InsertionMode.InsertBefore,
HttpMethod = "Get",
})
I need to convert this to jquery ajax. It seems to be working lets see the code
<script>
$(document).ready(function () {
$("#StartLabel").click(function (e) {
$.ajax({
type: "Get",
url: '/Home/Index',
// data: "X-Requested-With=XMLHttpRequest",
// contentType: "application/text; charset=utf-8",
dataType: "text",
async: true,
// cache: false,
success: function (data) {
$('#TweetBox').prepend(data);
alert('Load was performed.');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
complete: function (resp) {
alert(resp.getAllResponseHeaders());
}
});
});
});
</script>
In the microsoft ajax it sets XML Request in the headers. Do I need to add that too? I am just paging my controller that performs a query to twitter and appends the data to the top.
I am using fiddler to see how the requests are different but the results are the same.
I also noticed if i put the text in the data: object its puts it in the header. i dont think that is right by any means.
You could define a normal anchor:
#Html.ActionLink("Update Tweets", "Index", "Home", null, new { id = "mylink" })
And then unobtrusively AJAXify it:
$(document).ready(function () {
$("#mylink").click(function (e) {
$.ajax({
type: "GET",
url: this.href,
success: function (data) {
$('#TweetBox').prepend(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
complete: function (resp) {
alert(resp.getAllResponseHeaders());
}
});
return false;
});
});
Notice that I return false from the click handler in order to cancel the default action. Also notice that I am using the anchor's href property instead of hardcoding it.
The 2 AJAX requests should be identical.
Here is simple example using Ajax with Jason data
// Post JSON data
[HttpPost]
public JsonResult JsonFullName(string fname, string lastname)
{
var data = "{ \"fname\" : \"" + fname + " \" , \"lastname\" : \"" + lastname + "\" }";
return Json(data, JsonRequestBehavior.AllowGet);
}
in the view add a reference to the query as following
#section Scripts{
<script src="~/Scripts/modernizr-2.6.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.intellisense.js"></script>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
}
in the view add the js
note: (jsonGetfullname).on is a button
<script type="text/javascript">
$("#jsonGetfullname").on("click", function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "#(Url.Action("JsonFullName", "Home"))",
data: "{ \"fname\" : \"modey\" , \"lastname\" : \"sayed\" }",
dataType: "json",
success: function (data) {
var res = $.parseJSON(data);
$("#myform").html("<h3>Json data: <h3>" + res.fname + ", " + res.lastname)
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
})
});
</script>
you can also use (POST\GET) as following:
[HttpPost]
public string Contact(string message)
{
return "<h1>Hi,</h1>we got your message, <br />" + message + " <br />Thanks a lot";
}
in the view add the js
note: (send).on is a button
$("#send").on("click", function () {
$.post('', { message: $('#msg').val() })
.done(function (response) {
setTimeout(function () { $("#myform").html(response) }, 2000);
})
.error(function () { alert('Error') })
.success(function () { alert('OK') })
return false;
});