Multiple form submission - javascript

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();
}
});
}
}

Related

Ajax post formdata net::ERR_CONNECTION_RESET

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...

rerturning response of an ajax post

i am trying to check if an email exists in the db but the function doesn't return a value.
This is the code:
function checkemail(email)
{
var returnVal = "";
if (email.indexOf("#") != -1 && email.indexOf(".") != -1)
{
$.post( "registreren.php?email=" + email, function( response ) {
if(response == 1) { returnVal = 1; }
if(response == 2) { returnVal = 2; }
});
}
else
{
returnVal = 3;
}//email
return returnVal;
}
EDIT: email is send as a string
I short, You can not return values from ajax calls as it is asynchronous by nature, the statement return value executes before
To address such cases, use callback, a function accepted as argument and which is executed when response is been received (when asynchronous action is completed).
Try this:
function checkemail(email, callback) {
var returnVal = "";
if (email.indexOf("#") != -1 && email.indexOf(".") != -1) {
$.post("registreren.php?email=" + email, function(response) {
callback(response);
});
} else {
callback(3);
}
}
checkemail('abc#xyz.com', function(val) {
alert(val);
});
checkemail('INVALID_EMAIL', function(val) {
alert(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Can you use something simple like below
$.ajax({
url: 'registreren.php',
type: 'post',
dataType: "json",
data: {'email': email},
success: function (response) {
if (response == 1)
{
returnVal = 1;
}
else
{
returnVal = 3;
}
}
});
instead of
$.post( "registreren.php?email=" + email, function( response ) {
if(response == 1) { returnVal = 1; }
if(response == 2) { returnVal = 2; }
});

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

Return value false to stop ajax call?

var filterval = filterlist();
if (filterval) {
$.ajax({
type: "POST",
url: "filt.php",
data: main_string,
cache: false,
dataType:'json',
success: function(data) {}
});
}
filterlist() {
var fprice = $('input[name="fprice"]').val();
var lprice = $('input[name="lprice"]').val();
if (fprice >= lprice) {
alert("Value Wrong");
return false;
}
else if (fprice == "" || lprice == "") {
alert("price empty");
return false;
}
return fprice + " " + lprice;
}
I expectation is
Filterlist() function value false to AJAX process stop.
Value not false to work on ajax process .
var fprice = parseInt($('input[name="fprice"]').val());
var lprice = parseInt($('input[name="lprice"]').val());
Use parseInt to convert fprice and price into numbers(from strings) and then compairing is possible :)

Select boxes, disabling values based on values in an array

I have a select menu, that gives the user some criteria options that can use to act as a filter on a search, the user can add as many filters as they wish, however at the moment the user can add the same filter more than once.
What I am wanting to do is, when a user selects a filter from the select box, the value gets added into a array, and then that option in the select box is disabled, is this possible with javascript & jquery?
Currently I have the following
Code that creates a new filter select menu
$('select.option').live({
change: function() {
if($(this).val() == 'distance')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/distance',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'height')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/height',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'appearance')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/appearance',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'education')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/education',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'children')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/children',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'smoking')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/smoking',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'drinking')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/drinking',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'politics')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/politics',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'religion')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/religion',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'ethnicity')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/ethnicity',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
else if($(this).val() == 'work')
{
var element = $(this);
$.ajax({
url: site_url + 'ajax/row/work',
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
}
});
as the name of url and selected option is the same you can try this:
$('select.option').on({
change: function() {
var element = $(this).val();
$(this).prop('disabled', true);
$.ajax({
url: site_url + 'ajax/row/' + element,
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
})
Don't know what your HTML looks like, but I would make it look roughly like this:
<select class="option">
<option value="distance" data-path="ajax/row/distance">Distance</option>
<option value="height" data-path="ajax/row/height">Height</option>
...
</select>
Then have the jQuery be (assuming there are multiple selects in one page and a filter can only be applied once per row):
$('select.option').live({
change: function() {
// get selected history or empty array
var selected = $(this).data('selected') || [];
// get selected option
var $element = $(this).find('option:selected');
// if selected option in history, return
if($.inArray($element.val(), selected) return;
// otherwise, add to history and save back into element
selected.push($element.val());
$(this).data('selected', selected);
// query AJAX by using the data- attribute of the option
$.ajax({
url: site_url + $element.data('path'),
success: function(data) {
element.parent().next('td.fillin').html(data);
}
});
}
});

Categories