Sending several JSON requests creates a 500 error - javascript

This JSON post works, but if I start clicking them quickly, they start returning 500 errors. I'm guessing this is because they're not queueing correctly, and they fall apart when they can't go out one by one. Is there a way to queue this in JSON?
Here's my button in HAML :
= f.check_box :has_sticker, :style => 'width: 20px;', :class => "orgs_deals_admin_save"
And here's my jQuery :
$('.orgs_deals_admin_save').live('click', function() {
var button = $(this);
var form = button.closest('form');
var dataString = form.serialize();
$.ajax({
url: form.attr('action') + '.json',
dataType: 'json',
type: 'POST',
data: dataString,
success: function(data) {
}
});
});

This is because per default asynchronous is set to true. If you want them to be processed in the exact same order you sent them, set asynchronous to false.

500 is server error problem code, so i suppose that there is some problem with processing your script on the server side

Related

Not able to reload the div while using jQuery $.ajax()

I am trying to reload a div with id #todos after the data is saved in the database.
I tried using .load() in $.ajax()
$('.todo--checkbox').change(function () {
let value = $(this).data('value');
$.ajax({
url: `/todo/${value}`,
type: 'PUT',
data: { done: this.checked },
success: function (data) {
if (data.success) {
$('#todos').load(location.href + ' #todos');
}
},
});
});
The problem with this, that it is not reloading the page but it is updating the data in database correctly.
I also tried this
$('.todo--checkbox').change(function () {
let value = $(this).data('value');
$.ajax({
url: `/todo/${value}`,
type: 'PUT',
data: { done: this.checked },
success: $('#todos').load(location.href + ' #todos'),
});
});
In this, it is reloading the page as well as updating the data in the database but the problem is that it only reload and update the data at the first request, and after that I need to reload the whole page to update next data.
I tried to check if I am getting any data or not
$('.todo--checkbox').change(function () {
let value = $(this).data('value');
$.ajax({
url: `/todo/${value}`,
type: 'PUT',
data: { done: this.checked },
success: function (data) {
console.log(data);
},
});
});
It returned nothing, but my data in the mongoDB compass is changing.
I already read this articles so, please don't mark this question as duplicate.
Refresh/reload the content in Div using jquery/ajax
Refresh Part of Page (div)
refresh div with jquery
reload div after ajax request
I suggest you checking requests between your page and the server in the Network tab of browser's Development Console (F12).
Make sure you see PUT request going out to the server to update todo
Make sure that response you receive looks like { success: true } otherwise the following piece of code won't be triggered
if (data.success) {
$('#todos').load(location.href + ' #todos');
}
Make sure you see GET request going out to the server to pull '#todos' asynchronously.
If you don't see request #3 try the following:
replace location.href with window.location.href
try reloading it manually via console (for Chrome, F12 -> Console tab -> paste $('#todos').load(location.href + ' #todos') and hit Enter). That way you are going to skip first ajax request and just will check whether '#todo' section is loadable/reloadable.
I think it’s a cache problem. Try it like this
$('.todo--checkbox').change(function () {
let value = $(this).data('value');
$.ajax({
url: '/todo/${value}?t=202103010001',
type: 'PUT',
data: { done: this.checked },
success: $('#todos').load(location.href + ' #todos'),
});
});
t=202103010001 Set to a random number

Render rails fields_for through ajax call

I have an AJAX call:
$('#enrollment_members').change(function(){
var memberNumber = $(this);
$.ajax({type: 'GET',
url: $(this).href,
type: "get",
data: { members: memberNumber.val() },
error: function(){ alert("There was a problem, please try again.") }
});
return false;
console.log(data);
});
through which I send params[:members] into a new method.
I wanna do something like this:
def new
#enrollment = Enrollment.new
params[:members] ? params[:members].to_i.times { #enrollment.atendees.build } : #enrollment.atendees.build
respond_to do |format|
format.js
end
end
I need this value in order to know how many fields_for to build.
But this being in the new action, how can I update the content of the new view after inputting a value in the members input field?
From that ternary, #enrollment.atendees contains 4 objects.
My new.js.erb :
$("#contact-wrap").html("<%= j render(:partial => 'enrollments/form') %>");
The xhr response contains 4 fields_for forms.
Is the object #enrollment_members the input value you are trying to pass to the controller?
if so, try this:
$('#enrollment_members').change(function(){
var memberNumber = $(this);
$.ajax({type: 'GET',
url: $(this).href,
type: "get",
data: { members: memberNumber.serialize() }, //CHANGE
error: function(){
alert("There was a problem, please try again.")
}
});
return false;
Hmm are you really sure you need a custom made solution for this ? The behavior of dynamically adding/removing children in fields_for is already adressed by several gems like nested_form (no longer maintained) or cocoon (more promising)
I'd suggest to actually reuse their library even if you need to tweak it your way. Because doing an AJAX request is completely pointless. Your AJAX is a GET request that will always do the same thing, unless you have a custom atendees.build which will do weird things for successive calls (like incrementing a global counter somewhere).
Those gems I mentionned above will actually save the HTML fields to generate in a "template" (stored locally in HTML or JS), and just call this template when you want to add a new field.
I got it working by modifying the ajax call:
$('#enrollment_members').change(function(){
var memberNumber = $(this);
$.ajax({type: 'GET',
url: $(this).href,
type: "get",
dataType : "html",
data: { members: memberNumber.val() },
success: function( data ) {
var result = $('<div />').append(data).find('#contact-wrap').html();
$('#contact-wrap').html(result);
$('#atendees-wrap').show();
},
error: function( xhr, status ) {
alert( "Sorry, there was a problem!" );
}
});
return false;
});

Adding Spinner Function inside Jquery onclick function

I have the following code.
----HTML Part---
<div id="Optimize" class="Div"> Optimize </div>
----Jquery Part---
$('#Optimize').click(function()
{
var form_data = new FormData();
form_data.append('action',"Opt");
var perlURL= "$code";
$.ajax({
url: perlURL,
data: form_data,
type: 'post',
datatype: "script",
success: function(result) {
},
});
});
Once the user clicks on Optimization, the following jquery code will execute and display results to user. Now i need to insert a Spinner whenever user clicks Optimization to show that data is loading. Once data gets loaded, spinner should stop. So i have the two functions. If i insert those 2 functions, the Jquery code will look like this.
$('#Optimize').click(function()
{
startSpin(); // ------------------------START SPIN HERE----------------
var form_data = new FormData();
form_data.append('action',"Opt");
var perlURL= "$this_code";
$.ajax({
url: perlURL,
data: form_data,
type: 'post',
datatype: "script",
success: function(result) {
stopSpin(); // --------------STOP SPIN HERE --------------
},
});
This code should work as expected. i.e. spinner should start as soon as user clicks on "Optimize". but it doesnot start. i get a feeling that it straight away performs execution in asynchronous manner.
How can i ensure that the user executes startSpin(); first and then the later part of the function ?
I have read about promise() and have tried various ways to perform both functions simultaneously. but couldnt succeed.
This will surely help someone. I tried using the bind function in jquery and tried to bind both the functions to the onclick event. it was unsuccessful.
However after several retries, i thought of using the jquery function inside a javascript function. So now both the functions are plain javascript functions. I did the following.
-----------HTML CODE-------------
----------START SPIN HERE------------
<div class="Div" onclick="startSpin();setTimeout(function() { runopt(); }, 100); " > Run Optimization </div>
-----------SCRIPT CODE-------------
<script type="text/javascript">
function runopt() {
//$('#Optimize').click(function()
// {
var form_data = new FormData();
form_data.append('action',"Opt");
var perlURL= "$code";
$.ajax({
url: perlURL,
data: form_data,
type: 'post',
datatype: "script",
success: function(result) {
},
});
stopSpin(); // -----------------STOP SPIN HERE -----------------
// });
}
Commented out values in the script means earlier code. I have used both the functions at html side onclick and delayed the second function by 100 msec. it did the trick. the first function was allowed to run and then the second function { runopt() } was run.

pass data($post) to php file using javascript without callback

I need to pass data from HTML page to PHP page But without data callback ....
i'm used two method but One of them did not succeed
1)
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x },
success: function(data)
{
alert("success! X:" + data);
}
});
2)
$.post("getClassStudent.php",
{
},
function(data){
$("#div_id.php").html(data);
}
);
as i can understand, you just want to send info to a php script and don't need the response, is that right?
try this
$.post("phpexample.php", {voteid:x});
or simply remove the "succes" function from the equation if you feel more confortable using $.ajax instead of $.post
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x }
});
your fisrt example is correct, the second is not well formed.
more info:
http://api.jquery.com/jquery.post/
EDIT: to help you some more :)
<button type="button" id="element-id">click</button>
<button type="button" class="class-name">Click</button>
$(document).ready(function(){
//if you are marking ans element by class use '.class-name'
$(".class-name").click(function(){
$.post("getClassStudent.php");
});
//if marking by id element use '#id-name'
$("#element-id").click(function(){
$.post("getClassStudent.php");
});
});
be carefful with the markings, for debuggin try to use "console.log()" or "alert()" so you can see where is the problem and where the code crushes.
var formData = {
'voteid' : 'x',
};
$.ajax({
type : 'POST',
url : 'phpexample.php',
data : formData, // our data object
dataType : 'json',
encode : true
}).done(function(data) {
console.log(data);
});

AJAX will post to originating page but not another

I have a script that submits multiple forms using AJAX. It will post the data successfully if the url used is the originating page, but it will not post the data to another page (the page I use for processing).
Can anyone tell me why this is happening?
/* AJAX for edit */
var submitForms = [
document.forms["editRow"],
document.forms["editRow2"],
document.forms["editRow3"],
document.forms["editRow4"],
document.forms["editRow5"],
document.forms["editRow6"],
document.forms["editRow7"],
document.forms["editRow8"]
]
$('.submitEdit').on('click', function() {
var editRow = $(submitForms).serializeArray();
$.ajax({
type: 'POST',
url: "IRCprocessinventory.php",
data: editRow,
cache: false,
success: function(result){
$('body').html(result);
} //end result
}); // end ajax
}); // end click

Categories

Resources