I have 8 search filters user can choose. When user clicks on filter it opens options for this filter. When user clicks out, the function hideFilterSearch() is triggered. I have problem about understanding of scope for variable formData (see below).
$(document).ready(function() {
var formData = $("form").serialize();
});
function hideFilterSearch() {
console.log(formData);
$(".filters").hide();
newFormData = $("form").serialize();
if (formData != newFormData) {
//newFormData is sent with ajax and search results are updates
}
formData = $("form").serialize();
}
//show, hide filter changer
$('body').click(function(event) {
if (!$(event.target).closest('.filter').length) {
hideFilterChanger();
};
});
Console log gives me empty string in this case. I tried also to send formData as argument ()hideFilterSearch(formData), but then the problem is formData won't be updated. I am not sure what is the correct way to pass formData to function, but still update it's value inside function when it is changed.
Use global variable.As formData variable in local scope,you can't accesss it in antother function.
Change your code to the following
window.formData = $("form").serialize();
Functions can return values. Pass formData and return the updated one from the function. You can then assign it in hideFilterChanged.
$(document).ready(function(){
var formData = $("form").serialize();
function hideFilterSearch(formData){
console.log(formData);
$(".filters").hide();
newFormData = $("form").serialize();
if(formData!=newFormData){
//newFormData is sent with ajax and search results are updates
}
return $("form").serialize();
}
//show, hide filter changer
$('body').click(function(event) {
if (!$(event.target).closest('.filter').length) {
formData = hideFilterChanger(formData);
};
});
});
Related
I'm sorry in advance, my native language is not English :(
Since in Chrome version 80 the AJAX queries no longer work in the unload event, I require another alternative, I read about Navigator.sendBeacon the problem is that I did not find an example to send multiple data, for example in AJAX have this:
$(window).on('unload', function() {
console.log('ajax unload');
$.ajax({
type: 'POST',
url: 'config/myphpfile.php',
async: false,
data: {
xvar1: var1,
xvar2: var2,
xvar3: 0
},
success: function(data) {
console.log('work!');
}
});
As you can see in this AJAX event, it sent 3 variables to my PHP, and one of them the var2 is an array, how can I pass multiple variables in the same way with the Navigator.sendBeacon function, have you done something similar?
You could use the FormData Object
// URL to send the data to
let url = '/api/my-endpoint';
// Create a new FormData and add a key/value pair
let data = new FormData();
// Append data to FormData object
data.append('xvar1', var1);
data.append('xvar2', var2);
data.append('xvar3', 0);
let result = navigator.sendBeacon(url, data);
if (result) {
console.log('Success!');
} else {
console.log('Failure.');
}
I based this solution from: https://www.smashingmagazine.com/2018/07/logging-activity-web-beacon-api/#using-navigator-sendbeacon
Read more about the FormData Object here:
https://developer.mozilla.org/en-US/docs/Web/API/FormData
Simple script sending form data to a PHP script to be processed. The data in in an assoc array and output to the console shows it is present. Data is passed using a jquery AJAX function, however the PHP script is not receiving array. However, if I hardcode the data into the function, the data is passed.
If have tried setting the AJAX function 'method' to POST and also removing that option. I have tried different formats for the array. Passing the array as part of a hard coded array.
Javascript side
function saveInformation(e) {
var d = []
var f = $(e)[0].id; //Form name
var formData = $('#'+f).serializeArray();
formData.forEach(function(item){
d[item.name] = item.value;
})
console.log('data',d)
$.ajax({
data: d,
url: "TableUpdate.php"
})
.done(function(e) { $('#agentGeneralInfoTitle').text('Agent General Information (Saved)'); console.log(e);})
.fail(function(e) {
alert("save failed\n" + e.responseText); console.log(e);
});
}
The console.log command shows data in variable d. All the data is present and properly formatted.
PHP side
<?
require_once('/var/www/Debugging/ChromePhp.php');
chromePHP::log($_REQUEST,$_POST);
:
:
:
?>
this prints out "[],[]". It complete correctly with a determination that the data is not present.
I expect the data to be passed and the chromePHP::log to show an array with data.
var d should be an object not array.
Arrays have numeric indices only in javascript
Change
var d = []
To
var d = {}
Also using serialize() instead of serializeArray() would make it simpler as you wouldn't need to loop through and create d at all
function saveInformation(e) {
// assuming `e` is form element
var formData = $(e).serialize();
$.ajax({
data: formData ,
url: "TableUpdate.php"
})
.done(function(e) { $('#agentGeneralInfoTitle').text('Agent General Information (Saved)'); console.log(e);})
.fail(function(e) {
alert("save failed\n" + e.responseText); console.log(e);
});
}
I have a page with a list, with a number of checkboxes. When I check the boxes and click submit, I want an AJAX request to take the value of the checkboxes, stick them into an array, send that array to my 'setCourses' method, where I will use the array values to pull data out of the DB and then send that data back to the page as JSON. This is my first time trying AJAX so sorry for any silly mistakes!
The AJAX request seems to work, sending the array to the controller method, but I can't get the success function to return the data I want to send back from the controller. Here is what I have so far:
setCourses Method
public function setCourses(Request $request) {
$courses = $request->get('selectedCourses');
//Here I will use the "$selectedCourses" array above to query the database for specific info,
//but for now I am just trying to get the AJAX to return anything!
return response::json($courses);
}
AJAX to get checkbox values, add to array and send request
$('.submitCourses').on('click', function(){
var selectedCourses = $("input:checkbox[name=courseID]:checked").map(function(){
return $(this).val();
}).get();
console.log(selectedCourses);
$.ajax({
url: 'report-generator/custom/selected',
type: 'GET',
data: { selectedCourses: selectedCourses },
success:function(courses){
console.log(courses);
}
});
});
try this one
to change use helper function instead of facade
return response()->json($courses);
var obj = { selectedCourses: selectedCourses };
$.get('/eport-generator/custom/selected', obj,
function (response) { console.log(response);}
).fail(function () {
console.log("error");
});
I have a form and I have fetch form data inside function.I want to send all
variables having data to be send to next page .Please tell me how to do it
function form_values() {
var jsvar = document.myform1.text_quest.value;
alert(jsvar); // test
$('select[name="dropdwn"]').each(function() {
alert(($(this).val()));
});
var cal = document.getElementById("otherAnswer").value;
alert(cal);
var chk = [];
$(':radio:checked').each(function() {
//alert($(this).val());
chk.push($(this).val());
});
alert(chk);
$('[type=checkbox]:checked').each(function() {
alert($(this).val())
});
} //End of function
you have to use serialize() in jquery.
For example:
url:'your_file.php?'+serialize();
This will send all the form values to that file.
For more details check here
Why not use localStorage to store the values in a json object, and use them in any of your scripts?
For example, in your form_values():
var formData = {};
$('select[name="dropdwn"]').each(function() {
formData.dropdwn = $(this).val();
});
Then on form submit:
localStorage.setItem('formData', JSON.stringify(formData));
Then from another javascript file:
var formData = JSON.parse(localStorage.getItem('formData'));
console.log(formData.dropdwn); // logs your value
Of course, make sure you check if formData exists on localStorage before trying to get a value from it.
Ran into an issue where I need to use GET vs POST on a form method, but GATC cookie data is not being appended to the URL correctly, because the form's data is trumping Google's GATC data (using linkByPost).
I've read up on a potential solution posted here, but seems like an insane amount of work to make GET behave. I also stumbled upon another solution here, but IE doesn't respect anything after the 'anchor' portion of the url.
Anyone have any other ideas? If I can't handle this via JS, I will have to go into the script handling the form action and massage the querystring manually (assuming that GATC data is in $_REQUEST array). FTR, GATC data is not available via the $_REQUEST array, when using get.
For future reference, in case anyone runs into the same issue, this is the solution I implemented. I lifted some code from the answer to this SO post, and combined it with the idea behind this post, where it localizes the GATC data, and adds hidden fields to the form for each one.
Resulting code:
$(document).ready(function() {
$('#formId').submit(function(e) {
try {
e.preventDefault();
var form = this;
if (typeof _gat !== 'undefined') {
_gaq.push(['_linkByPost', this]);
var pageTracker = _gat._getTrackerByName();
var url = pageTracker._getLinkerUrl(form.action);
var match = url.match(/[^=&?]+\s*=\s*[^&#]*/g);
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
$('<input>').attr({
type: 'hidden',
name: name,
value: value
}).appendTo(form);
}
}
setTimeout(function() { form.submit(); }, 400);
} catch (e) { form.submit(); }
});
});
You can use jQuery serialize to get the form's elements, then _getLinkerUrl to append the cross-domain tracking data
$('#formID').submit(function(e) {
var pageTracker = _gat._getTrackerByName();
var url = this.action + '?' + $(this).serialize();
url = pageTracker._getLinkerUrl(url);
if (this.target != '_blank') location.href = url;
else window.open(url);
});