Ajax post formdata net::ERR_CONNECTION_RESET - javascript

I have 2 similar JS functions:
1)
$(area).on('click','#copy',function (e) {
//var images=[];
e.preventDefault();
var $this=$(this);
var $gal=$this.closest('.gal_insertion_new');
var id=$gal.attr('gal_id');
var $copy=$gal.find("#copy");
$copy.attr("disabled", true);
var copy_to=$gal.find('#copy_to').val();
var row_paste=$gal.find('#row_copy_to');
var formData=new FormData();
var row_p_l=row_paste.length;
var row_p_v=row_paste.val();
console.log(row_p_v);
if (copy_to=='') {
alert('Заполните id галереи');
return;
}
formData.append('gal_id',id);
if ($gal.find('input:checked').length<1){
alert('Выберите хотябы одну картинку');
return;
}
$.each($gal.find('input:checked'),function (i,item) {
formData.append(i,$(item).attr('image_id'));
});
formData.append('what','copy_images');
formData.append('where',copy_to);
if (row_p_l>0) {
if (row_p_v==''){
alert('Заполните номер ряда');
return;
}
formData.append('where_row',row_p_v);
}
$.ajax({
type:'post',
data:formData,
cache:false,
contentType: false,
processData: false
}).done(function (response) {
console.log(response);
//alert(response);
if (response[0]==0) {
alert(response[1]);
} else if (response[0]==1) {
alert(response[1]);
} else if (response[0]==2) {
alert(response[1]);
} else {
if ($('div[gal_id=' + copy_to + ']').length > 0) {
if (row_p_l > 0) {
response.forEach(function (item,i) {
$('.row_item_img_preview[image_id=' + item['id'] + ']').attr('src', item['path']);
});
} else {
$('.img_previews[gallery_id=' + copy_to + ']').append(response);
}
alert('Скопировано');
}
}
$copy.attr("disabled", false);
});
});
2)
$(area).on('click','#delete_selected_images',function (e) {
e.preventDefault();
console.log('delete');
var $this=$(this);
//$this.attr("disabled", true);
var $gal=$this.closest('.gal_insertion_new');
var id=$gal.attr('gal_id');
var formData=new FormData();
//console.log(row_p_v);
formData.append('gal_id',id);
if ($gal.find('input:checked').length<1){
alert('Выберите хотябы одну картинку');
return;
}
$.each($gal.find('input:checked'),function (i,item) {
formData.append(i,$(item).attr('image_id'));
console.log(item);
});
formData.append('what','delete_images');
for (var pair of formData.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
$.ajax({
type:'post',
data:formData,
cache:false,
contentType: false,
processData: false
}).done(function (response) {
console.log('delete2');
/*
console.log(response);
//alert(response);
$.each($gal.find('input:checked'),function (i,item) {
$(item).remove();
});
*/
$this.attr("disabled", false);
});
});
The first one works perfect, but the second one gives me net::ERR_CONNECTION_RESET error.
I'm using laravel, PHP 7.0.1, currently running on OpenServer.
The use of debugger gives nothing, but the understanding that the error is somewhere in the framework, or in my script.
Using json is not an option, cause of my PHP code...

Related

Not able to check the empty data returned from view

I am working on Infinite scrolling.
Here is the code in js
$('.workspace-activity .modal-body').scroll(function() {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight)
{
loadResults(base + 'co8/workspace/activityLogPagination');
}
});
function loadResults(url) {
start = parseInt($('.modal-body .acti-count').length);
var id = $(".single-workspace").attr("data-id");
$.ajax({
url: url,
type: "POST",
data: "start=" + start + "&limit=10&type=workspace&id=" + id,
success: function(data) {
if (!data) {
noData = '<h5 class="no-data">No more data</h5>';
$('.workspace-activity .modal-body').append(noData);
} else {
$('.workspace-activity .modal-body').append(data);
}
}
});
};
The problem is with !data.
The data returned is empty but the if statement executes the else statement,
Is the condition checking correct?
The problem might exists with the blank spaces
!$.trim(data) will remove the blank spaces
The updated javascript function is
function loadResults(url) {
start = parseInt($('.modal-body .acti-count').length);
var id = $(".single-workspace").attr("data-id");
$.ajax({
url: url,
type: "POST",
data: "start=" + start + "&limit=10&type=workspace&id=" + id,
success: function(data) {
if (!$.trim(data)) {
noData = '<h5 class="no-data">No more data</h5>';
$('.workspace-activity .modal-body').append(noData);
} else {
$('.workspace-activity .modal-body').append(data);
}
}
});
};

JavaScript callback function when working withing a loop

This is what the code below does:
Goes to a table in a database and retrieves some search criteria I will send to Google API (the PHP file is getSearchSon.php)
After having the results, I want to loop around it, call the Google API (searchCriteriasFuc) and store the results in an array
The last part of the code is doing an update to two different tables with the results returned from Google API (updateSearchDb.php)
In my code, I am using setTimeout in a few occasions which I don't like. Instead of using setTimeout, I would like to properly use callback functions in a more efficient way (This might be the cause of my problem) What is the best way of me doing that?
$(document).ready(function() {
$.ajax({
url: 'getSearchSon.php',
type: 'POST',
async: true,
dataType: 'Text',
/*data: { }, */
error: function(a, b, c) { alert(a+b+c); }
}).done(function(data) {
if(data != "connection")
{
var dataSent = data.split("|");
var search_criterias = JSON.parse(dataSent[0]);
var date_length = dataSent[1];
var divison_factor = dataSent[2];
var length = search_criterias.length;
var arrXhr = [];
var totalResultsArr = [];
var helperFunc = function(arrayIndex)
{
return function()
{
var totalResults = 0;
if (arrXhr[arrayIndex].readyState === 4 && arrXhr[arrayIndex].status == 200)
{
totalResults = JSON.parse(arrXhr[arrayIndex].responseText).queries.nextPage[0].totalResults;
totalResultsArr.push(totalResults);
}
}
}
var searchCriteriasFuc = function getTotalResults(searchParam, callback)
{
var searchParamLength = searchParam.length;
var url = "";
for(var i=0;i<searchParamLength;i++)
{
url = "https://www.googleapis.com/customsearch/v1?q=" + searchParam[i] + "&cx=005894674626506192190:j1zrf-as6vg&key=AIzaSyCanPMUPsyt3mXQd2GOhMZgD4l472jcDNM&dateRestrict=" + date_length;
arrXhr[i] = new XMLHttpRequest();
arrXhr[i].open("GET", url, true);
arrXhr[i].send();
arrXhr[i].onreadystatechange = helperFunc(i);
}
setTimeout(function()
{
if (typeof callback == "function") callback.apply(totalResultsArr);
}, 4000);
return searchParam;
}
function callbackFunction()
{
var results_arr = this.sort();
var countResultsArr = JSON.stringify(results_arr);
$.ajax({
url: 'updateSearchDb.php',
type: 'POST',
async: true,
dataType: 'Text',
data: { 'countResultsArr': countResultsArr },
error: function(a, b, c) { alert(a+b+c); }
}).done(function(data) {
var resultsDiv = document.getElementById("search");
if(data == "NORECORD") resultsDiv.innerHTML = 'Updated failed. There was a problem with the database';
else resultsDiv.innerHTML = 'Update was successful';
}); //end second ajax call
}
//llamando funcion principal
var arrSearchCriterias = searchCriteriasFuc(search_criterias, callbackFunction);
}
else
{
alert("Problem with MySQL connection.");
}
}); // end ajax
});
How you did it in 2015
Callbacks are things of the past. Nowadays you represent result values of asynchronous tasks with Promises. Here is some untested code:
$(document).ready(function() {
$.ajax({
url: 'getSearchSon.php',
type: 'POST',
async: true,
dataType: 'text'
/*data: { }, */
}).then(function(data) {
if (data == 'connection') {
alert("Problem with MySQL connection.");
} else {
var dataSent = data.split("|");
var search_criterias = JSON.parse(dataSent[0]);
var date_length = dataSent[1];
var divison_factor = dataSent[2];
return Promise.all(search_criterias.map(function(criteria) {
return $.ajax({
url: "https://www.googleapis.com/customsearch/v1"
+ "?q=" + criteria
+ "&cx=005894674626506192190:j1zrf-as6vg"
+ "&key=AIzaSyCanPMUPsyt3mXQd2GOhMZgD4l472jcDNM"
+ "&dateRestrict=" + date_length,
type: 'GET'
});
})).then(function(totalResultsArr) {
totalResultsArr.sort();
var countResultsArr = JSON.stringify(totalResultsArr);
return $.ajax({
url: 'updateSearchDb.php',
type: 'POST',
async: true,
dataType: 'text',
data: { 'countResultsArr': countResultsArr },
error: function(a, b, c) { alert(a+b+c); }
});
}).then(function(data) {
var resultsDiv = document.getElementById("search");
if(data == "NORECORD") {
resultsDiv.innerHTML = 'Updated failed. There was a problem with the database';
} else {
resultsDiv.innerHTML = 'Update was successful';
}
});
}
}).then(null, function() {
alert('Some unexpected error occured: ' + e);
});
});
This is how you do it in 2016 (ES7)
You can just use async/await.
$(document).ready(async() => {
try {
var data = await $.ajax({
url: 'getSearchSon.php',
type: 'POST',
async: true,
dataType: 'text'
/*data: { }, */
});
if (data == 'connection') {
alert("Problem with MySQL connection.");
} else {
var dataSent = data.split("|");
var search_criterias = JSON.parse(dataSent[0]);
var date_length = dataSent[1];
var divison_factor = dataSent[2];
var totalResultsArr = await Promise.all(
search_criterias.map(criteria => $.ajax({
url: "https://www.googleapis.com/customsearch/v1"
+ "?q=" + criteria
+ "&cx=005894674626506192190:j1zrf-as6vg"
+ "&key=AIzaSyCanPMUPsyt3mXQd2GOhMZgD4l472jcDNM"
+ "&dateRestrict=" + date_length,
type: 'GET'
}))
);
totalResultsArr.sort();
var countResultsArr = JSON.stringify(totalResultsArr);
var data2 = await $.ajax({
url: 'updateSearchDb.php',
type: 'POST',
async: true,
dataType: 'text',
data: { 'countResultsArr': countResultsArr },
error: function(a, b, c) { alert(a+b+c); }
});
if(data2 == "NORECORD") {
resultsDiv.innerHTML = 'Updated failed. There was a problem with the database';
} else {
resultsDiv.innerHTML = 'Update was successful';
}
}
} catch(e) {
alert('Some unexpected error occured: ' + e);
}
});
UPDATE 2016
Unfortunately the async/await proposal didn't make it to the ES7 specification ultimately, so it is still non-standard.
You could reformat your getTotalResults function in the following matter, it would then search rather sequential, but it should also do the trick in returning your results with an extra callback.
'use strict';
function getTotalResults(searchParam, callback) {
var url = "https://www.googleapis.com/customsearch/v1?q={param}&cx=005894674626506192190:j1zrf-as6vg&key=AIzaSyCanPMUPsyt3mXQd2GOhMZgD4l472jcDNM&dateRestrict=" + (new Date()).getTime(),
i = 0,
len = searchParam.length,
results = [],
req, nextRequest = function() {
console.log('received results for "' + searchParam[i] + '"');
if (++i < len) {
completeRequest(url.replace('{param}', searchParam[i]), results, nextRequest);
} else {
callback(results);
}
};
completeRequest(url.replace('{param}', searchParam[0]), results, nextRequest);
}
function completeRequest(url, resultArr, completedCallback) {
var req = new XMLHttpRequest();
req.open("GET", url, true);
req.onreadystatechange = function() {
if (this.readyState === 4 && this.status == 200) {
var totalResults = JSON.parse(this.responseText).queries.nextPage[0].totalResults;
resultArr.push(totalResults);
completedCallback();
}
};
req.send();
}
getTotalResults(['ford', 'volkswagen', 'citroen', 'renault', 'chrysler', 'dacia'], function(searchResults) {
console.log(searchResults.length + ' results found!', searchResults);
});
However, since you already use JQuery in your code, you could also construct all the requests, and then use the JQuery.when functionality, as explained in this question
Wait until all jQuery Ajax requests are done?
To get the callback execute after google calls are finished you could change:
var requestCounter = 0;
var helperFunc = function(arrayIndex)
{
return function()
{
if (arrXhr[arrayIndex].readyState === 4 && arrXhr[arrayIndex].status == 200)
{
requestCounter++;
totalResults = JSON.parse(arrXhr[arrayIndex].responseText).queries.nextPage[0].totalResults;
totalResultsArr.push(totalResults);
if (requestCounter === search_criterias.length) {
callbackFunction.apply(totalResultsArr);
}
}
}
}
then remove the setTimeout on searchCreteriaFuc.
Consider using promises and Promise.all to get all much cleaner :D

javascript formatting

I have a piece of code that seems to have a problem. I've tried JSLint and other tools to see where I might have a missing delimiter. Eclipse doesn't show me anything either. In Firebug, the complete block of code shows as disabled line numbers like comment lines do. Anyone know of a good tool? I used ctrl+K to indent the code I pasted below.
$(document).ready(function() {
$('.startover').live('click', function() {
var ReInitAnswer = confirm('Are you sure you want TO start over FROM SCRATCH?');
if (ReInitAnswer){
return true;
}
ELSE {
alert('canceled');
return false;
}
});
$('.notdupe').live('click', function(e) {
alert("indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"));
$.ajax({ type: "POST",
url: "cfc/basic.cfc?method=SetNotDupe",
data: "indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"),
error: function (xhr, textStatus, errorThrown){
// show error alert(errorThrown);
}
});
});
$('.alphabet').live('click', function(l) {
SelectedLetter = $(l.target).val();
$(".alphabet").each(function(i){
var CheckLetter = $(this).val();
if (CheckLetter == SelectedLetter){
$(this).css("background-color", "yellow");
$('.NameBeginsWith').val(SelectedLetter);
} ELSE {
$(this).css("background-color", "");
}
});
$('.Reinit').attr('value', SelectedLetter);
$('.Reinit').trigger ('click');
});
$(".alphabet").hover(function () {
var _$this = $(this);
var usercount = 0;
$.ajax({ type: "POST",
url: "scribble.cfc?method=CountUsersByLetter&returnformat=json",
data: "nbw=" + $(this.target).val(),
datatype: "html",
success: function(res){
usercount = eval("(" + res + ")").DATA[0][0];
_$this.append($("<span> (" + usercount +")</span>"));
},
error: function (xhr, textStatus, errorThrown){
console.log('errorThrown');
}
});
},
function () {
$(this).find("span:last").remove();
}
);
});
It's really difficult to tell what you're asking, but if you mean it's formatted wrong, try http://jsbeautifier.org/ for better formatting. Here's that code cleaned up (including the incorrect casing of else):
$(document).ready(function () {
$('.startover').live('click', function() {
var ReInitAnswer = confirm('Are you sure you want TO start over FROM SCRATCH?');
if(ReInitAnswer) {
return true;
} else {
alert('canceled');
return false;
}
});
$('.notdupe').live('click', function(e) {
alert("indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"));
$.ajax({
type: "POST",
url: "cfc/basic.cfc?method=SetNotDupe",
data: "indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"),
error: function (xhr, textStatus, errorThrown) {
// show error alert(errorThrown);
}
});
});
$('.alphabet').live('click', function(l) {
SelectedLetter = $(l.target).val();
$(".alphabet").each(function (i) {
var CheckLetter = $(this).val();
if(CheckLetter == SelectedLetter) {
$(this).css("background-color", "yellow");
$('.NameBeginsWith').val(SelectedLetter);
} else {
$(this).css("background-color", "");
}
});
$('.Reinit').attr('value', SelectedLetter);
$('.Reinit').trigger('click');
});
$(".alphabet").hover(function() {
var _$this = $(this);
var usercount = 0;
$.ajax({
type: "POST",
url: "scribble.cfc?method=CountUsersByLetter&returnformat=json",
data: "nbw=" + $(this.target).val(),
datatype: "html",
success: function(res) {
usercount = eval("(" + res + ")").DATA[0][0];
_$this.append($("<span> (" + usercount + ")</span>"));
},
error: function(xhr, textStatus, errorThrown) {
console.log('errorThrown');
}
});
}, function() {
$(this).find("span:last").remove();
});
});
Javascript is case sensitive.
ELSE must be lowercase.
ELSE must be lowercase
ELSE { // <-- this is bad
alert('canceled');
return false;
}

What makes the entire script block disabled?

When I check this code in Firebug, the entire block is disabled.
<script type="text/javascript">
var usercount = 0;
var nbw = '';
$(document).ready(function () {
$('.alphabet').each(function () {
_$this = $(this);
nbw = $(this).val();
$.ajax({
type: "Get",
url: "cfc/basic.cfc?method=CountUsersByLetter&returnformat=json",
data: "nbw=" + nbw,
datatype: "html",
success: function (response) {
usercount = parseInt(response.substring(0, 10));
$(_$this.target).attr('title', usercount);
},
error: function (xhr, textStatus, errorThrown) {
alert('errorThrown');
}
});
});
$('.StartOver').live('click', function () {
var ReInitAnswer = confirm('Are you sure you want TO DELETE ALL temp dupe records AND start over FROM SCRATCH? \nIt may take a couple OF hours.');
if (ReInitAnswer) {
// submit the form TO BEGIN re-creating the temp table
document.forms["dupeIndivs"].submit();
//return true;
} ELSE {
alert('canceled');
return false;
}
});
$('.notdupe').live('click', function (e) {
alert("indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"));
$.ajax({
type: "POST",
url: "cfc/basic.cfc?method=SetNotDupe",
data: "indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"),
error: function (xhr, textStatus, errorThrown) {
// show error alert(errorThrown);
}
});
});
$('.alphabet').live('click', function (l) {
SelectedLetter = $(l.target).val();
$(".alphabet").each(function (i) {
var CheckLetter = $(this).val();
if (CheckLetter == SelectedLetter) {
$(this).css("background-color", "yellow");
$('.NameBeginsWith').val(SelectedLetter);
} ELSE {
$(this).css("background-color", "");
}
});
$('.Reinit').attr('value', SelectedLetter);
$('.Reinit').trigger('click');
});
</script>
You have to replace all uppercase ELSE with else (JavaScript is case-sensitive).
Add the closing brace and parenthesis at the end of the code, to finish the $(document).ready(function(){ block.
Working code:
<script type="text/javascript">
var usercount = 0;
var nbw = '';
$(document).ready(function () {
$('.alphabet').each(function () {
_$this = $(this);
nbw = $(this).val();
$.ajax({
type: "Get",
url: "cfc/basic.cfc?method=CountUsersByLetter&returnformat=json",
data: "nbw=" + nbw,
datatype: "html",
success: function (response) {
usercount = parseInt(response.substring(0, 10));
$(_$this.target).attr('title', usercount);
},
error: function (xhr, textStatus, errorThrown) {
alert('errorThrown');
}
});
});
$('.StartOver').live('click', function () {
var ReInitAnswer = confirm('Are you sure you want TO DELETE ALL temp dupe records AND start over FROM SCRATCH? \nIt may take a couple OF hours.');
if (ReInitAnswer) {
// submit the form TO BEGIN re-creating the temp table
document.forms["dupeIndivs"].submit();
//return true;
} else { // <------------------------------------ ELSE > else
alert('canceled');
return false;
}
});
$('.notdupe').live('click', function (e) {
alert("indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"));
$.ajax({
type: "POST",
url: "cfc/basic.cfc?method=SetNotDupe",
data: "indivNum=" + $(e.target).val() + "&SetValue=" + $(e.target).is(":checked"),
error: function (xhr, textStatus, errorThrown) {
// show error alert(errorThrown);
}
});
});
$('.alphabet').live('click', function (l) {
SelectedLetter = $(l.target).val();
$(".alphabet").each(function (i) {
var CheckLetter = $(this).val();
if (CheckLetter == SelectedLetter) {
$(this).css("background-color", "yellow");
$('.NameBeginsWith').val(SelectedLetter);
} else { // <------------------------------------ ELSE > else
$(this).css("background-color", "");
}
});
$('.Reinit').attr('value', SelectedLetter);
$('.Reinit').trigger('click');
});
}); // <---------------------------------------------------- Added });
</script>

Multiple form submission

function saveConfig(val)
{
if(val == 1){
document.f1.submit();
document.f4.submit();
}
else if(val == 2){
document.f2.submit();
}
else if(val == 3){
document.f3.submit();
}
document.f0.submit();
}
Hi The above code works well in IE6, IE7, IE8, FF3.0.19, FF3.5.19 and FF3.6.20. However it doesnot work on Firefox versions > 4. Please help me in understanding what was wrong with the above code.
Can try by using
var form1=document.getElementsByName('f1');
form1.submit();
function f0Submit() {
document.f0.submit();
}
function f4Submit() {
var dataString = $('f4').serialize();
new Ajax.Request('url', {
method: 'post',
parameters: dataString,
onSuccess: function(data) {
f0Submit();
}
});
}
function saveConfig(val) {
if(val == 1) {
var dataString = $('f1').serialize();
new Ajax.Request('url', {
method: 'post',
parameters: dataString,
onSuccess: function(data) {
f4Submit();
}
});
}
else if(val == 2){
var dataString = $('f2').serialize();
new Ajax.Request('url', {
method: 'post',
parameters: dataString,
onSuccess: function(data) {
f0Submit();
}
});
}
else if(val == 3){
var dataString = $('f3').serialize();
new Ajax.Request('url', {
method: 'post',
parameters: dataString,
onSuccess: function(data) {
f0Submit();
}
});
}
}

Categories