***********EDIT ************
This is now my code:
<script>
$(document).ready(function(){
$("#btn").click(function(){
$(".div2").append("<div class='tekst2'><div id='green'></div><textarea rows='8' cols='30' id='tekst' name='tekst' class='tekst'></textarea></div><br/>");
});
$("#btn2").click(function(){
$(".div3").append("<div class='tekst'><div id='red'></div><input class='nummer' id='nummer' type='text' name='nummer'></div><br/>");
});
var ele = new Array();
$("#btn1").click(function(){
$('.tekst').each(function(){
$('.nummer').each(function(){
ele.push($(this).val());
}); });
var send = ele.join(',')
request = $.ajax({
url: "form.php",
type: "post",
data: ele
//you can use this request object to know what's the status of your response
});
});
});
</script>
And this is the code for set the data to the database
<?php
require_once'config.php';
$tekst = $_GET['tekst'];
$query = "INSERT INTO draaiboek (tekst)
VALUES ('$tekst')";
$result = mysqli_query($mysqli, $query);
if($result) {
}
else {
}
Only i get empty rows in the database. Whats gone wrong?
**********END EDIT**************
I made a site to fill things in on an form. I have two buttons to get an extra form field on the screen. I want to save the data using the exact same markup somewhere. In a mysql database or locally. Does anyone know how you can store data and can later read out again with the same format? This is the code for get an extra form field:
$(function() {
$('#btnAddtoList').click(function(){
var newDiv = $('<div class="tekst2"><div id="green"></div><input class="formtijd" placeholder="Tijd" id="tijd" type="text" name="tijd"><textarea rows="6" cols="50" id="tekst" name="tekst" class="tekst"></textarea></div><br/>');
//newDiv.style.background = "#000";
$('body').append(newDiv);
});
$('#btnAddtoList2').click(function(){
var newDiv = $('<div class="tekst"><div id="red"></div><input class="formtijd" placeholder="Tijd" id="tijd" type="text" name="tijd"><input class="formtekst" id="nummer" type="text" name="nummer"></div><br/>');
//newDiv.style.background = "#000";
$('body').append(newDiv);
});
});
And this is the code for show on the screen:
<button id="btnAddtoList" class="btn btn-success">Nieuw tekst veld</button>
<button id="btnAddtoList2" class="btn btn-danger">Nieuw nummer veld</button><br/><br/>
<div id="tekst"></div>
<div id="tekst2"></div>
When I click on the button, there shows an new field. So it looks like:
May be not an efficient one but this is what I could write in short time
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
$("div").append("<input type='text' class='funfoo' placeholder='Fill me'/> <br/><br/>");
});
var ele = new Array();
$("#btn1").click(function(){
$('.funfoo').each(function(){
ele.push($(this).val());
});
var send = ele.join(',')
request = $.ajax({
url: "/form.php",
type: "post",
data: ele
//you can use this request object to know what's the status of your response
});
});
});
</script>
</head>
<body>
<button id="btn">Add fields</button>
<button id="btn1">Submit fields</button>
<div></div>
</body>
</html>
In this approach, you can simply append input values and then get all the values in them. Join all the values with comma and then dump in any single column (will save lot of other effort and you just need one column for all the values).
Now to display these values in the same format what you can do is, simply get the field value form DB, split them and add input fields for individual values. (you can do it in a loop I'll show you a demo).
--------------------------your display page --------------
//this is a pseudo code
<?php
$val = query to get that value (comma separated)from db
$val2 = $val.split(',');
for($i =0; $i<val2.lenght; $i++)
{
<input class='' value='<?php echo $val2[i] ?>'/>
}
?>
Hope this would help you :)
Related
So I have all this code that works fine. But it only shows the table records when I start typing inside the search field. I want all the records to be visible by default the moment I open the page.
I know this has something to do with the keyup function but is there a way to have all the records be visible by default before I typed anything inside the search field?
AJAX Live Search/ Input Code
<input type="text" id="search">
<div class="table-container" id="output"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#search").keyup(function(){
$.ajax({
type:'POST',
url:'search.php',
data:{
name:$("#search").val(),
},
success:function(data){
$("#output").html(data);
}
});
});
});
</script>
PHP Code
$select = "SELECT * FROM info WHERE name LIKE '%".$_POST['name']."%'";
$result = mysqli_query($conn, $select);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "
//table code.. ";
}
I want it to work like how filter searches would work.
just write another ajax
$('#search').on('click',function(){
$.ajax({
type:'GET',
url:'searchAll.php',
success:function(data){
$("#output").html(data);
}
});
});
Then in searchAll.php file write your query php code.
NOTE: Use prepared statements or PDO to prevent SQL injections
I have a code that appends the input tag when i cliked the button
var max_fields = 10;
var wrapper = $("#container");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div class="form-group label-floating"><label class="label">title</label><input type="text" id="title_name'+x+'" class="form-control">Delete</div>'); //add input box
} else {
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove();
x--;
});
I used ajax call to get the data from my database
$.ajax({
url:'../ajax/gettitle.php',
type:'POST',
data:{userid:user},
dataType:'JSON',
success: function(result){
$('#title_name'+x).val(result.title_name);
console.log(result);
},
error:function(status){
}
});
and this is my gettitle.php
if (isset($_POST['userid'])) {
$id = $_POST['userid'];
$data = $user->getTitle($id);
echo json_encode($data);
}
public function getTitle($titleid) {
$sql = "SELECT * FROM tbl_title WHERE title_userid = '$titleid'";
$view = $this->dbh->prepare($sql);
$view->execute();
$userdata = $view->fetchAll(PDO::FETCH_ASSOC);
return $userdata;
}
and this is the query I use..
Now my problem is how can i display the returned data from my append input field, because whenever I tried it doesn't display anything.
This is the returned data from my ajax call
What I wanted is to display both title_name on my input field. Like if I have two array of data supposedly two input field will show up with the data from my database and like if there is a data on my input field what I want to achieve is the input field will show up.
Hi You have to modify your gettitle.php file instead of returning objects it need to return html code, which you can bind with your html file. As I understand from your question, here what you need to modify
gettitle.php
<?php foreach(exam-array as value){ ?>
<div class="form-group label-floating"><label class="label">title</label><input type="text" id="<?php echo value['title_name']; ?>" class="form-control">Delete</div>
<?php } ?>
Now on sucees call art you modify this one
success: function(result){
$(wrapper).append(result);
}
Let me know if you need any further assistance
I am having a problem with posting a value to my php script via jQuery/ajax. I have searched around looking for a solution but cannot seem to figure it out why i am not getting the value posted.
here's my code.
page.html
<body>
input message:<p><input type="text" id="note" name="note" placeholder="enter something that made you feel this way"></p><br />
<p><button name="submitMessage">submit</button></p>
<script src="../js/jquery-3.1.1.js"></script>
<script src="../js/welcomeScript.js"></script>
<script> $( document ).ready(function() {
$('[name=submitMessage]').on('click', function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '../php/post-note.php',
data: {data: $('#note').attr('val')},
success: function(){
alert('added your note, you will now go to main app!');
window.location.href = "../home.php";
}
});
});
});
</script>
</body>
post-note.php
session_start();
$note = $_POST['data'];
if(isset($note) && isset($_SESSION['username'])){
$username = $_SESSION['username'];
$sqlMessage = "UPDATE mt_tbl SET note = '$note' WHERE userName = '$username'";
mysqli_query($conn, $sqlMessage);
echo "note: ".$note. " added to the dB!";
}
Instead of $('#note').attr('val') use $('#note').val()
Why? the reason is given below:-
console.log($('#note').attr('val'));
console.log($('#note').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id = "note" value = "2">
I'm having an issue. When I hit submit, my form values are sent to the database. However, I would like the form to both send the value to the database and execute my script, as said in the title.
When I hit submit button, the form is sent to the database and the script remains ignored. However, if I input empty values into the input areas, the javascript is executed, and does what I want (which is to show a hidden < div >), but it's useless since the < div > is empty, as there is no output from the server.
What I want is:
submit button -> submit form -> javascript is executed > div shows up > inside div database SELECT FROM values (which are the ones added through the submitting of the form) appear.
Is this possible? I mean, to mix both PHP and JavaScript like this?
Thanks in advance.
By two ways, You can fix it easily.
By ajax--Submit your form and get response
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //action
data: form.serialize(), //your data that is summited
success: function (html) {
// show the div by script show response form html
}
});
});
First submit your from at action. at this page you can execute your script code .. At action file,
<?php
if(isset($_POST['name']))
{
// save data form and get response as you want.
?>
<script type='text/javascript'>
//div show script code here
</script>
<?php
}
?>
hers is the sample as I Comment above.
In javascript function you can do like this
$.post( '<?php echo get_site_url(); ?>/ajax-script/', {pickup:pickup,dropoff:dropoff,km:km}, function (data) {
$('#fare').html(data.fare);
//alert(data.fare);
fares = data.fare;
cityy = data.city;
actual_distances = data.actual_distance;
}, "json");
in this ajax call I am sending some parameters to the ajaxscript page, and on ajaxscript page, I called a web service and gets the response like this
$jsonData = file_get_contents("https://some_URL&pickup_area=$pickup_area&drop_area=$drop_area&distance=$km");
echo $jsonData;
this echo $jsonData send back the data to previous page.
and on previous page, You can see I Use data. to get the resposne.
Hope this helps !!
You need ajax! Something like this.
HTML
<form method='POST' action='foobar.php' id='myform'>
<input type='text' name='fname'>
<input type='text' name='lname'>
<input type='submit' name='btnSubmit'>
</form>
<div id='append'>
</div>
jQuery
var $myform = $('#myform'),
$thisDiv = $('#append');
$myform.on('submit', function(e){
e.preventDefault(); // prevent form from submitting
var $DATA = new FormData(this);
$.ajax({
type: 'POST',
url: this.attr('action'),
data: $DATA,
cache: false,
success: function(data){
$thisDiv.empty();
$thisDiv.append(data);
}
});
});
And in your foobar.php
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$query = "SELECT * FROM people WHERE fname='$fname' AND lname = '$lname' ";
$exec = $con->query($query);
...
while($row = mysqli_fetch_array($query){
echo $row['fname'] . " " . $row['lname'];
}
?>
That's it! Hope it helps
You can use jQuery ajax to accomplish it.
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //url where the form is to be submitted
data: data, //your data that is summited
success: function () {
// show the div
}
});
});
Yes, you can mix both PHP and JavaScript. I am giving you a rough solution here.
<?php
if(try to catch submit button's post value here, to see form is submitted)
{
?>
<script>
//do javascript tasks here
</script>
<?php
//do php tasks here
}
?>
Yes, This is probably the biggest use of ajax. I would use jquery $.post
$("#myForm").submit(function(e){
e.preventDefault();
var val_1 = $("#val_1").val();
var val_2 = $("#val_2").val();
var val_3 = $("#val_3").val();
var val_4 = $("#val_4").val();
$.post("mydbInsertCode.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// Form values are now available in php $_POST array in mydbInsertCode.php - put echo 'success'; after your php sql insert function in mydbInsertCode.php';
if(response=='success'){
myCheckdbFunction(val_1,val_2,val_3,val_4);
}
});
});
function myCheckdbFunction(val_1,val_2,val_3,val_4){
$.post("mydbCheckUpdated.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// put echo $val; from db SELECT in mydbSelectCode.php at end of file ';
if(response==true){
$('#myDiv').append(response);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
I have this code to insert some data that comes from a while, in a db. I'm trying to use jQuery serializearray and jQuery post together. But it seems I do some errors
$query= "SELECT * FROM barcode_prodotti";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo'
<input type="text" name="prodotto[]" class="prodotto" value="'.$row["prodotto"].'"></div>
<input type="text" name="prezzo[]" class="price" value="'.$row["prezzo"].'">
<input type="text" name="quantita[]" class="price" value="'.$row["quantita"].'">';
}
?>
<script src="js/mine.js"></script>
<button>Serialize form values</button>
</form>
<div id="results"></div>
This is my jQuery code I put in mine.js
$(document).ready(function(){
$('form').submit(function(msg) {
var mia =$(this).serialize();
$('#results').text(mia)
alert($(this).serialize()); // check to show that all form data is being submitted
$.post("testtest.php",$(this).serializeArray(),function(data){
alert(data);
});
return false; });
});
This is my php file (testtest.php)
mysql_connect("localhost","root","");
mysql_select_db("db");
$arr = $_POST;
$sql="INSERT INTO table VALUES(
'".$arr['prodotto']."',
'".$arr['quantita']."',
'".$arr['prezzo']."'
)";
$rssql = mysql_query($sql);
?>
So I the serialize is ok (i tried to assign in a div a value to see if it was ok), but I can't insert values in my db
Your INSERT query ends up looking like this after variable substitution.
INSERT INTO table VALUES( 'product', '123', '321')
If your table has exactly three columns this will work fine. Otherwise it will fail. You may wish to use this query instead.
INSERT INTO table (prodotto, prezzo, quantita ) VALUES( 'product', '123', '321')
which enumerates the columns where you want your data.
After doing an insert (and after any query) you should check for errors. This can be done with code like this.
$res = mysql_query($q);
if ($res === false) {
echo $mysql_error ();
}
Note well: The mysql_xxx() interface is being removed from PHP for a good reason: it is vulnerable to cybercriminals. Please adopt mysqli_xxx() or PDO as soon as possible.
The simplest way to do this:
<form id="myform" method="post">
<input type="text" name="prodotto" id="prodotto">
<input type="text" name="prezzo" id="prezzo">
<input type="text" name="quantita" id="quantita">
</form>
Jquery is pretty simple too:
var datastring = $("#myform").serialize();
$.ajax({
type: 'POST',
url: 'url/to/yourfile.php',
data: datastring
}).done(function(res){
var res = $.trim(res); //the ajax response. you can alert it or whatever...
});
You can parse the fields in the ajax file like that:
yourfile.php
<?php
$product = mysql_real_escape_string($_POST["prodotto"]);
$prezzo = mysql_real_escape_string($_POST["prezzo"]);
$quantity = mysql_real_escape_string($_POST["quantita"]);
//here you have the variables ready to add them as values to database
$ins = "INSERT INTO table (prodotto, prezzo, quantita ) VALUES( 'product', '123', '321')";
mysql_query($ins);
?>