using serializeArray, trying to insert from ajax multiple inputs, each with ID - javascript

I'm trying to submit an ajax call for a form where I have added functionality to dynamically add inputs to a form. My forms are created based on an array loop so sometimes I just have one form, sometimes more.
Regardless, I'm able to dump the proper input values from each form with a console on the button, but I'm getting a 500 error on the ajax submit.
One issue is that if I have 4 inputs in the form, I'm dumping all 4 and then my one hidden input value 'tickerID', but I'm calling a sql insert where I need to insert each value with that hidden input value.
My console log for data right now is this:
but I need to insert these as
insert into ticker_content (ticker_id, content)
values (1, 'one'), (1, 'two');
If that makes sense.
Here's my addticker.php that's being called for the insert:
$items = $_POST['Items'];
$tickerID = $_POST['tickerID'];
foreach ($items as $item){
$addTicker = "
INSERT INTO ticker_content (tickerID, content)
values ('$tickerID', '$item');
"
$mysqlConn->query($addTicker);
}
So basically for every Items[] value, I need to insert with the same hidden field.
Here's my form and JS code for reference. The first JS block is mainly for the functionality of dynamically adding inputs, but the last JS block is the ajax using serializeArray();
<?php foreach($tickerDisplays as $key => $ticker):?>
<form id="Items" method="post">
<label id="ItemLabel">Item 1: </label>
<input type="text" name="Items[]"><br/> <!--form starts with one input-->
<button type="button" class="moreItems_add">+</button> <!--button dynamically adds input, up to 10 per form-->
<input type="hidden" name="tickerID" id="tickerID" class="tickerIdClass" value="<?php echo $ticker['ticker'] ?>"><!--hidden input used for tickerID-->
<input type="submit" name="saveTickerItems" value="Save Ticker Items"> <!--submit button-->
</form>
<?php endforeach;?>
<!-- This is the functionality for each form to click the '+' button and create new inputs -->
<script type="text/javascript">
$("button.moreItems_add").on("click", function(e) {
var tickerID = $(this).closest('form').find('.tickerIdClass').val(); //get value of hidden input for form
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>
<!-- This is the ajax call to send all filled out and created inputs from form along with the hidden input -->
<script type="text/javascript">
$("#Items").submit(function(e) {
e.preventDefault();
var data = $("#Items").serializeArray();
console.log(data);
$.ajax({
type: "POST",
url: "addticker.php",
data: $("#Items").serializeArray(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
</script>

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

Related

How to submit form when any value selected from populated textbox using javascript or jQuery without clicking submit button

search.php
In this form, when we type something in textbox, matching words are fetched from api_search.php page and displayed as seen in attached screenshot.
<form role="form" id="frm_search" name="frm_search" method="POST" action="./api_search_p.php" enctype="multipart/form-data" >
<script type="text/javascript">
$(function()
{
$( "#txt_itemname" ).autocomplete({
source: '../user/api_search.php'
});
});
</script>
<input type="text" id="txt_itemname" name="txt_itemname" class="form-control" required data-validation-required-message="Please enter something here">
<button type="submit" class="btn btn-warning"><i class='fas fa-search'></i> </button></span>
</form>
api_search.php
Textbox on search.php is populated from API result data from this page.
-- API data are coming using curl in $result array --
$json = json_decode($result, true);
$arr_searchTerm = array();
if (is_array($json) && !empty($json))
{
foreach ($json as $key1 => $level1)
{
if (is_array($level1) && !empty($level1))
{
foreach ($level1 as $key2 => $level2)
{
array_push($arr_searchTerm, $level2['TITLE']);
}
}
}
}
echo json_encode($arr_searchTerm);
Currently need to click submit button to submit the form. But I want to do so when any word from fetched result is selected / clicked then form should be submitted immediately without clicking submit button.
I tried onselect="this.form.submit()" & onchange="this.form.submit()" with textbox but form is not submitted on any of javascript events.
Please let me know how can I make this working as expected.
Screenshot
You can use select function in your code
$( "#txt_itemname" ).autocomplete({
source: '../user/api_search.php',
select: function(e, ui){
this.value = ui.item.value;
this.form.submit();
}
});
You can try this way. in this case, you can make your API call every time someone inserts something. This means every single letter will make a call
document.querySelector("#txt_itemname").addEventListener('input',(e)=>{
...
})
and additionally, if you do it as an API try to look at this too http_responses with PHP

Using hidden inputs to POST JavaScript function result

I have a single form input on my homepage userinput. The homepage also contains a JavaScript function that uses that userinput value to calculate a result.
<form action="/run.php" method="POST" target="_blank">
<input type="hidden" id="idg" value="<?php echo $rand ?>"> // gets random url, can be ignored
<input type="text" name="userinput" id="userinput">
<button type="submit" onclick="calcResult();">Go!</button>
</form>
<script>
function calcResult() {
var userinput = document.getElementById('userinput').value;
var result = userinput + 10; // want to POST result in a hidden input field w/ form
</script>
I'm trying to find a way in which a user can enter their input, submit the form, the JavaScript takes that userinput and calculates a result, then that result is POST'ed along with the userinput in the form.
The problem I can forsee with this method is that:
The JavaScript function needs the userinput before it can calculate the result. However, the only way to get the userinput is to submit the form, which means the form data will be POSTed before the JavaScript result is returned.
My attempted solution(s):
I've been attempting to use AJAX (Unable to access AJAX data [PHP]) and have been consistently running into issues with that.
I was wondering whether it's possible to use a button (type="button"), instead of a submit (type="submit") for the form. Then just use that button to call the JS function, then (somehow) submit the form (with the JS function result) after the JS function has completed? (either with plain JS or jQuery).
there are multiple approaches to do this,
i'm gonna use jquery here instead of pure javascript to simplify it
[without submission] you may check the event change
$('#userinput').change(function (e) {
// make some calculation
// then update the input value
});
[with form submission] you will disable the submission using the object preventDefault inside the submit event
$('#userinput').submit(function (e) {
e.preventDefault();
// make some calculation
// then update the input value
// your ajax goes here OR resubmission of your form
// to resubmit the form
$(this).submit();
});
What you will find useful in this scenario is event.preventDefault();
function calcResult(e) {
// Prevent the default action of the form
e.preventDefault();
var userinput = document.getElementById('userinput').value;
var result = userinput + 10;
// Do whatever else you need to do
// Submit the form with javascript
document.getElementById("myForm").submit();
}
I believe this is what you are looking for. A way of having the information computed over PHP, without a page request. This uses a form and then serializes the data, then transmits it to PHP and displays the result from run.php.
Note:
I did change your id to a name in the HTML so the code would serialize properly. I can change this per request.
index.php
$rand = rand(10,100);
?>
<form action="javascript:void(0);" id="targetForm">
<input type="hidden" name="idg" value="<?php echo $rand ?>">
<input type="text" value="12" name="userinput" id="userinput">
<button onclick="ready()">Go!</button>
</form>
<div id="result"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function ready() {
$.post('run.php', $('#targetForm').serialize(), function (data) {
$("#result").html(data);
})
}
</script>
run.php
<?php
echo floatval($_POST['userinput']) * floatval($_POST['idg']);
?>
Nowhere in your question is there any indicator that your task requires AJAX. You're just trying to change an input value right when you submit. AJAX is not needed for that.
First, attach an onsubmit event handler to your form instead of using an onclick attribute on your button. Notice, we are not stopping the form from submitting with return false as we still want the form to submit.
For convenience, let's add an ID to your form and let's add a hidden input field to store the calculated value.
(Side-remark: you don't need to use document.getElementById(ID) if the ID is a string with no dashes i.e. document.getElementById('userinput') can be shortened to just userinput )
<form action="/run.php" method="POST" target="_blank" id="theform">
<input type="hidden" id="idg" value="<?php echo $rand ?>">
<input type="text" name="userinput" id="userinput">
<input type="hidden" name="hiddeninput" id="hiddeninput">
<button type="submit">Go!</button>
</form>
<script>
// this will be called right when you submit
theform.onsubmit = function calcResult() {
// it should update the value of your hidden field before moving to the next page
hiddeninput.value = parseInt(userinput.value, 10) + 10;
return true;
}
</script>
One way is by onSubmit
<form action="/run.php" method="POST" onSubmit="return calcResult()">
<input type="hidden" id="idg" value="<?php echo $rand ?>"> // gets random url, can be ignored
<input type="text" name="userinput" id="userinput">
<button type="submit" onclick="calcResult();">Go! </button>
</form>
And when you return true then only form will submit.
<script>
function calcResult() {
var userinput = document.getElementById('userinput').value;
var result = userinput + 10; // want to POST result in a hidden input field w/ form
return true;
}
</script>

Automatically update another page without refreshing

I have this problem on how I could automatically update my webpage without refreshing. Could someone suggest and explain to me what would be the best way to solve my problem? Thanks in advance
add.php file
In this php file, I will just ask for the name of the user.
<form id="form1" name="form1" method="post" action="save.php">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<input type="submit" name="add" id="add" value="add"/>
</form>
save.php In this file, I will just save the value into the database.
$firstname=isset($_POST['firstname'])? $_POST['firstname'] : '';
$lastname=isset($_POST['lastname'])? $_POST['lastname'] : '';
$sql="Insert into student (sno,firstname,lastname) values ('','$firstname','$lastname')";
$sql=$db->prepare($sql);
$sql->execute();
studentlist.php In this file, i want to display the name I enter
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
$sql->execute();
$output="The List of students <br></br>";
while($result=$sql->fetch(PDO::FETCH_ASSOC))
{
$output.="".$result['firstname']." ".$result['lastname']."<br></br>";
}
Problem
When the two pages is open, I need to refresh the studentlist.php before i can see the recently added data.
thanks :D
You'll want to use ajax and jquery. Something like this should work:
add.php
add to the head of the document:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){//loads the information when the page loads
var saveThenLoad = {
url: "save.php",//the file sending data to
type: 'POST',//sends the form data in a post to save.php
dataType: 'json',
success : function(j) {
if(j.error = 0){
$("#student_info").html(j.info);//this will update the div below with the returned information
} else {
$("#student_info").html(j.msg);//this will update the div below with the returned information
}
}
}
//grabs the save.submit call and sends to the ajaxSubmit saveThenLoad variable
$("#save").submit(function() {
$(this).ajaxSubmit(saveThenLoad);
return false;
});
//grabs the submit event from the form and tells it where to go. In this case it sends to #save.submit above to call the ajaxSubmit function
$("#add").click(function() {
$("#save").submit();
});
});
</script>
<!-- put this in the body of the page. It will wait for the jquery call to fill the data-->
<div id="student_info">
</div>
I would combine save and studentlist into one file like this:
$return['error']=0;
$return['msg']='';
$firstname=isset($_POST['firstname'])? $_POST['firstname'] : '';
$lastname=isset($_POST['lastname'])? $_POST['lastname'] : '';
$sql="Insert into student (sno,firstname,lastname) values ('','$firstname','$lastname')";
$sql=$db->prepare($sql);
if(!$sql->execute()){
$return['error']=1;
$return['msg']='Error saving data';
}
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
if(!$sql->execute()){
$return['error']=1;
$return['msg']='Error retrieving data';
}
$output="The List of students <br></br>";
while($result=$sql->fetch(PDO::FETCH_ASSOC))
{
$output.="".$result['firstname']." ".$result['lastname']."<br></br>";
}
$return['$output'];
echo json_encode($return);
Does this need to be in three separate files? At the very least, could you combine add.php and studentlist.php? If so, then jQuery is probably the way to go. You might also want to use some html tags that would make it easier to dynamically add elements to the DOM.
Here's the combined files:
<form id="form1" name="form1">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<input type="submit" name="add" id="add" value="add"/>
</form>
The List of students <br></br>
<ul id="student-list">
<?php
//I assume you're connecting to the db somehow here
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
$sql->execute();
while($result=$sql->fetch(PDO::FETCH_NUM)) //this might be easier to output than an associative array
{
//Returns will make your page easier to debug
print "<li>" . implode(" ", $result) . "</li>\n";
}
?>
</ul>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function(){
$('#form1').submit(function(event){
event.preventDefault();
//submit the form values
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
//post them
$.post( "test.php", { firstname: firstname, lastname: lastname })
.done( function(data) {
//add those values to the end of the list you printed above
$("<li>" + firstname + ' ' + lastname + "</li>").appendTo('#student-list');
});
});
});
</script>
You might want to do some testing in in the $.post call above to make sure it was handled properly. Read more about that in the docs.
If you really need three files, then you'll might need to use ajax to do some sort of polling on studentlist.php using setTimeout to see if you have any new items.
The cheap-way is using a meta-refresh to refresh your page (or use JavaScript setInterval and ajax).
The more expensive way is having a Realtime JavaScript application. Look at Socket.IO or something like that.

jQuery: How to submit an array in a form

I have the following form. Each time the users clicks add_accommodation I want to add to an array that I will return to the end point (http://server/end/point).
<form action="http://localhost:3000/a/b/c" method="post">
<div>
<input type="hidden" id="Accommodation" name="accommodation"><div>
</div>
</form>
<div id="accommodation_component">
<div>
<label for="AccommodationType">Type:</label>
<input type="number" step="1" id="accommodationType" name="accommodation_type" value="0">
</div>
<div>
<button type="button" id="add_accommodation">Add Accommodation</button>
</div>
</div>
<script>
$( document ).ready(function() {
$('#add_accommodation').click(function() {
make_accommodation(this);
});
});
function make_accommodation(input) {
var value = {
type : $("#AccommodationType").val(),
};
var accommodation = $('#Accommodation').attr('id', 'accommodation');
accommodation.push(value);
console.log(accommodation);
}
</script>
At my end point I want the result to be and array (accommodation = [{1},{2},{3},{4}]). How can I do this?
Give the form an id, and just append a new hidden(?) input that has a name that has [] at the end of it, it will send the values as an array to the server.
HTML
<form id="myform" ...>
Javascript
function make_accommodation(){
var newInput = $("<input>",{
type:"hidden",
name:"accommodation[]",
value: {
type: $("#AccommodationType").val()
}
});
$("#myform").append(newInput);
}
Also you list the output as [1,2,3,4] but your code shows you setting the value as an object with a property type and setting it to the value of the accommodation input, i am going to assume that was a mistake. If I am mistaken just modify the value property in the code above.
Also in your code you change the id of the input, not sure why you were doing that as it serves no purpose and would have made your code error out so i removed it.
EDIT
Since you are wanting to send an array of objects, you will have to JSON.stringify the array on the client end and decode it on the server end. In this one you do not need multiple inputs, but a single one to contain the stringified data.
var accommodationData = [];
function make_accommodation(){
accommodationData.push({
type: $("#AccommodationType").val()
});
$("#accommodation").val( JSON.stringify(accommodationData) );
}
Then on the server you have to decode, not sure what server language you are using so i am showing example in PHP
$data = json_decode( $_POST['accommodation'] );
If you are using jQuery's ajax method you could simplify this by sending the array data
jQuery.ajax({
url:"yourURLhere",
type:"post"
data:{
accomodation:accommodationData
},
success:function(response){
//whatever here
}
});
Add antorher hidden field in form
<input type="hidden" name="accommodation[]"> // click1
<input type="hidden" name="accommodation[]"> // click2
...
<input type="hidden" name="accommodation[]"> // clickn
Then when you submit form on server you will have array of accommodation.
JS part :
function make_accommodation() {
$(document.createElement('input'))
.attr('type', 'hidden')
.attr('name', 'accommodation[]')
.val($("#AccommodationType").val())
.appendTo('form');
}
on server(PHP) :
print_r($_POST['accommodation']);
Since you're using jQuery you can create a function which creates another hidden field, after clicking on the button
<div id='acommodation-wrapper'></div>
<button type="button" id="add_accommodation" onclick="addAnother()">Add Accommodation</button>
<script type="text/javascript">
function addAnother(){
var accWrapper = $('#accommodation-wrapper');
var count = accWrapper.children().length;
var div = "<input type=\"hidden\" class=\"accommodation-"+count+"\" name=\"accommodation["+count+"]\"></div>";
accWrapper.append(div);
}
</script>

Separating variables for SQL insert using PHP and JavaScript

A grid table is displayed via PHP/MySQL that has a column for a checkbox that the user will check. The name is "checkMr[]", shown here:
echo "<tr><td>
<input type=\"checkbox\" id=\"{$Row[CONTAINER_NUMBER]}\"
data-info=\"{$Row[BOL_NUMBER]}\" data-to=\"{$Row[TO_NUMBER]}\"
name=\"checkMr[]\" />
</td>";
As you will notice, there is are attributes for id, data-info, and data-to that are sent to a modal window. Here is the JavaScript that sends the attributes to the modal window:
<script type="text/javascript">
$(function()
{
$('a').click(function()
{
var selectedID = [];
var selectedBL = [];
var selectedTO = [];
$(':checkbox[name="checkMr[]"]:checked').each(function()
{
selectedID.push($(this).attr('id'))
selectedBL.push($(this).attr('data-info'))
selectedTO.push($(this).attr('data-to'))
});
$(".modal-body .containerNumber").val( selectedID );
$(".modal-body .bolNumber").val( selectedBL );
$(".modal-body .toNumber").val( selectedTO );
});
});
</script>
So far so good. The modal retrieves the attributes via javascript. I can choose to display them or not. Here is how the modal retrieves the attributes:
<div id="myModal">
<div class="modal-body">
<form action="" method="POST" name="modalForm">
<input type="hidden" name="containerNumber" class="containerNumber" id="containerNumber" />
<input type="hidden" name="bolNumber" class="bolNumber" id="bolNumber" />
<input type="hidden" name="toNumber" class="toNumber" id="toNumber" />
</form>
</div>
</div>
There are additional fields within the form that the user will enter data, I just chose not to display the code. But so far, everything works. There is a submit button that then sends the form data to PHP variables. There is a mysql INSERT statement that then updates the necessary table.
Here is the PHP code (within the modal window):
<?php
$bol = $_POST['bolNumber'];
$container = $_POST['containerNumber'];
$to = $_POST['toNumber'];
if(isset($_POST['submit'])){
$bol = mysql_real_escape_string(stripslashes($bol));
$container = mysql_real_escape_string(stripslashes($container));
$to = mysql_real_escape_string(stripslashes($to));
$sql_query_string =
"INSERT INTO myTable (bol, container_num, to_num)
VALUES ('$bol', '$container', '$to')
}
if(mysql_query($sql_query_string)){
echo ("<script language='javascript'>
window.alert('Saved')
</script>");
}
else{
echo ("<script language='javascript'>
window.alert('Not Saved')
</script>");
}
?>
All of this works. The user checks a checkbox, the modal window opens, the user fills out additional form fields, hits save, and as long as there are no issues, the appropriate window will pop and say "Saved."
Here is the issue: when the user checks MULTIPLE checkboxes, the modal does indeed retrieve multiple container numbers and I can display it. They seem to be already separated by a comma.
The problem comes when the PHP variables are holding multiple container numbers (or bol numbers). The container numbers need to be separated, and I guess there has to be a way the PHP can automatically create multiple INSERT statements for each container number.
I know the variables need to be placed in an array somehow. And then there has to be a FOR loop that will read each container and separate them if there is a comma.
I just don't know how to do this.
When you send array values over HTTP as with [], they will already be arrays in PHP, so you can already iterate over them:
foreach ($_POST['bol'] as $bol) {
"INSERT INTO bol VALUES ('$bol')";
}
Your queries are vulnerable to injection. You should be using properly parameterized queries with PDO/mysqli
Assuming the *_NUMBER variables as keys directly below are integers, use:
echo '<tr><td><input type="checkbox" value="'.json_encode(array('CONTAINER_NUMBER' => $Row[CONTAINER_NUMBER], 'BOL_NUMBER' => $Row[BOL_NUMBER], 'TO_NUMBER' => $Row[TO_NUMBER])).'" name="checkMr[]" /></td>';
Then...
$('a#specifyAnchor').click(function() {
var selectedCollection = [];
$(':checkbox[name="checkMr[]"]:checked').each(function() {
selectedCollection.push($(this).val());
});
$(".modal-body #checkboxCollections").val( selectedCollection );
});
Then...
<form action="" method="POST" name="modalForm">
<input type="hidden" name="checkboxCollections" id="checkboxCollections" />
Then...
<?php
$cc = $_POST['checkboxCollections'];
if (isset($_POST['submit'])) {
foreach ($cc as $v) {
$arr = json_decode($v);
$query = sprintf("INSERT INTO myTable (bol, container_num, to_num) VALUES ('%s', '%s', '%s')", $arr['BOL_NUMBER'], $arr['CONTAINER_NUMBER'], $arr['TO_NUMBER']);
// If query fails, do this...
// Else...
}
}
?>
Some caveats:
Notice the selector I used for your previous $('a').click() function. Do this so your form updates only when a specific link is clicked.
I removed your mysql_real_escape_string functions due to laziness. Make sure your data can be inserted into the table correctly.
Make sure you protect yourself against SQL injection vulnerabilities.
Be sure to test my code. You may have to change some things but understand the big picture here.

Categories

Resources