Function Statements no name error - javascript

I have the following code:
<script type="text/javascript">
$(document).on("click", "#leftconversation", function(){
var self = this;
var cid = $(this).attr('class'); // getting the user id here
var request = $.ajax({
url: "conversation.php",
type: "POST",
data: { cid: cid },
beforeSend: function(){
self.html("Loading please wait...");
}
});
//WHEN SUCCESS
request.success(function( data ) {
$("#right").html(data); // replace the right div with echoed content from php file
});
});
</script>
However, my console keeps giving me the error: “SyntaxError: Function statements must have a name.”
I can't seem to fix the issue and that’s why the AJAX code isn’t running. Where’s this error coming from?
As per what Todd said, i changed the code to following:
<script type="text/javascript">
$(document).on("click", "#leftconversation", function(){
var self = this;
var cid = $(this).attr('class'); //you are getting the user id here
var request = $.ajax({
url: "conversation.php",
type: "POST",
data: { cid: cid },
beforeSend: function(){
self.html("Loading please wait...");
},
success: function(data) {
$("#right").html(data);
},
error: function(request, err){ console.log('An Error Occured' + err); }
});
});
</script>
It fixed the first error, but now its telling me TypeError: undefined is not a function (evaluating 'self.html("Loading please wait...")')
This is fixed, should have used var self = $(this); instead

as per my comment
$(document).on("click", "#leftconversation", function(){
var $self = $(this);
var cid = $(this).attr('class'); // getting the user id here
var request = $.ajax({
url: "conversation.php",
type: "POST",
data: { cid: cid },
beforeSend: function(){
$self.html("Loading please wait...");
}
});
//WHEN SUCCESS
request.success(function( data ) {
$("#right").html(data); // replace the right div with echoed content from php file
});
});

You can fix your issue without having to use a variable. Just set the context: property of the $.ajax call.
var request = $.ajax({
url: "conversation.php",
type: "POST",
data: { cid: this.className }, // Quicker way to get the class.
context: $(this), // The context in the callback will be the jQuery object.
beforeSend: function() {
// v-- This is now a jQuery object.
this.html("Loading please wait...");
}
});

Your code, as you have posted it, is correct. The error must be coming from elsewhere. That said, wherever the error is, here’s what to look for:
As you likely know, functions can be defined like this:
function greet(name) { /* ... */ }
This works in a statement context. Functions can also be used in an expression context:
[1, 2, 3].forEach(function(item) { alert(item); });
In an expression context, we can omit the name, as we did above, or we can include a name:
[1, 2, 3].forEach(function foo(item) { alert(item); });
However, what we cannot do is have a standalone function declaration without a name. This is an error:
function(name) { /* ... */ }
That is what your (now first) problem was.
“undefined is not a function”
Your updated code has a different problem. When you set self = this, this is a DOM element, not a jQuery object. You later try to use self.html, but DOM elements do not have a html property. If you wish to use jQuery methods, you must convert the element into a jQuery object, either at the point of assignment (self = $(this)) or at the point of use $(self).html.

Related

Why can't I toss post variable to PHP when I cover .ajax with function?

I have 3 files for showing data from myAdmin and it shows no error but after I put function around .ajax, to re-use it, I cannot pass button id to PHP. " Undefined index: btnId"
What seems wrong?
HTML file, written in PHP (below looped in for code)
print"<button class='refresh' data-name='$btnId' id='$btnId'>{$btnId}</button>";
print "<table id='$idForShowNewData' class='showNewData'></table>";
show.js
$(document).ready(function(){
$('.refresh').click(function(){
$(function showTable() {
    $.ajax({
url: "show.php",
type: "POST",
data: {
"btnId": $(this).data("name")
},
success: function(data) {
//more code
},
error: function(xhr,XMLHttpRequest,errorThrown){
//more code
}
});
});
showTable();
});
});
PHP file that get's data from myAdmin. Getting id like below is at the top of the script.
$gotBtnId = $_POST['btnId'];
this in showTable refers to window object and not the button whose data-name you want to send in the request.
If you want showTable to be invoked when the page is loaded and also be registered as a listener for click events to the refresh button, declare it as follows:
const $refreshBtn = $('button.refresh');
function showTable() {
    $.ajax({
url: "show.php",
type: "POST",
data: {
"btnId": $refreshBtn.data("name")
},
success: function(data) {
//more code
},
error: function(xhr,XMLHttpRequest,errorThrown){
//more code
}
});
});
$(function() {
showTable();
$refreshBtn.click(showTable);
});

unable to set result from ajax success to div html in mvc

I have the below code, I'm calling an action and getting a partialviewresult in ajax success.
But I'm unable to set the html to the div-Graph, but I'm getting undefined in alert; alert( $('#div-Graph').html()); The entire html is disappearing...
Any idea on this?
$(document).ready(function () {
$('#ChartTypes').change(function () {
var selectedID = $(this).val();
$.ajax({
url: '/charts/GetChart/4',
type: 'GET',
success: function (result) {
debugger ;
$('#div-Graph').html(result.toString());
alert( $('#div-Graph').html());
}
});
});
});
Kindly let me know if you need any more code parts. Tried a lot for a solution :(
Thanks
Ragesh
You can directly append it to the class/id like this. You can't display the whole div inside the alert box.
success: function (result) {
alert(result);
var res = JSON.stringify(result);
$('#div-Graph').append(res);
}

Jquery - (this) not defined in success block

I use Jquery quite a bit and I must be missing something simple here. I am trying to access this in the success block of this ajax call, but I get a Reference Error: that is not defined inside the success block. Here is the code:
$('body').on('click', '.row', function() {
var $row = $(this);
var id = $row.parent().data().scout;
var requirement_id = $row.data().req;
var req = $.ajax({
url: '/scouts/' + id + '/reqs',
data: {requirement_id: requirement_id },
type: 'PUT'
});
var success = function() {
// that not defined
$row;
};
req.done(success);
});
What am I missing here?

the id of the element won't change in jquery?

i.e.
$("#savenew").live('click', function(e) {
var user=<?php echo $user?>;
$.ajax({
type: "POST",
url: "actions/sub.php",
data:{user: user} ,
success: function(){
$('#savenew').html('<span>Unsubscribe</span>');
$(this).attr('id', 'clean'); // this my problem my problem
}
});
});
the id after the ajax request, is not changing from savenew to clean, but the html is perfectly fine, so i know the ajax request is working. what do u thiunk the problem is?
You just need to save the context (via the context option for $.ajax()) so this still refers to #savenew, like this:
$("#savenew").live('click', function(e) {
var user=<?php echo $user?>;
$.ajax({
context: this, //add this!
type: "POST",
url: "actions/sub.php",
data:{user: user} ,
success: function(){
$(this).attr('id', 'clean').html('<span>Unsubscribe</span>');
}
});
});
Also note that this allows you to chain and clean things up a bit.
$(this) inside success: function(){ does not refer to $('#savenew').
As you do in the line above, you need to reference it by id:
$('#savenew').attr('id', 'clean');

CKEDITOR ajax posts

I am trying to make an admin page using AJAX so when the client updates information in the CKEDITOR it doesn't have to take him to a new page. Getting data from input fields are easy enough using the .val() function, but because textareas are not updated on the fly, I can't use that same function. Heres as far as I got:
// this replaces all textarea tags into CKEDITORS
<script type="text/javascript">
CKEDITOR.replaceAll();
</script>
//this attempts to grab all data from inputs and textareas
$(function() {
$("#submit").click(function() {
var newsTitle = $("#newsTitle").val();
var editNews = CKEDITOR.instances.editNews.getData();
var contactTitle = $("#contactTitle").val();
var editContact = CKEDITOR.instances.editContact.getData();
var linksTitle = $("#linksTitle").val();
var editLinks = CKEDITOR.instances.editLinks.getData();
$.ajax({
type: "POST",
url: "update.php",
data: 'newsTitle='+newsTitle+'&editNews='+editNews+'&contactTitle='+contactTitle+'&editContact='+editContact+'&linksTitle='+linksTitle+'&editLinks='+editLinks,
cache: false,
success: function(){
updated();
}
});
return false;
});
});
the getData() function seemed like it would work because I tested it with alerts and it was grabbing the data from the editors, but once I would try and update, it wouldn't work...
any ideas?
This code replaces the textarea:
<script type="text/javascript">
CKEDITOR.replace( 'TEXTAREA_ID', {
extraPlugins : 'autogrow',
removePlugins : 'resize',
entities : false
});
</script>
In the JS file this is the code and I am using Jquery Validator Plugin:
$(document).ready(function(){
jQuery.validator.messages.required = "";
$("#FormID").validate({
submitHandler: function(){
var ContentFromEditor = CKEDITOR.instances.TEXTAREA_ID.getData();
var dataString = $("#FormID").serialize();
dataString += '&ContentFromEditor='+ContentFromEditor;
$.ajax({
type: "POST",
url: "Yourfile.php",
data: dataString,
cache: false,
success: function(html){
YOU WORK WITH THE RETURN HERE
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.responseText);
}
});
return false;
}
});
});
This is the line that most of the time creates the error:
CKEDITOR.instances.TEXTAREA_ID.getData();
After the instances always comes the ID of the textarea.
I have my own config.js that you can get from the ckeditor website or from the examples.
Tage a look at the CKEditor function/adaptor for jQuery
http://docs.cksource.com/CKEditor_3.x/Developers_Guide/jQuery_Adapter
Because setting and retrieving the editor data is a common operation, the jQuery Adapter also provides the dedicated val() method:
// Get the editor data.
var data = $( 'textarea.editor' ).val();
// Set the editor data.
$( 'textarea.editor' ).val( 'my new content' );
With this code, my problems were solved.
I updated the field running ckeditor to be seen in serialize.
$('#form').find('.class').each(function(index) {
$(this).val(CKEDITOR.instances[$(this).attr('id')].getData());
});

Categories