Posting form values with jQuery ASP.NET Webpages Error - javascript

I am trying to send a form data, converted to JSON, to another page with jQuery, . However, I believe my POST method is not working as I am always getting the error message- which only says "error". Can anyone help me catch the exact error or tinker the code for making it correct?
I have checked that the data is properly getting JSONed (the first alert is showing the correct form data).
$('#submit').click(function () {
var rows = [];
$('#Tinfo tbody tr').each(function () {
var tds = $(this).children('td'); /* taking all the td elements of the current tr */
rows.push({
'sl': tds.eq(0).find('input').val(),
'tname': tds.eq(1).find('input').val(),
'ttype': tds.eq(2).find('select').val(),
'tduration': tds.eq(3).find('input').val()
});
});
rows = JSON.stringify(rows);
alert(rows);
/* Using the post function to send data over to the database handler page */
$.ajax({
type: "POST",
url: "/Insert",
data: rows,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, status) {
alert(status);
},
error: function (xhr, textStatus, error) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
});

I think there is a problem with your URL. It should be:
url: "Webpage/function"
you are just using the function part. See this example:
http://weblogs.asp.net/karan/archive/2010/09/12/calling-server-side-method-using-jquery-ajax.aspx

Related

Uncaught ReferenceError: function is not defined : Can not call my function with onclick button [solved]

I have got the weird errors from browser when I was trying to add individual events to each buttons that I have created in table.
It has never happened before till now. Can someone tell me where is my blind spot? thanks
Here is how I generate the table with callback function from response data:
$("#bulletin .card-body tbody").html("")
$.each(data.content, function(index, item){
var type = $("#bulletin .card-header button").eq(item.type-1).text()
var res =
'<tr>'+
'<td>'+parseInt(index+1)+'</td>'+
'<td>'+item.announcement+'</td>'+
'<td>'+type+'</td>'+
'<td>'+item.announcement+'</td>'+
'<td>'+item.createdTime+'</td>'+
'<td><button class="btn btn-dark" onclick="openBulletinDetails(\'' + item.id + '\')">details</button</td>'+
'</tr>';
$("#bulletin .card-body tbody").append(res)
})
And there you go the callback:
function openBulletinDetails(id){
console.log(id)
}
I can only got this error
Uncaught ReferenceError: openBulletinDetails is not defined
I request the data from restful API using ajax to get that JSON if it helps.
function generateTable(){
// XHR
$.ajax({
url: url,
type: "GET",
dataType: "json",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "bearer " + globalAuthToken);
},
success: function(data) {
// generate the table here....
},
error: function(data) {
alert(data.status);
}
});
}
function openBulletinDetails(id){
console.log(id)
}
Problem solved!!!
The reason why I got this error is because >> I set my external js file as module type. None of logic were wrong. But why is that stopping the onclick events? no clue...if anyone knows the reason, kindly give me some response.

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.

AJAX in WordPress only returns 0

I'm trying to utilize WordPress's admin-ajax feature in order to build a dynamic admin panel option-set for a plugin. Essentially, once an option is selected from a dropdown (select/option menu), PHP functions will sort through and display more dropdown menus that fall under the dropdown above it. I began with a simple return that I was hoping to utilize later down the line, but I can't seem to get the text to print out without running into unidentified issues.
The AJAX I set up puts out a 200 status but the response never builds, and I'm left with 0 as my result. Here's the code:
JS/jQuery built into PHP function ajax-action()
$ = jQuery;
$('#platform').change(function(e) {
var data = {
action: 'action_cb',
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl, data, function(data) {
$('#user_id').val(data);
});
e.preventDefault();
});
PHP functions and add-actions
add_action('wp_ajax_action_cb','action_cb');
add_action('admin_footer','ajax_action');
function action_cb() { $platform = 'test'; echo json_encode($platform); wp_die(); };
My question is: how can I fix this and prevent it from continuing to happen? I'd like to return the actual results and not 0.
As per the wordpress documentation:
https://codex.wordpress.org/AJAX_in_Plugins (Reference "Error Return Values")
A 0 is returned when the Wordpress action does not match a WordPress hook defined with add_action('wp_ajax_(action)',....)
Things to check:
Where are you defining your add_action('wp_ajax_action_cb','action_cb');?
Specifically, what portion of your plugin code?
Are you logged into wordpress? You mentioned the admin area, so I'm assuming so, but if you are not, you must use add_action('wp_ajax_nopriv_{action}', ....)
Additionally, you didn't share the function this is tied to:
add_action('admin_footer','ajax_action');
And lastly, why are you using "json" as the data type? If you are trying to echo straight HTML, change data type to 'html'. Then you can echo directly on to page (or as a value as you are doing). Currently, you are trying to echo a JSON object as a value in the form...
So your code would look like so:
function action_cb() { $platform = 'test'; echo $platform; p_die(); };
...and your AJAX could be:
<script type = "text/javascript">
jQuery.ajax({
url: ajaxurl,
type: 'post',
data: {'action' : 'action_cb'},
success: function (data) {
if (data != '0' && data != '-1') {
{YOUR SUCCESS CODE}
} else {
{ANY ERROR HANDLING}
}
},
dataType: 'html'
});
</script>
Try This:
<script>
$ = jQuery;
$('#platform').change(function(e) {
var data = {
data: {'action' : 'action_cb'},
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl, data, function(data) {
$('#user_id').val(data);
});
e.preventDefault();
});
</script>
Probably you need to add
add_action('wp_ajax_nopriv_action_cb', 'action_cb');
https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
just make small change in your AJAX. I am assuming you're logged in as admin.
replace action in data object with data:"action=action_cb",
var data = {
data:"action=action_cb",
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl,data,function(data){
$('#user_id').val(data);
});
To prevent WP adding zero into response i always using die(); insted of wp_die();
and registering function:
add_action( 'wp_ajax_action_cb', 'action_cb_init' );
add_action( 'wp_ajax_nopriv_action_cb', 'action_cb_init' );
function action_cb_init() {
}
When calling to function with AJAX use action: 'action_cb'
Hope this helps. I have already explained standard way of using ajax in wp.
Wordpress: Passing data to a page using Ajax
Ok, I have been recreating your code now in my own project and noticed that the javascript you shared returned the ajax-object and not the results. So what I come up with is a bit rewriting, but is worked fine when I tried it.
$j = jQuery.noConflict();
$j('#platform').change(function(e) {
$j.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'action_cb',
}
}).done(function( data ) {
// When ajax-request is done.
if(data) {
$j('#user_id').val(data);
} else {
// If 0
}
}).fail(function(XMLHttpRequest, textStatus, errorThrown) {
// If ajax failed
console.log(errorThrown);
});
e.preventDefault();
});
I hope the comments explain good enough how it is working. Note how I'm using $j instead of just $ for the jQuery.noConflict mode.
For those by the "Load More" problem.
Normally "0" is used instead of false.
I found such a solution.
So that 0 does not come. Try this code with false.
PHP
ob_start(); // start the buffer to capture the output of the template
get_template_part('contents/content_general');
$getPosts[] = ob_get_contents(); // pass the output to variable
ob_end_clean(); // clear the buffer
if( $read == $articles->found_posts )
$getPosts[] = false;
JS
if( posts[i] == false )
$(".load_more_button").fadeOut();

How to connect to the Parse Javascript API? (502 error)

I am building a chatroom-type app using the Parse Javascript API. The task is to get some data from Parse, display it, add user input to the messages, and send it right back to parse.
The problem is I am not being able to see the data from parse, and receive a 502 error. I am a bit newer to javascript, so any advice on how to accomplish this, or any mistakes you may see in my code, would be fantastic. I also commented out my code the best I could. Thanks for the help.
Here is my code;
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages')
//fetches data from parse
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success: console.log("Success"),
function message(a) {
my_messages.append('<ul>' + a +'</ul>'); //adds ul 'text' to messages
};
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
function(message){
window.location.reload(1) //refresh every 3 seconds
});
});
});
</script>
you have syntax error in both of your success functions of $.ajax calls. In the first ajax call you have places console.log, which should be inside the success callback. In the second one u haven't even added success: callback.
Try below updated code
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages');
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success:function message(a) {
console.log("Success")
$.each(a,function(i,item){
my_messages.append('<ul>' + item.username +'</ul>'); //adds ul 'text' to messages
});
}
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
success:function(message){
window.location.reload(1) //refresh every 3 seconds
}
});
});
});

Return a set from ajax to JavaScript

I have an ajax call which will return a set<E>. I need to process this set from the JavaScript function from which I call this ajax.
<script type="text/javascript">
function mySr(id){
$.ajax({
type: 'POST',
url: '../controller/action',
data: 'id=' + id,
success: function(data) {
var length= data.length
var size = data.size
alert(data[0]+'----'+length+'--'+size+'----'+data)
},
error: function () {
alert('error')
}
});
</script>
This is the way i used,
The alert will display like this
["37",
"40","80","90"]----22--undefined----[
I understood the data is clearly reached in the script but i don't know how to iterate through it.
How to iterate here?
How to get the length?
How to get each elements?
You need to parse the data. Try putting data = $.parseJSON(data); after the line success: function(data) {
See http://api.jquery.com/jQuery.parseJSON/ for more details.

Categories