So I have a jscript that creates a new text input and a drop-down select with each addition. That first one i have on the page is fine since the php function gets called on that page. The issue i have is my drop-down does not get populated by my query since i do not have the javascript function calling the php function. Im not sure how to add that in.
Here is my Jscript function.
var counter = 1;
var limit = 45;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Hop " + (counter + 1) + " <br><input type='text' name='myInputs[]'><br>" + "Type "+ (counter + 1) + " <br><select name='myInputs2[]' data-rel='chosen'><?php query() ?></select>" ;
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
Here is my html. This drop-down (the first drop-down) Does get populated.
<?php
include_once 'dropfunc2.php';
connect (); ?>
<script src="js/addInput.js" language="JavaScript" type="text/javascript"></script>
<form method="POST">
<div id="dynamicInput">
Hop 1<br><input type="text" name="myInputs[]"><br>
Type 1<br><select name="myInputs2[]" data-rel="chosen"><?php query() ?></select>
</div>
<input type="button" value="Add Hop" onClick="addInput('dynamicInput');">
<input type="submit" value="Submit">
</form>
Now I have tried doing what i have found on this site and making my jscript a .php page and adding the Header("content-type: application/javascript"); but then the function breaks completely and it does not add more inputs. I get a addInputs is not defined jscript error.
Put your PHP code to retrieve the data in a separate file and then call that script with AJAX. You can either send back formatted HTML or a JSON array to parse through and populate the tags in JavaScript.
This will help you out if you're new to AJAX and don't want to use JQuery: http://www.w3schools.com/ajax/default.ASP
If you want to use JQuery, then check this out: http://api.jquery.com/jquery.ajax/
Related
My if(isset) validation is returning false after I have submitted the form through jQuery ,however works fine when done without jquery. Reason I am using jQuery is because I need to submit multiple forms:
Button
<input class="btn btn-primary" type ="submit" id="myButton"
name="create_record" value="Submit 1">
jQuery:
<script>
$(document).ready(function () {
$("#myButton").click(function (event) {
event.preventDefault();
$("#form1").submit();
// $("#form2").submit();
});
});
</script>
PHP
<?php
if(isset($_POST['create_record'])){
$ecode = $_POST['ecode'];
$ename = $_POST['ename'];
$date = $_POST['date'];
$jobRole = $_POST['jobRole'];
}else{
echo "did not receive anything";
}
?>
Always getting "did not receive anything" . Can someone please help.
The submit button value only gets sent if the form is submitted in the traditional way by a button click. Since you are submitting the form via javascript, you'll need to explicitly include the submit button's value or validate your post data in some other way. If you need the value of the specific button that was clicked, something like this should work:
$("#myButton").click(function (event) {
event.preventDefault();
var el = '<input type="hidden" name="' + $(this).prop('name') + '" value="' + $(this).val() + '">';
$("#form1").append(el).submit();
});
As for your objective of submitting multiple forms at once, I believe it's impossible without using ajax as discussed here. If you need guidance on how to do that, better to open a new question.
Your code, isset($_POST['create_record']) maybe false or it didn't receive any values. If your query is only in one PHP file together with your jQuery, you need to check first your algorithm or use var_dump() for testing. Second, If it didn't work, make an alternative solution for it. Do the proper HTML code when using form or make another PHP file for receiving post purpose only.
<form action="directory_to_another_file" method="POST">
<!-- SOME INPUTS HERE -->
<input type="submit" value="Submit 1" name="create_record">
</form>
Try to test all of your codes.
You have to set form method as "POST" type and if you want to receive the form data in same page then empty the "action" key otherwise give the target link.
<?php
if(isset($_POST['create_record'])){
print_r($_POST);
}
?>
<form action="" method="POST" id="form1">
<input type="text" name="create_record" value="Submit 1"/>
</form>
Submit
<script>
$(function(){
$("#myButton").click(function (event) {
event.preventDefault();
$("#form1").submit();
});
})
</script>
Let me know if it's work for you.
I am trying to learn how to use Ajax to submit a form in a php loop. Can anybody see why the below code won't write to my database? If I take out the sname parts it works but only allows one column to be updated. Thanks in advance for your help
<!DOCTYPE html>
<html>
<head>
<?php include 'dbconnection.php';?>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
// Add the counter id as an argument, which we passed in the code above
function chk(id)
{
// Append the counter id to the ID to get the correct input
var name=document.getElementById('name' + id).value;
var name=document.getElementById('sname' + id).value;
var dataString='name='+ name + '&sname=' + sname;
$.ajax({
type:"post",
url: "dataInsert2.php",
data:dataString,
cache:false,
success:function(phtml){
// Instead of using the class to set the message, use the ID,
// otherwise all elements will get the text. Again, append the counter id.
$('#msg' + id).html(phtml);
}
});
return false;
}
</script>
</head>
<body>
<?php
$query=mysqli_query($connect,"SELECT distinct first_name from people " );
// Initiate a counter variable
$i = 1;
while ($row=mysqli_fetch_array($query))
{
?>
</br> <?php echo$row["first_name"]; ?>
<form>
<!-- Extra input added here
Append the counter to the ID -->
<input type="text" id="name<?= $i ?>">
<input type="text" id="sname<?= $i ?>">
<br/>
<!-- Send just the current counter to your method -->
<input type="submit" value="submit" onclick="return chk('<?= $i ?>')">
</form>
<!-- Append the counter to the message ID -->
<p id="msg<?= $i ?>" class="msg1"></p>
<?php
// Increment the counter
$i++;
}
?>
</body>
</html>
dataInsert2.php
<?php
include 'dbconnection.php';
$notes = $_POST['name'];
$class = $_POST['sname'];
mysqli_query($connect, "INSERT INTO people(class, notes)
VALUES ('$class','$notes')");
?>
Assuming your php loop is syntactically and grammatically correct,
The below function should be called whenever you click that Button.
function chk(id)
{
// Append the counter id to the ID to get the correct input
var name=document.getElementById('name' + id).value;
var name=document.getElementById('sname' + id).value;
var dataString='name='+ name + '&sname=' + sname;
$.ajax({
type:"post",
url: "dataInsert2.php",
data:dataString,
cache:false,
success:function(phtml){
// Instead of using the class to set the message, use the ID,
// otherwise all elements will get the text. Again, append the counter id.
$('#msg' + id).html(phtml);
}
});
return false;
}
In the third line, during variable declaration, you have variable name it should be sname according to your logic.
var sname=document.getElementById('sname' + id).value;
Since that variable will not be found in the 4th line(when you use it), It is facing an error. So your code after that line wont be executed.
i dont want to use serialize() function please help me with this. I am a beginner
html
<input type='button' value='Add Tier Flavor' id='Add'>
<input type='button' value='Remove Tier Flavor' id='Remove'>
<div id='batch'>
<div id="BatchDiv1">
<h4>Batch #1 :</h4>
<label>Flavor<input class="textbox" type='text' id="fl1" name="fl[]" value=""/></label></br>
<label>Filling<input class="textbox" type='text' id="fi1" name="fi[]" value="" /></label></br>
<label>Frosting<input class="textbox" type='text' id="fr1" name="fr[]" value=""/></label></br>
</div>
</div>
<br>
</div>
this is a dynamically added fields using javascript the code is:
javascript
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#Add").click(function () {
if(counter>5){
alert("Only 5 Tiers allow");
return false;
}
var newBatchBoxDiv = $(document.createElement('div')).attr("id", 'BatchDiv' + counter);
newBatchBoxDiv.html('<h4>Batch #'+ counter + ' : </h4>' +
'<label> Flavor<input type="text" name="fl[]" id="fl' + counter + '" value=""></label><br>'+
'<label> Filling<input type="text" name="fi[]" id="fi' + counter + '" value=""></label><br>'+
'<label> Frosting<input type="text" name="fr[]" id="fr' + counter + '" value=""></label><br>' );
newBatchBoxDiv.appendTo("#batch");
counter++;
});
$("#Remove").click(function () {
if(counter==1){
alert("No more tier to remove");
return false;
}
counter--;
$("#BatchDiv" + counter).remove();
});
});
</script>
i am trying to post the values in an array to post it onto next .php page
i am using this
var user_cupfl = $('input[name^="fl"]').serialize();
var user_cupfi = $('input[name^="fi"]').serialize();
var user_cupfr = $('input[name^="fr"]').serialize();
serialize is not passing the values. :(
on second page i am trying to mail it using
$message .= "<tr><td><strong>Cake Flavors(according to batches):</strong> </td><td><pre>" .implode("\n", $user_cupfl). "</pre></td></tr>";
$message .= "<tr><td><strong>Filling type (Inside the cake):</strong> </td><td><pre>" .implode("\n", $user_cupfi). "</pre></td></tr>";
$message .= "<tr><td><strong>Frosting type (top of the cake):</strong> </td><td><pre>" .implode("\n", $user_cupfr). "</pre></td></tr>";
i m posting array like this
$user_cupfl=filter_var($_POST["userCupfl"], FILTER_SANITIZE_STRING);
$user_cupfi=filter_var($_POST["userCupfi"], FILTER_SANITIZE_STRING);
$user_cupfr=filter_var($_POST["userCupfr"], FILTER_SANITIZE_STRING);
your replies will be highly appreciated
Just because you name a variable user_* doesn't mean that is what the name of the field is in the serialized POST data. You would still be looking for $_POST['fl'], $_POST['fi'] etc.
I don't understand why you think you need to serialize sets of input groups individually. You should just serialize the whole form at once.
I also see no reason why you need to have all this logic around unique id's with the counter and what not. If you are not using id's at all, just drop them altogether.
You might also consider simply using clone techniques to generate your dynamically added fields. You could greatly simplify all that javascript code by doing these things.
A more reasonable implementation may look like this.
HTML (cleaning up your code - consistent use of double quotes around properties, better strategy for class and id usage, etc.)
<div id="batch">
<div class="batchDiv">
<h4 class="batchLabel">Batch #1 :</h4>
<label>Flavor</label>
<input class="textbox" type="text" name="fl[]" value=""/>
</br>
<label>Filling</label>
<input class="textbox" type="text" name="fi[]" value="" />
</br>
<label>Frosting</label>
<input class="textbox" type="text" name="fr[]" value=""/>
</br>
</div>
</div>
Javascript:
$(document).ready(function() {
$('#Add').click(function(){
var $existingBatches = $('.batchDiv');
var count = $existingBatches.size();
if (count < 5) {
// get last batch div
var $newBatch = $existingBatches.last().clone();
// reset input values to empty string
$newBatch.find('input').val('');
// change batch label
count++;
$newBatch.find('.batchLabel').html('Batch #' + count + ' :');
// append to document
$newBatch.appendTo('#batch');
} else {
// alert or whatever
}
});
$('#Remove').click(function(){
var $existingBatches = $('.batchDiv');
var count = $existingBatches.size();
// delete last batch item if more than 1 exists
if(count > 1) {
$existingBatches.last().remove();
} else {
// alert or whatever
}
});
});
Now you haven't shown your AJAX code, but all you would need to do is something like:
var url = '/some/url';
var postData = $('[some form selector]').serialize();
var dataType = '...'; //whatever dataType you are expecting back
$.post(url, postData, function(){
// success handler
}, dataType));
Your data when then be available in PHP script at $_POST['fl'], etc.
I wrote script directly in html file, it adds some pagination feature, and it works just fine until it's in HTML file, but I just cant get how to transfer this script to external js file and make it run from there. So heres html part :
<form id="moredisplay" method="get" style="display:inline;">
<input class="hiddeninteger" type="hidden" name="loadmore" value="">
<!--LIMIT CHANGER-->
<input type="checkbox" title="" id="limitcheck" name="limit" value="<?php echo $vsego;?>" style="display:none;">
<input type="checkbox" title="" id="skipforfcheck" name="skip_items" value="" style="display:none;">
<input type="checkbox" title="" id="skipbackcheck" name="skip_items" value="" style="display:none;">
<button type="submit" title="back" value="" id="rerurn_more_items"/>back</button>
<button type="submit" title="next" value="" id="skip_more_items"/>fowards</button>
<button type="submit" title="more content" value="<?php echo $vsego;?>" id="limit" name="limit" onclick=""/>more content</button>
<script>
var currentval = jQuery('.scippeditems').attr('value');
jQuery('#skip_items,#rerurn_items').attr('value',currentval);
var valuenumber = jQuery('#skip_items').val();
if (valuenumber == 0){
jQuery('#rerurn_items').attr('disabled', 'disabled').css({'opacity':'0.6'});
}
var itemsshow = jQuery('#limit').val();
var pagescount = (jQuery('#skip_items').attr('value'))/(jQuery('#limit').attr('value'));
if(pagescount >=5){jQuery('#skip_items, #limit').attr('disabled', 'disabled').css({'opacity':'0.6'});}//COUNT PAGES AND LOCK NEXT
function changepageforf(){
var elem = document.getElementById("skip_items");
var currentval = elem.value;
elem.value = parseInt(currentval) + 24;}//parseInt(itemsshow);}
function changepageback(){
var elem = document.getElementById("rerurn_items");
var currentval = elem.value;
elem.value = parseInt(currentval) - 24;}//parseInt(itemsshow);}
</script>
<script>
jQuery(document).ready(function(){
jQuery('#limit').click(changelimit);//RUN FUNCTION ON LIMIT CHANGE
if ( document.location.href.indexOf('&limit') > -1 ) {//IF URL CONTAINS LINES LIMIT
jQuery('#rerurn_items, #skip_items').hide()//HIDE PAGINATION
jQuery('#rerurn_more_items, #skip_more_items').show()//SHOW LIMIT PAGINATION
var checkval = jQuery('#limitcheck').attr('value');
var currentvalskip = jQuery('.scippeditems').attr('value');
jQuery('#skipforfcheck').attr('value', (parseInt(checkval)+parseInt(currentvalskip)));//NEXT BTN VALUE
var currentforfaction = jQuery('#skipforfcheck').attr('value')
jQuery('#skipbackcheck').attr('value',Math.ceil( ( (parseInt(currentforfaction)-parseInt(checkval) ) - parseInt(checkval) ) ) );//PREV BTN VALUE
var pagescount = (jQuery('#skipforfcheck').attr('value'))/(jQuery('#limitcheck').attr('value'));
if(pagescount >=5){jQuery('#skip_more_items, #limit').attr('disabled', 'disabled').css({'opacity':'0.6'});}//COUNT PAGES AND LOCK NEXT
if( jQuery('#skipbackcheck').attr('value') <= 0 ){ jQuery('#skipbackcheck').attr('value', 0 );}//RETURN 0 AS A VALUE IF NEGATIVE
jQuery('#skip_more_items').click(function(){//SUBMIT NEXT BTN
jQuery('#limitcheck').attr('checked', true);
jQuery('#skipforfcheck').attr('checked', true);
jQuery('#moredisplay').submit()
});
jQuery('#rerurn_more_items').click(function(){//SUBMIT PREV BTN
jQuery('#limitcheck').attr('checked', true);
jQuery('#skipbackcheck').attr('checked', true);
jQuery('#moredisplay').submit()
});
}
function changelimit(){//LIMIT INCREASE STEP
var elem = document.getElementById("limit");
var currentval = elem.value;
elem.value = parseInt(currentval) + 6;}//HOW MUCH
var valuenumber = jQuery('#skip_items').val();
if (valuenumber == 0){//HIDE PREV BTN IF NO PREV
jQuery('#rerurn_more_items').attr('disabled', 'disabled').css({'opacity':'0.6'});
}
});
</script>
</form>
What i did try: copied script and put in in the pagination.js file and called a script on the top of the page like this
$document =& JFactory::getDocument();
$document->addScript("jquery/pagination.js");
but that doesnt work...Im new to jQuery so please dont bash me if im just stupid:L)
You need to wrap your code in:
$(document).ready( function() {
// your code here
});
As Aspiring Aqib pointed out, you need to start your JQuery script with either
$(document).ready( function() {
// your code here
});
or
$(function() {
// your code here
});
This is basically saying, ' wait until the DOM has been fully created before executing the script inside that function.
Both Aspiring Aqib and Dave were right about wrapping your jQuery code in the $(function(){//code goes here}); block.
Yet one more common mistake is not loading jQuery library file and your own .js files in the correct order, which might be tricky to find out as there is no warning anywhere in your editor or browser. The jQuery library must precede all your own .js files.
I have a hidden field in a form where I'm trying to grab the users screen resolution. Then on the processing end retrieve the screen resolution via php. Unfortunately, my understanding of javascript is pretty limited. Here is what I have. I would really appreciate any help.
<head>
<script type="text/javascript">
function xy(){
document.write(screen.width + "x" + screen.height);
document.getElementById('xy').value;
}
</script>
</head>
<form action="" method=post >
//other fields here
<input type="hidden" name="xy" id="xy" value=""/>
<input type=submit name="button" value="button" />
</form>
When I view the page's source code, shouldn't I see the value set to for example "1366x768"? Now on the processing side, I would like to pull out information with php like this.
if(isset($_POST['xy']) && (!empty($_POST['xy'])){
$blah = $_POST['xy'];
//sanatize $blah;
}
You can use
<script type="text/javascript">
function setResolution()
{
document.getElementById('xy').value = screen.width + "x" + screen.height;
}
</script>
Then, on submit, make sure the function is executed
<input type="submit" name="button" value="button" onclick="setResolution()" />
use
function xy(){
document.getElementById('xy').value = screen.width + "x" + screen.height;
}
and use the script tag or execute the function after rendering of the form else the element would not be found
EDITED: added fiddle
ulliw,
you don't call the function so you don't get anything...
if you will change to this, i beleive it will work for you:
<head>
<script type="text/javascript">
document.write(screen.width + "x" + screen.height); //this will write on the html page
document.getElementById('xy').value=screen.width + "x" + screen.height; // this will put the resolution in your form's hidden field
</script>