I'm trying to submit a form using Jquery's ajax. It has got a few textboxes, some checkboxes, and a multiple options' dropdown (i.e multiple options can be selected).
Someone here told me that I can get values of all selected checkboxes using
$("input:checkbox[name=type]:checked")
Then I can loop through all the values returned by the above code, assign them to an array like this:
var types=new Array();
$.each(cboxes, function()
{
types[types.length]=$(this).val();
}
);
And try to submit the form using this:
var someField=$("#someField").val();
var someField2=$("#someField2").val();
var data={field1 : someField, field2=someField2, s_types:types};
$.post("signup.php?type=p",types);
But that doesn't work, specifically the checkboxes don't get submitted correctly. How can I make it work?
It's not necessary to iterate over each field to get the form values. jQuery has a method to serialize form inputs into a querystring. You can do this:
$.ajax({
url: "mybackend.php",
data: $("#myForm").serialize(),
success: function(e) { // do something on success },
error: function(e) { // do something on error }
});
Remember that javascript posts always send data in UTF-8 format, so be sure you're expecting that on the backend if you plan to send text with international characters.
I recommend using a plug-in to do that. Have a look at this form plug-in. It also can integrate nicely with validation plug-in.
The default jQuery $.param doesn't handle arrays (by design), so you can't use $.serialize as it is. Use either a plugin, like suggested in kgiannakis' answer, or overwrite the $.param function so it'll handle arrays properly:
function($) {
$.param = function(a) {
var s = [];
if (a.constructor == Array || a.jquery)
jQuery.each(a, function() { s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) ); });
else
for (var j in a)
if (a[j] && a[j].constructor == Array) jQuery.each( a[j], function(){ s.push( encodeURIComponent(j) + "[]=" + encodeURIComponent( this ) ); });
else s.push(encodeURIComponent(j) + "=" + encodeURIComponent(a[j]));
return s.join("&").replace(/%20/g, "+");
};
})(jQuery);
...and then use $.serialize, like suggested by Danita.
Related
I have an Input that takes a name, and I want to take that name from input and set the url accordingly .. Here's the code, and an example
.form-group
%input.form-control{'type':'name','placeholder':'Name',id:'wisher_name'}
%input.form-control{'type':'name','placeholder':'Special Message'}
%button.btn.btn.btn-success{'id':'wisher_btn'} Wish
Javascript
$(document).ready(function() {
$(document).on('click', '#wisher_btn', function() {
var e = document.getElementById("wisher_name");
var diwali_wisher = e.value
location.replace("localhost:3000" + "/loccasion/diwali/" + diwali_wisher);
});
});
But the last statement is never reached, I don't know why?
This is a very basic problem, but I am a beginner so need some help.
You need to use a full url, like https://stackoverflow.com.
Add the http protocol.
diwali_wisher= Input parameter name in receiver function
diwali_wisher = e.value
location.replace("localhost:3000" + "/loccasion/diwali?diwali_wisher=" + diwali_wisher);
I have MVC controller that returns a list containing a search string.
public ActionResult GetList(string searchString)
{
ViewData["searchString"] = searchString;
if (String.IsNullOrEmpty(searchString))
{
var persons = db.Persons.ToList();
return View(persons);
}
else{
var persons = db.Persons.Where(p=> p.Title.Contains(searchString)).ToList();
return View(persons);
}
}
In the view the list is displayed in a table. I want to highlight the searchString (or at most the td that contains the searchString). The following is my jquery where I attempted to achieve this. I have tried putting this bit of code in a separate .js script or in the view itself and I have also tried to change the code in several ways but it wouldn't work. It appears like the searchString remains null even if the content of my ViewData has changed.
$(document).ready(function () {
var textToHighligt = #ViewData["searchString"];
$("#simpleSearchButton").click(function () {
$("td:contains(textToHighligt)").css("background-color", "yellow");
});
});
I think this:
var textToHighligt = #ViewData["searchString"];
$("td:contains(textToHighligt)").css("background-color", "yellow");
should be concatenated:
var textToHighligt = '#ViewData["searchString"]'; //<---put in quotes
$("td:contains("+textToHighligt+")").css("background-color", "yellow");
I think you can do otherwise if it is not happening in the javascript file , create a hidden field and populate the value from the ViewBag
#Html.Hidden("hiddensearchString", (string)ViewBag.searchString)
For the ViewData
#Html.Hidden("FirstName", ViewData["searchString"])
and then the javascript read the value like this
var searchString = $("#hiddensearchString").val();
In you code you can also try this using of the single quote.
var textToHighligt = '#ViewData["searchString"]';
I have a CMS that let my users to sort menu by jquery ui sortable.
What does jquery ui return?
I used this code:
JavaScript:
$( "#menuUl" ).sortable({
update: function (event, ui) {
var data = $(this).sortable('serialize');
console.log(data);
}
})
html:
echo '<ul id="menuUl">';
$i=0;
while($row=mysql_fetch_array($result_select_menu)){
$i++;
echo '<li name="asdsad" id="li-'.$row['menu_id'].'" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>'.$row['title'].'<input type="hidden" value="" id="hidden-'.$row['menu_id'].'" class="hiddenClass" name="id['.$row['menu_id'].']"/></li>
';
}
echo '</ul>';
This is what javascript says :
li[]=2&li[]=1&li[]=3&li[]=4&li[]=5&li[]=6&li[]=7&li[]=8&li[]=9&li[]=10&li[]=11&li[]=12&li[]=13&li[]=14
I need to know which li has what number.
like this:
li[1]=2&li[2]=1&li[3]=3&li[4]=4&li[5]=5&li[6]=6&li[7]=7&li[8]=8&li[9]=9&li[10]=10&li[11]=11&li[12]=12&li[13]=13&li[14]=14
my other question is this: Can I change what serialize return, for example serialize return li[]=1, but I need to say li[1]=1
There is some way to doing this, I think you should use serialize, and then send it by Ajax to your server side page.
This is a good answer for you write order into database
Out of the box: no, you can't do this. sortable.serialize() returns a string formatted according to the spec in $.param(). The closest approach to doing it out of the box would be with sortable.toArray() with JSON.stringify() and JSON.parse().
As for doing it manualy, since this is all in order, and only contains lis, converting it to the format you say you want wouldn't be difficult:
var data = $(this).sortable('serialize');
var i = 0;
while(data.indexOf("li[]") !== -1) {
data = data.replace(/li\[\]/, "li[" + (i++) + "]");
}
This will convert your first string to
li[0]=2&li[1]=1&li[2]=3&li[3]=4&li[4]=5&li[5]=6&li[6]=7&li[7]=8&li[8]=9&li[9]=10&li[10]=11&li[11]=12&li[12]=13&li[13]=14
Keep in mind you'll need to maintain this yourself, and it's only for the case where you absolutely need to preserve array indices.
HTML input fields
<input type="text" name="partner_name_or_description[]" id="partner_name_or_description1" class="row_changed1"/>
<input type="text" name="partner_name_or_description[]" id="partner_name_or_description2" class="row_changed2"/>
<input type="text" name="partner_name_or_description[]" id="partner_name_or_description3" class="row_changed3"/>
Part of jquery autocomplete code (that works)
$("#partner_name_or_description1:input, #partner_name_or_description2:input, #partner_name_or_description3:input").autocomplete(
"__autocomplete_source.php",
In jquery there are: partner_name_or_description1, 2, 3 etc.... Instead of this long list of 1, 2, 3 etc. want to use something short with serialize (or in other possible way).
At first get these 1,2,3... with this code
$('[id^="partner_name_or_description"]').each(function (index, partner_name_or_description) {
var s_id = partner_name_or_description.id.substring(27);
});
Then instead of that long list trying to make something like this
$("#partner_name_or_description" + s_id + " :input").serialize().autocomplete(
It does not work. If View source, see
$("#partner_name_or_description" + s_id + " :input").serialize().autocomplete(
Do not understand reason... May be incorrectly use serialize().autocomplete
Or may be must not use serialize() and must use something else.
I can not use class="row_changedX" because it is necessary for other purposes (class must be like row_changed1, 2, 3; for each row class name must be different).
Working code
/*Actually do not understand why this is necessary, but if I delete all uncommented, then code does not work*/
function findValue(li) {
/*if( li == null ) return alert("No match!");
// if coming from an AJAX call, let's use the CityId as the value
if( !!li.extra ) var sValue = li.extra[0];
// otherwise, let's just display the value in the text box
else var sValue = li.selectValue;
alert("The value you selected was: " + sValue);*/
}
function selectItem(li) {
findValue(li);
}
function formatItem(row) {
return row[0] + " (id: " + row[1] + ")";
}
$('[id^="partner_name_or_description"]').autocomplete("__autocomplete_source.php",
{
delay:10,
minChars:2,
matchSubset:1,
matchContains:1,
cacheLength:10,
onItemSelect:selectItem,
onFindValue:findValue,
formatItem:formatItem,
autoFill:true
}//{ delay:10,
)//.autocomplete(;
Edit: Thanks to #jk -- this will work:
$('[id^="partner_name_or_description"]').autocomplete(
"__autocomplete_source.php",
//do stuff
});
I have a multi-lingual page where I want to display form validation error in the user's language. I use a hidden input to determine which language version the user is browsing like this: <input type="hidden" name="lang" id="lang" value="<?php echo $lang; ?>" />
The PHP side of the script works, but jQuery doesn't seem to realize which language is passed on. It displays the English error message no matter on which language site I am.
Here's the code (I removed the other form fields for length):
$(document).ready(function(){
$('#contact').submit(function() {
$(".form_message").hide();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var lang = $("#lang").val();
var name = $("#name").val();
var dataString = {
'lang': lang,
'name': name
}
if (name == '') {
if (lang == 'de') {
$("#posted").after('<div class="form_message"><p><span class="error">Fehler:</span> Bitte gib deinen Namen an!</p></div>');
} else {
$("#posted").after('<div class="form_message"><p><span class="error">Error:</span> Please enter your name!</p></div>');
}
$("#name").focus();
$("#name").addClass('req');
} else {
$("#loading").show();
$("#loading").fadeIn(400).html('<img src="/img/loading.gif" />Loading...');
$.ajax({
type: "POST",
url: "/contact-post.php",
data: dataString,
cache: false,
success: function(html){
$("#loading").hide();
$("#posted").after('<div class="form_message"><p>Thank you! Your contact request has been sent.</p></div>');
$("#contact input:submit").attr("disabled", "disabled").val("Success!");
}
});
}return false;
}); });
The problem seems to be somewhere in the nested if statement. Does jQuery / javascript even recognize nested ifs? And if yes, why is it not working?
Does jQuery / javascript even recnogize nested ifs?
Yes they do
One thing worth checking that would cause this behaviour is that you don't have any other elements on your page with id = lang. If there are, your $("#lang") selector will only find the first one, and if that's not your hidden input it won't work as you expect.
Javascript is case-sensitive, and perhaps the value of your #lang element is in a different case. You can force it to be lowered like this...
var lang = $("#lang").val().toLowerCase();
Why wouldn't it recognize nested if's?
Can you include the HTML for the page? There doesn't appear to be anything wrong with this javascript at all - so I have a feeling the issue is with the rest of the page.
Barring that, put an alert(lang) in right before your if statement to see what it is set to. My guess is that it will not be set to the value that you think it should be set to.
Check the value
alert("'" + lang + "' :" + lang.length);