Insert data from multiple text boxes into sql via ajax - javascript

Not sure of the best way do this.
On my page I have the following (which pulls a list of custom questions from my database set by a user)
PHP PAGE THAT SHOWS THE QUESTIONS / COVER LETTER TEXT AREA
$questions = $this->db->get_where("applicationquestions",
["opportunity_id" => $contact->id]);
$questionsfound = $questions->num_rows();
$questions = $questions->result();
<? foreach ($question as $q):?>
<div class="form-group">
<label for="<?echo $q->id;?>" class="control-label"><? echo $q->label;?
>:</label>
<input type="text" class="form-control" id="<?echo $q->id;?>" name="<?echo $q->id;?>">
</div>
<?endforeach;?>
and using ajax / javascript i am passing information via POST
** THE JS **
$("#apply").click(function(e) {
e.preventDefault();
var oppid = "<?echo $opportunity->id;?>";
$.ajax({
url:
"https://MYSITEHERE/submitapplication",
method: "POST",
data: {oppid:oppid}}); });
What i am wondering is the best way to get then insert the questions id and the users answer into my database through this method.
** Submit Application File / Function **
public function submitapplication() {
$insert['opportunity_id']= $this->input->post('oppid');
$insert['user_id']= is_user_logged_in();
$insert['time']= time();
$insert['coverletter']= $this->input->post('coverletter');
$this->db->insert("applications", $insert);
// here i would need it to submit the answers from the question textboxes into the table applicationanswers along with the question id
}
HTML THAT IS DISPLAYED AFTER PHP HAS LISTED QUESTION FIELDS
<form id="applyform" class="">
<div class="row">
<div class="col-md-6 col-xs-12">
<label>Cover Letter</label>
<textarea class="form-control" id="coverletter" name="coverletter" rows="7" placeholder="Start typing a cover letter"></textarea>
<div class="form-group">
<label for="1" class="control-label">Have you sold web design before?:
</label>
<input type="text" class="form-control" id="1">
</div>
<div class="form-group">
<label for="2" class="control-label">Do you like monkeys?:</label>
<input type="text" class="form-control" id="2">
</div>
</div> </div>
</form>

If you are using more than one item in your form, I would suggest using
var data = $('form').serialize();
This will pass all of the form values to your php script and then you can use php to insert them.
$("#apply").click(function(e) {
e.preventDefault();
var oppid = "<?echo $opportunity->id;?>";
var data = $('form').serialize();
$.ajax({
url:
"https://MYSITEHERE/submitapplication",
method: "POST",
data: {formdata:data}}); });
You would then just parse the data in your php

Related

AJAX form submitting the wrong row from dynamically generated rows of data

I am currently reading data from a database and displaying the returned data in a table. One column contains the ID of each row, which I pass to a modal like this:
Edit
The modal gets data from another php file I included, using:
require('user_info.php');
The right data for each row is displayed on the modal, as I 'GET' the id passed into the modal, and query the database and display the returned info on a form on the modal. I have been careful to use classes in identifying the form elements, as I intend to submit the form using AJAX. Part of the form is:
<form method="POST" action="">
<div class="row form-group">
<label>User ID</label>
<div class="col-sm-12">
<input name="userid" type="text" class="form-control userid" value="<?php echo $prow['id'];?>">
</div>
<div class="col-md-6">
<label>Name</label>
<input name="name" type="text" class="form-control" value="<?php echo $prow['fullname'];?>">
</div>
<div class="col-md-6">
<label>Folder</label>
<input name="folder" type="text" class="form-control" value="<?php echo $prow['folder'];?>">
</div>
<input type="submit" class="btn form-control modify_user_info" value="Submit Modification">
</div>
The problem now is, no matter which row on the original table I edit and submit through a modal, it is the first row of the table that attempts to get edited. The modals display the right information based on the row selected, but submitting the form on the modal always returns the data on the first row to the php file handling the form submission.
Here's my javascript:
<script>
$(document).ready(function () {
$('.modify_user_info').click(function (e) {
e.preventDefault();
var userid = $('.userid').val();
var email = $('.email').val();
$.ajax
({
type: "POST",
url: "modify_user_info.php",
data: {
"userid": userid,
"email": email,
},
success: function (data) {
$('.result').html(data);
}
});
});
});
PS: Submitting the form without AJAX works fine.
Edit: I need to add that printing the id submitted by the form shows that it is the first row of the table that is submitted, not the selected row.
Change your href tag and modal like this
i hope you are using a foreach loop
then change your href tag and target modal like this
View
and your target modal as
<div style="" class="modal fade mymodal" id="user_id_<?php echo $row['id'];?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">

Cannot post dropdown list selected value to server using $.ajax

This is my first development using JQuery (jquery-3.0.0.min.js) and Javascript. I am creating a simple web form connected to a database via Web API.
The form includes some input text tags and two select tags.
I am posting the form data using $.ajax method.
When I submit the form the values in the textboxes are correctly posted to the server but the selected values always result null.
Here is a piece of the HTML code:
<form name="modulo" id="modulo">
....
<div class="field">
<label id="mailLbl" for="mail">Mail:</label>
<input id="mail" type="text" name="mail" required="required" />
</div>
<div class="field">
<label id="CDselectLBL" for="CDselect">Centro di Costo</label>
<select id="CDselect" class="DropDownList" name="CDselect"></select>
</div>
<div class="field">
<label id="FINALITAselectLBL" for="FINALITAselect">Finalità</label>
<select id="FINALITAselect" class="DropDownList" name="FINALITAselect"></select>
</div>
<div class="field">
<label id="rif_studio_cliLbl" for="rif_studio_cli">Riferimento Studio Clinico:</label>
<input id="rif_studio_cli" type="text" name="rif_studio_cli" />
</div> </form>
.. and here is the $.Ajax call:
$('#modulo').submit(function (event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'api/richiestes', // the local url where I want to POST
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
data: $('#modulo').serialize(),
})
// using the done promise callback
.done(function (data) {
console.log(data);
});
});
Here is the form data (copied from Chrome DevTools):
mail : tom.cat#google.com
CDselect:10A0003 - GESTIONE FINANZIARIA
FINALITAselect:Studio clinico approvato da Comitato Etico
rif_studio_cli:sfvsdfv
Here is the preview of the request data being sent (also copied from Chrome DevTools):
mail : "tom.cat#google.com" CDC : null finalità : null rif_studio_cli : "sfvsdfv"
Can you help me understand what is wrong with my code?
Thanks in advance for your time and kindness
This is beacuse you dont have any option element in your select control. You need to add the option and then selected one. e.g.
I have created a plunker code for you.
https://plnkr.co/edit/L5SyOdU8hnEKdrKitmcL?p=preview
$(document).ready(function(){
$('form').submit(function (event) {
event.preventDefault();
console.log($('#modulo').serialize());
});
});
html is as provided by you on the comments above but i have removed the input boxes to simplify the page.
Hope it helps you.

why is this not printing to console

Hello I have a form with some data what I want is when I click a button a jQuery function executes and print all that data in the console so here is my form code:
<form>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="fecha">Fecha:</label>
<input type="text" name="fecha" id="fecha" class="form-control" placeholder="dd/mm/yyyy">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="total">Total:</label>
<input type="number" min="0" name="total" id="total" class="form-control">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="abono">Abono:</label>
<input type="number" min="0" name="abono" id="abono" class="form-control">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="resta">Restante:</label>
<input type="text" name="resta" id="resta" class="form-control" readonly>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-5">
<button type="submit" value="actualizar" class="btn btn-info" id="actualizar">Actualizar Datos
<span class="glyphicon glyphicon-refresh"></span>
</button>
</div>
</div>
</form>
and this is my script include
<script src="js/jquery-1.12.2.min.js"></script>
<script type="text/javascript" src="js/actualizar_orden.js"></script>
this is actualizar_orden.js file:
//Al clickear boton actualizar ordenes
$('#actualizar').click(function(){
var orden = parseInt($('#norden').val());
var id_tecnico = parseInt($('#id_tec').val());
var memoria = $('#memoria').val();
var chip = $('#chip').val();
var tapa = $('#tapa').val();
var falla = $('#falla').val();
var observacion = $('#observacion').val();
var estado = $('#estado').val();
var fecha = $('#fecha').val();
var total = parseInt($('#total').val());
var abono = parseInt($('#abono').val());
var ajaxUrl = 'actualizar_ordenes.php';
data = { 'norden': orden, 'id_tec': id_tecnico, 'memoria': memoria, 'chip': chip, 'tapa': tapa,
'falla': falla, 'observacion': observacion, 'estado': estado, 'fecha': fecha,
'total': total, 'abono': abono };
console.log(data);
/*$.post(ajaxUrl, data, function(response){
if(response.empty)
alert("Datos no actualizados");
else{
alert("Datos Actualizados.");
location.reload();
}
}) */
});
I just want to log that data into console to check if I'm getting it right.. but instead of log that to console my page is refreshing automatically so I can't see the output in the console... I've tried with both mozilla and chrome but still nothing
I see You want to submit form using jquery, without refreshing screen.
simply do following in Your js file:
$(function() {
$('form.ajax').submit(function(e) { // catch submit event on form with ajax class
e.preventDefault(); // prevent form act as default (stop default form sending)
var $form = $(this); // caching form object to variable
var data = $form.serializeArray(); // getting all inputs from current form and serializing to variable
var url = $form.attr('action'); // reading forms action attribute
console.log('DATA:', data);
$.post(url, data, function(response) { // posting form data to url (action)
console.log('RESPONSE:', response);
if(response.empty) {
alert("Datos no actualizados");
return;
}
alert("Datos Actualizados.");
$form.find('input, select').val(''); // resets form inputs
});
});
});
and change Your form tag to be like this:
<form class="ajax" action="actualizar_ordenes.php" method="post">
this example shows You that:
1) You can catch all form submits that has ajax class defined
2) no need to set exact url in js code (before it was hardcoded ajaxUrl variable). now it gets form action url from form attributes.
3) it does ajax post and if success, so You can redefine some wise behavior to make really flexible solution, and forget about writing custom code for each form submitting
isn't it flexible? (:
Everyform need some default action to do on submitting. When it's not set it reloads the page by default. So to prevent the refreshing, you should add some empty action to your <form> tag, like this:
<form action="javascript:void(0);">

How To use Query string in java script?

I have Created calculator project. I have only two pages. Now my question how to pass input field value to another page? trying too many ways its Not Working.
What to do to pass input fields values from one page to another page?
My input fields code Looks Like
<p class="pull-right">DPA Minimum Buyer Contribution<br /></p>
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6" style="padding-right:1%">
<input type="text" id="txtLocationContactName5" class="txt"/>
</div>
<div class="col-md-3" style="padding-left:0%">
Another page name default_results.php I have created input fields
<div class="col-md-5 padding-rht">
Minimum Buyer Contribution
</div>
<div class="col-md-2 padding-Zero">
<input type="text" id="txtCustomerName3" class="txt" />
</div>
I have tired in jQuery script
<script>
$(function () {
$("#btnQueryString").bind("click", function () {
var url = "default_results.php?id=" + encodeURIComponent($("#txtLocationContactName5").val()) + "&technology=" + encodeURIComponent($("#txtCustomerName3").val());
window.location.href = url;
});
});
</script
but Not working so how to pass value one page to other page ?
You're making life hard for yourself! A simple form is needed to help you pass data to another page :). See here for info on html Forms - http://www.w3schools.com/html/html_forms.asp
Here is a simple example for you:
<form action="page_2_link" method="POST">
<input type="text" name="field1" value="easy">
<input type="submit" name="button1" value="Submit">
</form>
Then on the second page you can do this to retrieve the form data:
<?php
$blah = $_POST['field1']; // this now has the posted fields value
?>
I have given the second page answer in PHP as you have used this as a tag for this question, so I hope you are using this or my answer won't work.

On submit, remote call php - why aren't $_POST values being posted?

So, I'm a bit in unfamiliar territory with json and remote calls but the url and datatype is correct and... it is clearly arriving at target. BUT.!
It's a very simple form with 3 visible and 2 hidden fields.
<form id="subChange" action="#" method="POST">
<div style="clear:both;">first name</div>
<div>
<input id="fart" type="text" style="margin:4px;width:90%;" name="newFirst" value="" data-validetta="required,characters,remote[check_update]">
</div> last name<BR>
<div>
<input type="text" style="margin:4px;width:90%;" name="newLast" value="" data-validetta="required,characters,remote[check_update]">
</div> eMail<BR>
<div>
<input type="hidden" name="oldName" value="Conor" data-validetta="remote[check_update]">
</div>
<div>
<input type="hidden" name="oldEmail" value="cburkeg#gmail.com" data-validetta="remote[check_update]">
</div>
<div>
<input type="text" style="margin:4px;width:90%;" name="newEmail" value="" data-validetta="required,email,remote[check_update]">
</div>
<div style="margin-top:12px">
<input type="submit" name="sub_change" value="change it" data-validetta="remote[check_update]">
</div>
</form>
Here is the js
<script type="text/javascript">
$(function(){
$("#subChange").validetta({
realTime : true,
bubbleLoc:"right",
onValid : function( event ){
event.preventDefault();
$("#changeDIV").html("thanks Conor <P>Your subscription has been updated");
},
remote : { check_update : { type : "POST", url : "checkNewsUpdate.php", datatype : "json" }}
});
})
</script>
With fields filled we test Submit; name='sub_change' value='change it'
if (isset($_POST['sub_change'])) {
$count = count($_POST);
$postdata = file_get_contents("php://input"); //... write to file, etc.
}
output -
$count: 1
$postdata: sub_change=change+it
What happened to the other fields?
My only current working solution is to set each field with the remote call and set a $_POST validation (done auto., in real time) for each input which writes to a remote file. On submit we then call the contents of that file. Only trouble is it misses the 2 hidden files - there is no auto trigger :(
This is a clumsy work-around (that doesn't even work).
I thought about setting the hidden fields as an ID but getting the value with PHP is a trial. There must be something real simple I am missing here.

Categories