ajax with multiple records to insert into database - javascript

I have a block of code which is a dynamically generated div with a form (based on array loop) that has dynamic inputs which are added by a button:
<?php foreach($tickerDisplays as $key => $ticker):?>
<form id="Items" method="post">
<label id="ItemLabel">Item 1: </label>
<input type="text" name="Items[]"><br/>
<button type="button" class="moreItems_add">+</button>
<input type="hidden" name="tickerID" id="tickerID" value="<?php echo $ticker['ticker'] ?>">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
<?php endforeach;?>
<script type="text/javascript">
$("button.moreItems_add").on("click", function(e) {
var tickerID = $('#tickerID').val();
var numItems = $("input[type='text']", $(this).closest("form")).length;
if (numItems < 10) {
var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
html += '<input type="text" name="Items[]"/><br/>';
$(this).before(html);
console.log(tickerID);
}
});
</script>
That code above is working and simply allows the '+' button to add a new input. I'm getting the input values as well as the tickerID from my hidden input in preparation for ajax submission. I'm getting what I expect from the serialized form but I have an issue.
The following code:
<script type="text/javascript">
$("#Items").submit(function(e) {
e.preventDefault();
var data = $("#Items").serialize();
console.log(data);
});
</script>
Prints this:
Items%5B%5D=this&Items%5B%5D=is&Items%5B%5D=test&tickerID=1
Which I expect. The problem is that with my ajax call to my mysql insert function, I need to insert one record for each value plus the tickerID. My sql insert is inserting into columns tickerID and content. So for the above console.log, I would need the following insert:
tickerID | content
----------------------
1 this
1 is
1 test
How can I properly pass my form data to the ajax and then do something like a foreach in order to insert multiple records?
ajax call
<script type="text/javascript">
$("#Items").submit(function(e) {
$.ajax({
type: "POST",
url: addticker.php,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
addticker.php
$tickerID = $_POST[''];
$content = $_POST[''];
$addTicker = "
INSERT INTO tickerTable (tickerID, content)
values ('$tickerID', '$content');
"
$mysqlConn->query($addTicker)

Hope this works.
$items = $_POST['Items'];
$tickerID = $_POST['tickerID'];
foreach ($items as $item){
$addTicker = "
INSERT INTO tickerTable (tickerID, content)
values ('$tickerID', '$item');
"
$mysqlConn->query($addTicker);
}

Related

How can I get the values of multiple inputs by numbered ids and insert them into MySQL [duplicate]

This question already has an answer here:
How store multiple language textfield in mysql with php?
(1 answer)
Closed 3 years ago.
I tried to create a multi insert form where you can insert as many tiles and related languages as you want by filling in a number. The display of the Titles and language works fine, but I'm not able to get the different values and insert them into db. My aim is it that every Title with its Lang gets a unique ID in the db.
<form method="POST" action="" enctype="multipart/form-data">
<table>
<tr>
<th>Title</th>
<th>Language</th>
</tr>
</table>
<input id="count" type="number" placeholder="Number of Titles">
<input type="button" id="plus" value="+">
<input type="submit" id="save" name="save" value="Save">
<script type="text/javascript">
$('#plus').on('click', function(){
var queryString = "";
var count = $('#count').val();
var i;
for(i = 1; i <= count; i++){
$('table').append('<tr><td><input name="title" type="text" placeholder="Title" id="Title_'+i+'" autocomplete="off" class="title"></td><td><select name="lang" id="Lang_'+i+'"><option value="0">Romaji</option><option value="ja">Japanese</option><option value="en">English</option><option value="de">German</option><option value="ru">Russian</option></select></td></tr>');
}
});
$('#save').on('click', function(){
var Title = $('#Title_'+i).val();
console.log(Title);
queryString ='title='+Title+'&lang='+Lang;
jQuery.ajax({
url: "action/insert.php",
data: queryString,
type: "POST",
success:function(data){
location.reload();
},
});
});
</script>
</form>
I also tried to get the value of the inputs via Jquery and send them with Jquery Ajax to the PHP file but I only get the output "undefined" when I tried to show the values in console
The insert.php
<?php
require "../config.php";
$title= $_POST['title'];
$lang= $_POST["lang"];
$sql = "INSERT INTO MyGuests (title, lang) VALUES ('".$_POST['']."', '".$_POST['']."');";
$sql .= "INSERT INTO MyGuests (title, lang) VALUES ('".$_POST['']."', '".$_POST['']."');";
$sql .= "INSERT INTO MyGuests (title, lang) VALUES ('".$_POST['']."', '".$_POST['']."')";
...
mysqli_multi_query($conn, $sql);
?>
You need to iterate over all #Title_<something> items:
var titles = $('[id^=Title_]');
titles.each(function() {
console.log(this.val());
// do other things
});
See Wildcards in jQuery selectors
and how to iterate a result of jquery selector
Javascript
<script type="text/javascript">
$(document).ready(function(){
var input = '<input type="text" placeholder="Title" autocomplete="off" class="title">';
var select = '<select><option value="0">Romaji</option><option value="ja">Japanese</option><option value="en">English</option><option value="de">German</option><option value="ru">Russian</option></select>';
var i = 1;
$('#plus').on('click', function(){
var tr = $('tr');
var td1 = $('td');
var td2 = $('td');
td1.append($(input).attr('name', 'myguest['+i+'][title]').attr('id','Title_'+i));
td2.append($(select).attr('name', 'myguest['+i+'][lang]').attr('id','Lang_'+i));
tr.append(td1).append(td2);
$('table').append(tr);
i++;
});
});
</script>
PHP side
<?php
foreach($_POST['myguest'] as $guest) {
$sql = "INSERT INTO MyGuests (title, lang) VALUES ('".$guest['title']."', '".$_POST['lang']."');";
mysqli_query($conn, $sql);
}
don't forget to escape the values from post

Ajax autocomplete doesn't return correct value

I have an ajax autocomplete where it returns the full name of the user. However, when there are instances where some names or values are the same, it doesn't return the correct value. Rather, it returns the first value in the dropdown. Even if it has 4 same occurences, it still returns the first value.
When I click Stannis Arryn Baratheon, it returns Stannis Targaryen Baratheon.
Here is my php code (sql/php code; ad.php):
<?php
include('config.php');
if($_POST)
{
if($_POST['search_keyword'])
{
$similar = mysql_real_escape_string($_POST['search_keyword']);
$result=mysqli_query($conn, "SELECT * FROM person WHERE (firstName like '" . $_POST["search_keyword"] . "%' OR lastName like '" . $_POST["search_keyword"] . "%') AND residentOrNot = 'Yes' ");
if (mysqli_num_rows($result) > 0) {
while($row=mysqli_fetch_array($result))
{
//$name = $row['fullname'];
//$copiedname = $row['fullname'];
//$b_name= '<strong>'.$similar.'</strong>';
//$final_name = str_ireplace($similar, $b_name, $name);
?>
<div class="show" align="left">
<span class="returnName"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
<span class="returnID" style="display:none"><?php echo $row['idPerson'];?></span>
</div>
<?php
}
}
else {
?>
<div class="show" align="left">
<span class="returnMessage">No matching records found.</span>
</div>
<?php
}
}
mysqli_close($conn);
}
?>
HTML input form:
<form method="post" action="try.php" name="try">
<div class='web'>
<input type="text" class="search_keyword" id="search_keyword_id" placeholder="Search" />
<input type="hidden" name="resID" id="resID"/>
<div id="result"></div>
<input type="submit" name="try" value="Submit">
</div>
AJAX/JS/JQUERY CODE (i think this is where the problem occurs):
<script type="text/javascript">
$(function(){
$(".search_keyword").keyup(function()
{
var search_keyword_value = $(this).val();
var dataString = 'search_keyword='+ search_keyword_value;
if(search_keyword_value!='')
{
$.ajax({
type: "POST",
url: "ad.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}
return false;
});
jQuery("#result").on("click", function(e)
{
/*var $clicked = $(e.target);
var $name = $clicked.find('.returnName').html();
var decoded = $("<div/>").html($name).text();
$('#search_keyword_id').val(decoded);
var $clicked = $(e.target);
var $id = $clicked.find('.returnID').html();
var id = $("<div/>").html($id).text();
$('#resID').val(id);
*/
$name = $('span.returnName',this).html();
$name = $("<div/>").html($name).text().toString();
$('#search_keyword_id').val($name);
$id = $('span.returnID',this).html();
$id = $("<div/>").html($id).text().toString();
$('#resID').val($id);
});
jQuery(document).on("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search_keyword")){
jQuery("#result").hide();
}
});
});
</script>
It really returns the first value even if I click the second or third or fourth value. Where did I go wrong in my code? Please help me. Thank you so much!
Your code is currently collecting all elements with class returnName in #result, and by calling .html() on that collection jQuery will only return the html of the first element found. The same goes for the your returnID search. This is why you are only getting the first returned entry.
Modify your #result click handler to only trigger for elements with class show, since that is the element that will contain your data.
jQuery("#result").on("click", ".show", function(e){
Then all you have to do is search for the elements with class returnName and returnID and call .text().
var showName = $('.returnName',this).text();
var showId = $('.returnID',this).text();
$('#search_keyword_id').val(showName);
$('#resID').val(showId);
So all together
jQuery("#result").on("click", ".show", function(e){
var showName = $('.returnName',this).text();
var showId = $('.returnID',this).text();
$('#search_keyword_id').val(showName);
$('#resID').val(showId);
});
Though note there are probably better ways of returning your data, and utilizing it rather than transporting it in html elements. For example use data-* attributes instead of using a separate span element to contain your id.
Another option is to use jQuery-UI's autocomplete that does most of the client side work for you and just return the raw data in JSON format from your php script.
In your php code, change this:
<div class="show" align="left">
<span class="returnName"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
<span class="returnID" style="display:none"><?php echo $row['idPerson'];?></span>
</div>
With this:
<div class="show" align="left">
<span class="returnName" data-id="<?php echo $row['idPerson'];?>"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
</div>
And your new jquery function:
jQuery("#result").on("click","'.returnName" function(e)
{
var choosenName = $(this).html();
var choosenId = $(this).data('id');
$('#search_keyword_id').val(choosenName );
$('#resID').val(choosenId );
});

Why I can not receive data from jQuery (PHP)?

I have a PHP form:
<form action="" method="post" id="CheckBoxForm">
foreach ( $results as $result ) :
<input type="checkbox" class="chk" id="check_list[]" value="'.($result->meta_value).'"/>
<input type="submit" name="submit" value="Submit"/>
</form>
I take values from it in js file:
jQuery('#CheckBoxForm').on('submit', function(e) {
var chkArray = [];
var CheckBoxForm=jQuery(this).serialize();
alert(CheckBoxForm);
jQuery(".chk:checked").each(function() {
chkArray.push($(this).val());
});
var selected;
selected = chkArray.join(',') + ",";
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: selected,
success:function(data){
jQuery("#feedback_country").html(data);
}
});
return false;
});
});
If I alert selected it gives me list of values. So script has initialized and took data.
At the end of the script it receive feedback data html(data) and send it back to initial php file.
PHP file which take request from js file (POST REQUEST) has such code:
foreach($_POST['check_list'] as $selected){
echo $selected."</br>";
}
And it send back 0. I can't understand what is wrong.
You have too much extra code in your JavaScript that is unneeded. You don't need those chkArray or selected variables.
jQuery('#CheckBoxForm').on('submit', function(e) {
var CheckBoxForm = jQuery(this).serialize();
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: CheckBoxForm,
success:function(data){
jQuery("#feedback_country").html(data);
}
});
return false;
});
That should be all you need. serialize() will take all the values from the form and create a string in the correct format to be sent to your PHP script.
Note: Your HTML is incorrect, your form should look like this:
<form action="" method="post" id="CheckBoxForm">
<?php foreach($results as $result): ?>
<input type="checkbox" class="chk" name="check_list[]" value="<?=$result->meta_value?>"/>
<?php endforeach; ?>
<input type="submit" name="submit" value="Submit"/>
</form>
You want to use the name attribute, not id on your checkboxes.
Your problem is that you are sending a single string instead of key - value pairs:
selected = chkArray.join(',') + ",";
...
data: selected,
Although I would not recommend building the query string manually - serialize() will take care of the correct escaping - you can send your check-list string like:
data: {check_list: selected},
Edit: Now in php you will have a $_POST['check_list'] variable but that is a list in a comma-separated string. So to convert it into an array and loop over it, you would need something like:
$arr = explode(',', $_POST['check_list']);
foreach ($arr as $selected) {
echo $selected."</br>";
}

jQuery and JSON: loop json array

I have an array in database:
a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}
So I unserialize with php and then encode it with json, code looks like following:
$unwp = unserialize('a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}');
print_r ($unwp);
echo json_encode($unwp);
I get this on the page:
Array ( [1] => 1993 [2] => 1994 [3] => 1995 [4] => 1996 ) {"1":"1993","2":"1994","3":"1995","4":"1996"}
I need to loop it somehow with jQuery? so i can get 1993,1994,1995,1996 and so on.
I was testing jQuery.getJSON(), but cant figure out how exactly to use it?
All code together on the page:
<?php
$array = $_POST['inputarray'];
$str = serialize($array);
print $str . "\n";
$unwp = unserialize('a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}');
print_r ($unwp);
echo json_encode($unwp);
?>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
jQuery(function ($) {
// Add children input fields
var childBlock = $('.block');
var countChildren = $('div.block div.row').size() + 1;
$('#addChild').live('click', function (e) {
e.preventDefault;
$('<div class="row"><input type="text" name="inputarray['+countChildren+']" id="inputarray'+countChildren+'" placeholder="inputarray['+countChildren+']">Delete</div>').appendTo(childBlock);
countChildren++;
});
$('#deleteChild').live('click', function (e) {
e.preventDefault();
if (countChildren > 2) {
$(this).parents('div.row').remove();
countChildren--;
var counter = 1;
$('input[name^="inputarray"]').each(function () {
$(this).attr('name', 'inputarray[' + counter + ']');
$(this).attr('placeholder', 'inputarray[' + counter + ']');
$(this).attr('id', 'inputarray' + counter);
counter++;
});
}
});
})(jQuery);
</script>
<form action="" method="post">
<div class="block">
<div class="row"><input type="text" name="inputarray[1]" placeholder="inputarray[1]"></div>
<input type="hidden" value="<?php echo $str; ?>">
</div>
<input type="submit">
</form>
Add a child
Thank you!
This could be done easily in PHP. Since I don't see any handlers for submit() or click() or anything that could suggest an ajax request.
And you also have the php in the same file, so why not simply loop with PHP and produce what you need?
echo "<select name='year'>";
foreach($unwp as $year) {
echo "<option value='{$year}'>{$year}</option>";
}
echo "</select>";
The above snippet will product exactly what you need.
Example
Edit
You're trying to generate a <select> right? If not, let me know so I can modify as required.
I would change
echo json_encode($unwp);
to
echo "<script> var fromPhP = ".json_encode($unwp). "</script>;
in this way you get json in variable and I saw you are using jquery so i would use $.each to loop it:
$.each(fromPhP ,function(index,item){
console.log(index,item);
});
Use $.getJSON like this:
$.getJSON("scriptname.php", function(data) {
html = '';
$.each(data, function(i, el) {
html += '<div class="block">' +
'<div class="row"><input type="text" name="inputarray['+i+']" placeholder="inputarray['+i+']"></div>' +
'<input type="hidden" value="'+el+'">');
});
$("form > div").delete();
$("form").prepend(html);
});

dynamically updating select boxes with php mysql jquery ajax

I am trying to populate an initial customer select box with results from PDO MySql via PHP. Then I would like the second contact select box to update with additional information related to what was chosen in the first box. I can't get the second script to work. I think the problem is in my ajax script because the PHP scripts work fine when ran on there own.
The Primary Script
<html>
<head>
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.4.custom.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#contact").change(function(){
var cid = $("#cid").val();
$.ajax({
type:"post",
url:"contact.php",
data:"cid="+cid,
success: function(data) {
$("#contact").html(data);
}
});
});
});
</script>
</head>
<body>
Campaign :
<select name="customer" id="customer">
<option>-Select a Customer-</option>
<?php
include ("function.php");
include("connect.php");
$id = $_SESSION['profile']['id'];
foreach($db->query("SELECT * FROM customers WHERE pid = '$id'") as $row) {
echo "<option value=" . $row['id'] . ">" . $row['name'] . "</option>";
}
?>
</select>
<select name="contact" id="contact">
<option>-Select a Contact-</option>
</select>
</body>
</html>
The Contact script
include("connect.php");
$cid = $_POST["cid"];
foreach($db->query("SELECT * FROM contact WHERE cid = '$cid'") as $row) {
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
Maybe your second function should start on #customer change
I see you used the contact select in ajax not customer as you described. However the code you wrote, you used the contact selector with change event, But the contact select box contain only one value, How can it change ??
<select name="contact" id="contact">
<option>-Select a Contact-</option>
</select>
The previous select should has more than option to can change. Or I think you mean the #customer instead contact as following:-
$("#customer").change(function(){
// your code;
});
Why not just encode a JSON response with the ids and names?
foreach($db->query("SELECT * FROM contact WHERE cid = '$cid'") as $row) {
$arr[] = array("id" => $row['id'], "name" => $row['name']);
}
echo json_encode($arr);
Then in your ajax response, you could do
$(document).ready(function () {
$("#customer").change(function () {
var cid = $("#customer").val();
$.ajax({
type: "post",
url: "contact.php",
data: {cid: cid},
success: function (data) {
var options = [];
$.each(data, function () {
options.push('<option value="' + this.id + '">' + this.name + '</option>');
});
$("#contact").html(options.join(""));
}
});
});
});

Categories