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.
Related
var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
$checkboxes = $("#list :checkbox");
$checkboxes.on("change", function(){
$checkboxes.each(function(){
checkboxValues[this.id] = this.checked;
});
localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
});
I am using the code above to store the data into local storage.
{"2":false,"3":false,"4":true}
The data stored in the local storage. How can i get only the value 2 or false?
I want to collect the data in the local storage and stored into an array during submit the form.
var items=[];
$.each(checkboxValues, function(key, value) {
if(value===true){
$("#" + key).prop('checked', value);
items.push(key);
}
});
The code seem like got problem during submit which caused integrity constraint duplicate entry when store the data to database. I am using ajax to post the data to server and store the data. Is there anything wrong with my code?
Use the below code to access the checkboxValues object. You need to parse it.
var obj = JSON.parse(localStorage.getItem("checkboxValues"));
To access "2", use obj["2"].
var obj = {"2":false,"3":false,"4":true};
localStorage.setItem('checkboxValues',JSON.stringify(obj));
var storedObject = JSON.parse(localStorage.getItem('checkboxValues'));
console.log(storedObject["2"]);
i have a file locally which has array of objects in my view i need it to be warped as a variable, on viewing the variable that array should be used
i tried this but i dont know its the right way could some one help me
var url = 'proj/array/arrayobject';
console.log(url);
var refreshId = setInterval(function(){
$('div.comment-container').comment({
//here i should call that url and display object one by one with equal intervals
})
}, 1000);
could some one help me
First of all I would suggest to keep that file as JSON file having .json extension. It would make the file purpose more clear.
Secondly, You can use jQuery Ajax's getJSON() method to get data of that file and assign it to your local or global variable like below:
var myGlobalVariable = null;
$.getJSON("proj/array/arrayobject.json", function( data ) {
myGlobalVariable = data;
});
Then, You can use your myGlobalVariable in your code. But, Make sure that you use it once you get data in it. For this you can use callbacks.
For your scenerio, Code will be like below:
var url = null;
function init() {
$.getJSON("proj/array/arrayobject.json", function(data) {
url = data;
MyFunc();
});
}
function MyFunc() {
setInterval(function() {
$('div.comment-container').comment({
// use url here
})
}, 1000);
}
$(function() {
init();
});
I've written a jQuery-AJAX function as follows :
$('#request_form').submit(function(e) {
var form = $(this);
var stud_id = $('#stud_id').val();
var reg_date = $('#reg_date').val();
var formdata = false;
var fileInput = $("#receipt_image")[0];
/*I want to pass values of below variables to the PHP file.*/
var ImgSizeInBytes = fileInput.files[0].size;
var filename = $('input[type=file]').val().split('\\').pop();
var customer_id = $('#customer_id').val();
/*These values need to send to PHP file and access there */
if(window.FormData) {
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
url : 'student_request.php',
type : 'POST',
cache : false,
data : formdata ? formdata : form.serialize(),
contentType : false,
processData : false,
success: function(response) {
var responseObject = $.parseJSON(response);
if(responseObject.error_message) {
if ($(".alert-dismissible")[0]) {
$('.alert-dismissible').remove();
}
var htmlString = "<div class='alert alert-danger alert-dismissible' role='alert'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>"+responseObject.error_message+"</div>";
$(htmlString).insertBefore('div.modal-body #request_form');
} else {
alert("Student successfully registered...!!!");
}
}
});
e.preventDefault();
});
Now I'm able to access the values filled in by user on a form by means of $_POST array in PHP file. But I also want to pass the values I put in comment in my code above to the PHP file.
The values/parameters which I want to send are not part of a form fields. I've manipulated the values of these variables. So they can't come in $_POST array.
My issue is how should I send these values to PHP file and how should I access these values in PHP file?
You should change this: formdata ? formdata : form.serialize()
Store this in a variable and concatenate the values you want to send.
For Example:
var pars = formdata ? formdata : form.serialize();
pars += "&myField1=myValue1&myField2=myValue2"
As #chris said, all you need to do is to concatenate your own hidden variables to post variables. As I see, you are confused about how to use those extra variables in your php file, here's simple example:
var params = formdata ? formdata : form.serialize();
params += "param1=myExtraVar1¶m2=myExtraVar2";
So now you have all variables ready to be sent to your php file, modify your data parameter in ajax call like this:
...data: params,
So far, so good. Let's see the other side (PHP)
<?php
// get the variables you want to treat.
$param1 = $_POST['param1']; // now you have access to this variable from ajax call
// Notice you can display all variables you have in superglobal variable POST
// by dumping it using either var_dump($_POST) or print_r($_POST)
Hope this helps understand better the process, and feel free to comment and I'll get back to you
Another thing I captured and I'd like to share with you is that you can use datatype to JSON instead of casting your returned response, so you can put this code anywhere inside your ajax call:
dataType: "json", // if you put this in last line, omit the comma, otherwise leave as it is
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);
});
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);
};
});
});