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

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.

Related

Insert data from multiple text boxes into sql via ajax

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

Mithril ajax sending empty inputs

I'm trying to send a POST request through ajax and Mithril.js using CodeIgniter. But for some reason the input always is empty. I have tried with a regular ajax post request and that works fine, but Mithril doesn't.
m.request({
method: "POST",
url: "http://localhost/index.php/login",
data: {
username: $("#login-username").val(),
password: $("#login-password").val()
}
})
.then(function(result) {
console.log(result)
})
And the php
public function login()
{
$username = $this->input->post('username');
die($username);
}
It always prints "null" in console. Any ideas?
UPDATE:
<form class="uk-form-stacked uk-margin-remove" id="login-form" method="post" action="index.php/login">
<fieldset class="uk-fieldset">
<div class="uk-margin">
<div class="uk-inline uk-width-1-1">
<span class="uk-form-icon" uk-icon="icon: user"></span>
<input class="uk-input" id="login-username" name="username" type="text" placeholder="Username">
</div>
</div>
<div class="uk-margin">
<div class="uk-inline uk-width-1-1">
<span class="uk-form-icon" uk-icon="icon: lock"></span>
<input class="uk-input" id="login-password" name="password" type="password" placeholder="Password">
</div>
</div>
<div class="uk-margin" style="margin-top:10px">
<label ><input class="uk-checkbox" type="checkbox"> Remember me</label>
</div>
<input type="submit" class="uk-button uk-button-primary uk-width-1-1" value="Login">
</fieldset>
</form>
Routes:
$route['login']['post'] = 'Users/login';
That code will send a JSON body to the server, not a form submission. I'm guessing your PHP code expects the data to be formatted like a <form> would send it, so for that you'd want to use a FormData instance.
var data = new FormData();
data.append("username", document.querySelector("#username").value);
data.append("password", document.querySelector("#password").value);
m.request({
method: "POST",
url: "https://httpbin.org/post",
data: data
})
.then(function(result) {
console.log(result)
})
I also set up a JsBin where you can see this working & poke at it.
https://jsbin.com/gififo/2/
try print the data to be able to see it i the console .
public function login()
{
$username = $this->input->post('username');
echo $username;
}
I don't know if you have define a route (in app/config/route.php) but, actually you are pointing to the default controller.
If you are trying to send your request to, for exemple, the login method of the users controller, your request path should be http://localhost/index.php/users/login
I also recommand you to use the base_url function instead of a simple string, which is far more easier when you deploy your app on the real server.
So, I propose to change this line
url: "http://localhost/index.php/users/login",
By
url: <?= json_encode(base_url("/users/login")) ?>,
For this function work, you should have load the URI helper, in your controller __construct or directly in your current method :
$this->load->helper('URI');

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.

Modifying HTML form action with jQuery/Javascript

I am trying to create a post form in HTML using a RESTful express route, something akin to /game/:gameID/node/:nodeRow/:nodeCol/update to update a given node in a given game.
Here's the route code:
app.post("/game/:gameID/node/:nodeRow/:nodeCol/update", function(request, response) {
gameHandler.updateNode(request, response)
});
The reason I'm doing this in HTML is because I haven't created the functionality yet in the actual client (mobile game) so I need something to test it. However, I have not figured out how to make the HTML form so that I can enter the data in the form to replace :gameID, :nodeRow, and :nodeCol without just going to the URL manually, like /game/3/node/2/5/update.
This is a post request and I would like other data to be contained in the form to specify the property to update as well as the new value.
How can I do this, or am I thinking about it wrong?
Edit:
Changed the question title to be more useful.
Try
app.post("/game/:gameID/node/:nodeRow/:nodeCol/update", function(request, response) {
console.log({gameID: request.params.gameID, nodeRow: request.params.nodeRow,nodeCol: request.params.nodeCol, body: request.body});
response.send({gameID: request.params.gameID, nodeRow: request.params.nodeRow,nodeCol: request.params.nodeCol, body: request.body});
});
Sorry I misunderstood your question. I thought you are having difficulties in parsing node parameters in node.
Anyway, there are different ways you can achieve this. Of course you need support of javascript, either pure javascript or jQuery.
Here is an example
<form id="myform">
<input name="gameID" id="gameID" />
<input name="nodeRow" id="nodeRow" />
<input name="nodeCol" id="nodeCol" />
<button name="action" value="bar" onclick="submitForm();">Go</button>
</form>
and javascript (using jQuery) will be
<javascript>
function submitForm(){
$("#myform").attr('action',
'/game/' + $("#gameID").val() + '/node/' + $("#nodeRow").val()
+ '/' + $("nodeCol").val() + '/update');
$("#myform").submit();
}
</javascript>
The way to pass data in a POST request is to push it from the html form controls and retrieve the values from the body of the request. The HTML below defines a form with your variables which you can hand-key from a browser:
<html><body>
<form method="post" action="/game/update" role="form">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">gameID</span>
<input type="text" class="form-control" name="gameID" placeholder="<gameID>" value="123456">
</div>
</div>
<div class="input-group">
<span class="input-group-addon">nodeRow</span>
<input type="text" class="form-control" name="nodeRow" placeholder="<nodeRow>" value="1">
</div>
</div>
<div class="input-group">
<span class="input-group-addon">nodeCol</span>
<input type="text" class="form-control" name="nodeCol" placeholder="<gameID" value="1">
</div>
</div>
<hr>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</body></html>
Then you can write a handler along the lines of what's below. Clicking submit will fire the POST request off, and pulling the variables out of the request body can be done as shown below.
app.post("/game/update", function(request, response) {
updateNodeHandler(request, response)
});
function updateNodeHandler(request, response) {
var nodeID = request.body.nodeID;
var nodeRow = request.body.nodeRow;
var nodeCol = request.body.nodeCol;
// Additional logic goes here...
}

Complete Javascript Ajax php confusion

Hi all I am developing a site in Codeigniter and I have a form that I am posting using PHP and this is absolutely fine. However I have a small dropdown on the side of my page which I am using to jump between pages - in order to do this I am simply using a href and passing variables within the URL.
I need to POST some data however when they click on the link. I don't wish to use a button and was wondering whether this could be acheived using an ajax onclick() event?? - the data I need to post however is within the form. The code structure is roughly:
<form action="main/postback" method="post">
<input type="hidden" name="pagereference" value="2" />
<input type="hidden" name="supervariable" value="7" />
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
<div>
<ul>
<li><a href = 'http:localhost/landing'>click me</a></li>
</ul>
</div>
When someone clicks on the link I want to send an Ajax Post request, but In the php file that I am posting the data I want to be able to retrieve data from within the form. Is this possible? if so could someone please provide an example AJAX request and how to retrieve the data in PHP as I am majorly confused. I tried the following:
<li><a onclick='myFunction()'>click me</a></li>
<script type="text/javascript">
function myFunction()
{
var "test";
$.ajax({
type: "POST",
url: "http://localhost/ciproject/assessment/test",
dataType: String,
success: function(msg){
alert( "Data Saved: " + msg ); //Anything you want
}
});
window.alert("TEST");
}
</script>
Any ideas would be much appreciated, many thanks
You will probably run into problems using complete urls (with the domain name) due to CORS so I would recommend removing that, but you can easily do what you want using something like:
<li><a class="postFormLink">click me</a></li>
<script type="text/javascript">
$('.postFormLink').on('click', function() {
$.ajax({
type: "POST",
url: "/ciproject/assessment/test",
data: $('form').serialize(),
success: function(msg){
alert( "Data Saved: " + msg ); //Anything you want
}
});
window.alert("TEST");
}
</script>
If you have more than one form on your page, you should add an ID or a class to target it instead of using $('form').
Note that I have also removed the inline event handler.
Try the following:
<form action="main/postback" method="post" id="form1">
<input type="hidden" name="pagereference" value="2" />
<input type="hidden" name="supervariable" value="7" />
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
<li><a id="clickme">click me</a></li>
<script type="text/javascript">
$(function () {
$("#clickme").click(function () {
var form_data = $('#form1').serialize();
$.ajax({
type: "POST",
dataType: "text",
url: "ciproject/assessment/test",
data: form_data,
success: function(response){
alert('Job well done');
}
})
})
})
</script>
The following should work, if you put it into your ajax options. You will need to identify your form, the easiest way is to use an id.
data: $("#theFormId").serialize()

Categories