I want to do the search using ajax jquery js, for that I have taken this piece of code from here:-
Now i have some issues, I have this Javascript code:-
<script language="JavaScript" type="text/javascript">
<!--
function searchuser(cv) {
$("#SearchResult").html('<img src="loader.gif"/>').show();
var url = "elements/search-user.php";
$.post(url, {contentVar: cv} ,function(data) {
$("#SearchResult").html(data).show();
});
}
//-->
</script>
My Form:-
<label>
<input onClick="generatenew();" type="radio" name="search_option" value="code" id="search_option_0">
Customer Code</label></td>
<td><label>
<input onClick="generatenew();" type="radio" name="search_option" value="company" id="search_option_1">
Customer Company</label></td>
<td><label>
<input onClick="generatenew();" type="radio" name="search_option" value="name" id="search_option_2">
Customer Name</label></td>
<td><label>
<input onClick="generatenew();" type="radio" name="search_option" value="email" id="search_option_3">
Customer Email</label>
This is my search textbox
<input type="text" name="searchuser_text" id="newInput" size="25" maxlength="25" class="inputbox MarginTop10">
This is my search button
<input onclick="javascript:searchuser('con1');" class="Button" name="search_user_submit" type="button" value="Search">
This is my Display Area :-
<div id="SearchResult">My default content for this page element when the page initially loads</div>
Now i want to know on click of button i am sending a data i.e. con1. I want to send two data to the searchuser function, one the selected option button value and the another one is the text in the textbox. After sending both the data to the function how will i get the data in the function? Do i need to change the function searchuser(cv) to function searchuser(cv, cvtwo).
Also while the $.post(url, {contentVar: cv} ,function(data) is sending only one data to the php file, how can i send both the data i.e. cv and cvtwo to the php file?
First of all you can modify the search function to something like this
$("input[name='search_user_submit']").click(function(){
var cv = $('#newInput').val();
var cvtwo = //similar to above
var data = 'cv='+ cv + '&cvtwo='+cvtwo; // sending two variables
$("#myDiv").html('<img src="loader.gif"/>').show();
var url = "elements/search-user.php";
$.post(url, {contentVar: data} ,function(data) {
$("#SearchResult").html(data).show();
});
});
Don't use inline functions, you can do it easily with jQuery's native bind functionality:
// Search when you click on submit
$(document).on('click', '.submit_button', function(){
search('click_button');
});
// Search when you press enter
$(document).on('keypress', "#searchString", function(e){
var c = (e.keyCode ? e.keyCode : e.which);
if(c == 13) {
search('pressed_enter');
}
});
You can therefore collect the button value and pass it through to your search function:
function search(button_value) {
$("#myDiv").html('<img src="loader.gif"/>').show();
$.post("elements/search-user.php", { search_value: $('#newInput').val(), button_value: button_value} ,function(data) {
$("#SearchResult").html(data).show();
});
}
What you're doing is send off the form with two $_POST variables: one is the search string you've inputted in to the search box (called search_value) and the other is the button value.
Related
I have here Jquery code with ajax/json. First i will discuss the flow. I have 3 textboxes, my item textbox pass it's value to auto-complete.php through ajax to get it's details. The return value is post or place into mode textbox. And if the post value is 1 or 2 the number textbox should change is css into display:none. But the problem this not working, I set the number textbox into readonly. The change function is working when I change directly the value of number textbox. Why isn't working when the value is post value?
<script>
$(document).ready(function() {
$("#number").css("display","none");
$(document).on('change','#mode',function(){
if($("#mode").val() =="1"){
$("#number").css("display","");
} else if($("#mode").val() =="2"){
$("#number").css("display","");
} else {
$("#number").css("display","none");
}
return true;
});
});
</script>
<input name="item" id="item" type="text"/>
<input name="mode" id="mode" type="text"/>
<input name="number" id="number" type="text" readonly />
<script type="text/javascript">
$(document).ready(function()
{
$('#item').change(function()
{
var item= $("#item").val();
$.ajax({
type: "POST",
url: "autocomplete-ajax.php",
data :"item="+item,
dataType:'json',
type:'POST',
success:function(data){
var mode=data.mode;
//send to element ID
$('#mode').val(mode);
}
});
return false;
});
});
</script>
When you change the value using JavaScript it won't trigger events.
A simple fix is to trigger the event yourself after you update the value.
success:function(data){
var mode=data.mode;
//send to element ID
$('#mode').val(mode).change();
/* OR */
$('#mode').val(mode).trigger('change');
}
I have html form with dynamical number of fields, for example:
<form id="myform">
<input type="text" id="input1">
<input type="text" id="input2">
<input type="text" id="input3">
...
<input type="text" id="inputN">
<span id="button_click"> CLICK </span>
</form>
and jQuery which is:
$("#button_click").click(function(){
$.post("myfile.php",
{
XXXX:YYYY
},
function(data,status){
// do anyting
});
});
I don't know the exact number of fields, so I can't fill XXXX - post variable name, and YYYY - field data from web page.... so I can't count/write one by one...
How can I submit whole form, through post variables, using AJAX and click button?
Sounds like you're looking for the .serialize() method:
$.post("myfile.php",
$("#myform").serialize(),
function(data,status){
// do anyting
});
http://api.jquery.com/serialize/
//rough code for general puporse of storing values for post
var obj = $("#myform"),
data = {};//to hold the values
obj.find('[name]').each(function(index, value) {
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.post("myfile.php",
data: data,
function(data,status){
// do anyting
});
i'm new to programming. I need to develop a rating system with check boxes and text-fields where user clicks the subjects from the list and add his rating/experience in the text field as shown in below image.
This is my HTML code.
<form action="" method="post">
<input type="checkbox" id="1" name="cb[1]" value="" onclick="document.getElementById('t1').disabled=!this.checked;" />
<label for="1">Checkbox No. 1</label>
<input type="number" max="5" min="1" id="t1" name="t[1]" value="" disabled="disabled" /><br /><br />
<input type="checkbox" id="2" name="cb[2]" value="" onclick="document.getElementById('t2').disabled=!this.checked;"/>
<label for="2">Checkbox No. 2</label>
<input type="number" max="5" min="1"id="t2" name="t[2]" value="" disabled="disabled" /><br /><br />
<input type="checkbox" id="3" name="cb[3]" value="" onclick="document.getElementById('t3').disabled=!this.checked;"/>
<label for="3">Checkbox No. 3</label>
<input type="number" max="5" min="1"id="t3" name="t[3]" value="" disabled="disabled" /><br /><br />
<input type="checkbox" id="4" name="cb[4]" value="" onclick="document.getElementById('t4').disabled=!this.checked;"/>
<label for="4">Checkbox No. 4</label>
<input type="number" max="5" min="1"id="t4" name="t[4]" value="" disabled="disabled" /><br /><br />
<input name="submit" type="submit" value="Submit" />
</form>
This is my php function.
global $usedTexts;
$usedTexts = array();
function postdata(){
if ( isset($_POST['submit']) && array_key_exists("t", $_POST) && is_array($_POST["t"]) && array_key_exists("cb", $_POST) && is_array($_POST["cb"])) {
$usedTexts = array_intersect_key($_POST["t"], $_POST["cb"]);
foreach($usedTexts as $subjectId=>$subjectExp){
if($subjectExp!=null){
echo "This is checkbox id = " . $subjectId . " and This is text field value = " . $subjectExp . "<br />";
}
}
}
}
I'm using wordpress and I want to submit checkbox ID and text Field value without refreshing the browser using Ajax. And also I want to display check box id and value as shown in the picture. I would be very much appreciated if someone can provide ajax code for this. Thanks :)
You can code this using XMLHttpRequest Object or an easier not necessary better is using JQuery. JQUERY AJAX API
Then you can do something like this
$('form').submit(function(event) { //make sure you give your form an ID
event.preventDefault();
$.ajax({ // Initiate an ajax call
type: "POST", // You seem to want post HTTP call
url: "URLPATH/youphpcode.php",
dataType: "json", // this is the data type to return usually JSON
data: votes,//data to send USUALLY JSON or hashmap/array
success: function(d)
{
$('#displayMSG').HTML('Your Votes have been submitted') // Maybe display a message or error.
}
});
});
To find out what fields they enabled and selected the values I have added a script here.
http://jsfiddle.net/eMEYP/10/
var votes = {}; // initialize it globally
$('#form').submit(function (event) {
event.preventDefault();
var votes = {}; // reset and empty the votes
$('input[type=number]:enabled').each(function (i) { // Check inputs by type and which are enabled and run a for each
votes[$(this).attr('id')] = $(this).val(); // Add items to the hashmap
});
var json = JSON.stringify(votes); //you can send DATA as the HASH or stringify it.
});
FULL CODE *
$('form').submit(function(event) { //make sure you give your form an ID
event.preventDefault();
var votes = {}; // reset and empty the votes
$('input[type=number]:enabled').each(function (i) { // Check inputs by type and which are enabled and run a for each
votes[$(this).attr('id')] = $(this).val(); // Add items to the hashmap
});
$.ajax({ // Initiate an ajax call
type: "POST", // You seem to want post HTTP call
url: "URLPATH/youphpcode.php",
dataType: "json", // this is the data type to return usually JSON
data: votes,//data to send USUALLY JSON or hashmap/array
success: function(d)
{
$('#displayMSG').HTML('Your Votes have been submitted') // Maybe display a message or error.
}
});
});
Use JQuery to prevent the default submit behavior of the form when you click the Submit button. It is like this but it is incomplete:
$('#form').submit(function(event){
event.preventDefault(); //This line prevents the default submit action of the id #form
//Put your AJAX code here that will submit your checkbox and textbox data
})
See http://api.jquery.com/submit/
now i have a input text, radio, and a submit button ..
lets say my url = image-search.php
<form>
<input type="text" name="name"><br>
<input type="radio name="arrange" value="horizontal"><br />
<input type="radio name="arrange" value="vertical"><br>
<input type="submit" name="submit"><br>
when i click the button..
it redirect same page but url = image-search.php?name=ss&arrange=horizontal
and this page still have the button..
the question is .. after i click button at 1st page = image-search.php
i want the user input value remain in the input text of name..
and how to make the checkbox as checked based on user choose?
If the page is reloaded when you submit the form you could use php to set default values for your form fields
<form>
<input type="text" name="name" value="<?php echo isset($_GET["name"])?$_GET["name"]:""; ?>"><br>
<input type="radio" name="arrange" value="horizontal"<?php echo (isset($_GET["arrange"])?($_GET["arrange"]=="horizontal"?" checked='checked'":""):""); ?>><br />
<input type="radio" name="arrange" value="vertical"<?php echo (isset($_GET["arrange"])?($_GET["arrange"]=="vertical"?" checked='checked'":""):""); ?>><br>
<input type="submit" name="submit"><br>
</form>
Here is the answer to your question.. hope this will help everyone..
#Macke - your approach for setting values after submission is really good, but when we have lot of elements on form.. let's say 1000 - it become pain in AS*..
Add this script tag in your HEAD tag of the page -
<script language="javascript" type="text/javascript">
var obj = JSON.parse('<?= json_encode($_REQUEST) ?>');
console.log(obj);
function __setPostBackValue(element){
if(obj.length <= 0) return;
var type = element.type;
var fval;
console.log('Processing...'+ element.name);
try{
eval('fval = obj'+'.'+element.name);
}
catch(ex){
}
if(type == 'text'){
element.value = fval;
}
if(type == 'checkbox'){
if(fval != undefined)
element.setAttribute("checked","on");
}
if(type == 'radio'){
if(fval != undefined && element.value == fval)
element.setAttribute("checked","on");
}
}
</script>
and at the bottom of the page, yes at the bottom of the page (before body ends) add another script tag -
<script language="javascript" type="text/javascript">
var fields = document.getElementsByTagName('input');
for(var i=0;i<fields.length;i++){
__setPostBackValue(fields[i]);
}
</script>
What it does ?
When you submit your form, var obj = JSON.parse('<?= json_encode($_REQUEST) ?>'); this creates local JSON Object usable by Javascript - and the script we added at the end of the page.. loop through all elements and call __setPostBackValue function. Where we are setting the values of the elements by Javascript.
This is little bit tricky but it works..!!
PS: I had no radio button in my page, but if you have you can add it easily.
-Paresh Rathod
I have a registration form that is currently in a popup modal window coded in jQuery. I have a PHP submit button on the bottom and I have added jQuery code that stops the button from submitting. This is because it will stop my modal window from closing when I submit the page. My issue now is that submitting the form would be impossible. Is there a way to submit my form over all this crowded pop-ups and jQuery? Say is it possible to use AJAX or jQuery to submit the form and allow my PHP to handle it.
Since I am writing in PHP, there is quite a bit of server side validation going on, so the point of this is to allow my viewers to fix their validation mistakes before the modal window closes.
Here is my jQuery, I didnt bother to mess with that anymore as it does what I need.
$(document).ready(function() {
$('a.modal-window').click(function() {
//Getting the variable's value from a link
var loginBox = $(this).attr('href');
$(loginBox).fadeIn(300);
var popMargTop = ($(loginBox).height() + 24) / 2;
var popMargLeft = ($(loginBox).width() + 24) / 2;
$(loginBox).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
// Add the mask to body
$('body').append('<div id="mask"></div>');
$('#mask').fadeIn(300);
return false;
});
// When clicking on the button close or the mask layer the popup closed
$('a.close, #mask').live('click', function() {
$('#mask , .login-popup').fadeOut(300 , function() {
$('#mask').remove();
});
return false;
});
});
Here is the code I used to stop the form from submitting:
$(function () {
$(':submit').click(function (event) {
event.preventDefault();
// submit the form dynamically
});
});
and below is my form, it might not matter although its there for the viewing.
<form method="post" id="loginform" action="<?php echo $_SERVER['PHP_SELF']?>">
<table style="color: white;">
<tr><th style="float:left;">Register a new account with us.</th></tr>
<tr><td>Username</td><td><input type="text" name="txtUser"/></td></tr>
<tr><td>Password</td><td><input type="text" name="txtPass"/></td></tr>
<tr><td>Email</td><td><input type="text" name="txtEmail"/></td></tr>
<tr><td>Confirm Email</td><td><input type="text" name="txtEmail2"/></td></tr>
<tr><td>First Name</td><td><input type="text" name="txtFname"/></td></tr>
<tr><td>Last Name</td><td><input type="text" name="txtLname"/></td></tr>
<tr><td>Address</td><td><input type="text" name="txtAddress"/></td></tr>
<tr><td>City</td><td><input type="text" name="txtCity"/></td></tr>
<tr><td>Postal Code</td><td><input type="text" name="txtPostal"/></td></tr>
<tr><td>Birth Year</td><td><input type="text" name="txtBirth"/></td></tr>
<tr><td>Gender</td><td><input type="radio" id="radio-1-1" name="radicalSex" class="regular-radio" value="m" selected="true" /><label for="radio-1-1"></label> Male</td></tr>
<tr><td></td><td><input type="radio" id="radio-1-2" name="radicalSex" class="regular-radio" value="f"/><label for="radio-1-2"></label> Female</td></tr>
<tr><td colspan='2' style="color: #FF6600;float:left;font-size:70%;"><?php echo $Error;?></td></tr>
<tr><td colspan="2"><input type="submit" name="btnRegister" ID="btnBlueTemp" value="Submit Registration" /></td></tr>
<tr><td colspan='2' style="float:left; font-size:70%;">Address information is optional</td></tr>
</table>
</form>
Let me give you an example of how you can do that .
<html>
<head>
<title></title>
<script src="js/jquery-1.7.2.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
function validate(name, addr){
if(name=="") {
alert('Name is Blank');
return false;
} else if(addr=="") {
alert('Address is Blank');
return false;
} else {
return true;
}
}
$("#save").click(function(event){
event.preventDefault();
var name = $("#name").val();
var addr = $("#addr").val();
if(validate(name,addr)){
$.ajax({
type:'POST',
data:'name='+name+'&addr='+addr,
url:'test2.php',
success:function(data) {
alert(data);
}
})
}
});
});
</script>
</head>
<body>
<form name="frm" method="POST" action="">
<input type="text" name="name" id="name" value=""/><br>
<input type="text" name="addr" id="addr" value="" /><br>
<input type="submit" name="save" id="save" value="Save"/>
</form>
</body>
</html>
Now in test2.php You can do your php codes
<?php
if(isset($_POST['name'])) {
echo $_POST['name'];
}
?>
Hope this gives you an Idea.
You need to serialize the form data before posting it to PHP.
<script type="text/javascript">
var frm = $('#loginform');
frm.submit(function () {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('submitted');
}
});
return false;//stop actual form submit
});
</script>
Then, submit your form via ajax
Jquery AJAX
On AJAX URL on which the request is sent, you can write necessary codes for validation and return accordingly. For eg. if some one the form element doesn't meet the validation, you can throw the flag accordingly as json value.
Its possible, why not.
Once you have done all the input validation at client side, just submit the form...
$("#loginform").submit();
Then you will have your server do the rest of the validation.
If you want to stay in the page and show the validation output from server, the. You should submit using Ajax.
It will send your form data to server, then you can do server validation, and output any errors. You will get this in your Ajax complete handler, which you can use to show error messages to user.
To stop the form from reloading the page you needn't call any prevent methods as a simple script request would do the trick.
For instance,
$('#loginForm').submit(function() {
// Do the relevant tasks needed here, form is already prevented from being submitted
});
Check out this demo for more information on what I am referring to