In message variable I am getting the multiple selected, how to store them in array, after this store in database?
<script type="text/javascript">
$(function () {
$('#lstFruits').multiselect({
includeSelectAllOption: true
});
$('#btnSelected').click(function () {
var selected = $("#lstFruits option:selected");
// document.write(selected);
//.var array = string.split(",").val(selected);
var message = "";
selected.each(function () {
message += $(this).val();
// here I am getting the selected ids like 2,4,5 and I
// want to submit all ids in the database.
// While, when I am submitting currently only the last
// id is being submitted.
var vale = [$(this).val()];
//document.write(vale);
$('#second').val(vale);
});
alert(message);
});
});
</script>
How to store all selected values in array and then submit in php page by query?
Try to save the values in array & name of the field whose id is second should be like second[]
<script type="text/javascript">
$(function () {
$('#lstFruits').multiselect({
includeSelectAllOption: true
});
$('#btnSelected').click(function () {
var selected = $("#lstFruits option:selected");
var message = [];
selected.each(function () {
message.push($(this).val());
});
$('#second').val(message);
alert(message);
});
});
</script>
For example, you can submit this to php by ajax. (With GET or POST query)
Another guide about ajax
Example
$.post('yourphpfile.php', {data: JSON.stringify(message)})
.done(function(data) { console.log('success'); })
.fail(function() { console.log('error');
// in youphpfile.php
$_POST['data'] ? yourFunctionToInsert($_POST['method']) : null;
btw, to insert in array in your js file, you can also do:
message[] = $(this).val(); //in the loop
$(function () {
$('#lstFruits').multiselect({
includeSelectAllOption: true
});
//create array variable
var selectedValues = new Array();
$('#btnSelected').click(function () {
var selected = $("#lstFruits option:selected");
selectedValues.push(selected);
//then by use=ing ajax you can send this array
$.ajax({
type: "POST",
data: {info:selectedValues},
url: "page.php",
success: function(msg){
$('.answer').html(msg);
}
});
});
});
You can make array then by useing .push method can store values in array, after that by ajax you can send over PHP page.
Related
I have this div
<div class='additional_comments'>
<input type="text" id='additional_comments_box', maxlength="200"/>
</div>
Which will only sometimes appear on the page if jinja renders it with an if statement.
This is the javascript i have to send an ajax request:
$(document).ready(function() {
var button = $("#send");
$(button).click(function() {
var vals = [];
$("#answers :input").each(function(index) {
vals.push($(this).val());
});
vals = JSON.stringify(vals);
console.log(vals);
var comment = $('#additional_comments_box').val();
var url = window.location.pathname;
$.ajax({
method: "POST",
url: url,
data: {
'vals': vals,
'comment': comment,
},
dataType: 'json',
success: function (data) {
location.href = data.url;//<--Redirect on success
}
});
});
});
As you can see i get the comments div, and I want to add it to data in my ajax request, however if it doesnt exist, how do I stop it being added.
Thanks
You can use .length property to check elements exists based on it populate the object.
//Define object
var data = {};
//Populate vals
data.vals = $("#answers :input").each(function (index) {
return $(this).val();
});
//Check element exists
var cbox = $('#additional_comments_box');
if (cbox.length){
//Define comment
data.comment = cbox.val();
}
$.ajax({
data: JSON.stringify(data)
});
in my index page i sent a request ajax and response is a number.and i set the response to the value of input with hidden type
<input type="hidden" id="Status">
<script src="js/indexPhone.js"></script>
<script>
$(document).ready(function() {
$("#SendPhone").click(function(e) {
var phoneField = $("#PhoneField").val();
var phoneFieldString = "989" + phoneField.substring(0);
$.ajax({
type:'post',
url:'getSMS.php',
data:{'phoneFieldString':phoneFieldString},
success:(function (response) {
$("#Status").val(response);
})
})
});
});
</script>
and my problem is i want to get this value in another javascript page that i included in my index but it alerts empty. this my indexPhone.js:
$("#SendPhone").click(function() {
alert($("#Status").val());
});
Ajax request is asynchronous, so the second click runs before value is set.
Use events:
// index.html
$("#SendPhone").click(function (e) {
// ...
$.ajax({
// ...
success: (function (response) {
$("#Status").val(response);
$("#Status").trigger("gotSMS");
})
});
});
// indexPhone.js
$("#Status").on("gotSMS", function () {
alert($(this).val());
});
So, I have a view with a chosen search box, a button "Add" (btn-default) and a button "Edit" (breadcrumb) . When I click the Add button, the ajax sent me a table with the values (in this case, funcionaries) selected in the chosen text box.
I want that, when I click on the Edit button, send the chosen values (can be one, or hundreds of values) to another controller to return another view.
Don't want to use ajax because I want to use a new view on totally.
On the controller side, when I send the data with javascript, I always get null. Why?
View
<script>
$(document).ready(function () {
$(".btn-default").on("click", function (event, params) {
$.ajax({
url: '#Url.Action("EditarPonderacoesEspecial", "Sorteios")',
type: 'POST',
dataType: 'html',
cache: false,
traditional: true,
data: { bdoIds: $(".chosen-select").val() },
success: function (responseText, textStatus, XMLHttpRequest) {
$("#MyDiv").empty();
$("#MyDiv").html(responseText);
},
error: function () { }
})
});
$(".breadcrumb").on("click",function (event, params) {
bdoIds = $(".chosen-select").val();
$.post("/Sorteios/EditarPonderacoesEspecialSecond/", bdoIds);
});
});
Controller
public ActionResult EditarPonderacoesEspecialSecond(string[] bdoIds)
{
//do whatever I want with the bdoIds
return View();
}
I had tried many different ways, but the controller always receive the parameter as null. What I am doing wrong? Thanks!
Your controller action is expecting an array of strings.
Assuming .chosen-select is a select list as that part is missing from the question.
First read the selected values into an object as follows:
var selectedValues = [];
$(".chosen-select :selected").each(function() {
selectedValues.push($(this).attr('value'));
});
Then send them as follows:
$(".breadcrumb").on("click",function (event, params) {
var selectedValues = [];
$(".chosen-select :selected").each(function() {
selectedValues.push($(this).attr('value'));
});
$.post("/Sorteios/EditarPonderacoesEspecialSecond/", { bdoIds: selectedValues });
});
Declare Global array like
var SelectedArray = new Array();
When you select multiple selectlist item each time push value in SelectedArray
$('#ChosenId').chosen().change(function () {
SelectedArray = $('#ChosenId').chosen().val();
});
Then your ajax data is like
data: { bdoIds: SelectedArray },
I have this array = var1;var2;var3;var4;var5;var6;var6
and I want to split it with jQuery and put it in different textboxes (txt1),(txt2)...etc,
but I can't find the right code.
<script type="text/javascript">
$(document).ready(function() {
$("#cb_motor").change(function() {
$("#cb_motor option:selected").each(function() {
cb_motor = $('#cb_motor').val();
$.post("http://localhost/sag_app/index.php/motor/motor/buscar_id/", {
cb_motor : cb_motor
}, function(data) {
valores = data.split(';');
});
});
})
});
</script>
If txt1, txt2 are inputs ID and is set following DOM order, you could use:
$("[id^=txt]").val(function(i){
return valores[i];
});
Assuming cb_motor is a select with no multiple, the code can be simplified
$(function() {
$("#cb_motor").change(function() {
$.post("http://localhost/sag_app/index.php/motor/motor/buscar_id/", {
cb_motor : $(this).val()
}, function(data) {
var valores = data.split(';');
$('[name="txt_num_serie_motor"]').each(function(i) {
$(this).val(valores[i]);
});
});
});
});
if it IS multiple, then you cannot do Ajax using each for the selected values since you need to wait for each call to return
Hi There I need to get the names and values of checkboxes that have been checked into an array name selected, I cannot for life of me get it working, below is my attempt, if someone could clrify what I am doing wrong that would be brilliant.
//Location AJAX
//var dataObject = new Object();
var selected = new Array();
$('#areas input.radio').change(function(){ // will trigger when the checked status changes
var checked = $(this).attr("checked"); // will return "checked" or false I think.
// Do whatever request you like with the checked status
if(checked == true) {
/*$("input:checked").each(function() {
selected.push($(this).attr('name')+"="+$(this).val();
});
alert(selected)*/
getQuery = $(this).attr('name')+"="+$(this).val()+"&location_submit=Next";
$.ajax({
type:"POST",
url:"/search/location",
data: getQuery,
success:function(data){
alert(getQuery);
console.log(data);
// $('body.secEmp').html(data);
}
});
} else {
//do something to remove the content here
alert("Remove");
}
});
You're missing the closing parantheses on the call to selected.push. It should be:
selected.push($(this).attr('name')+"="+$(this).val());
Otherwise, it looks fine.
Another, possibly simpler, way to do the same thing is to use map instead of each:
var selected = $('input:checked').map(function() {
return $(this).attr('name')+"="+$(this).val();
}).get();