How to send SELECT element to server using AJAX - javascript

I have an issue in checking form element SELECT at server PHP code.
I found a similar link here, but it is slightly different in discussion.
My HTML code is
<body>
<div id="header">
<h1>Please add your landed property to advertise</h1>
</div>
<div id="background">
<form name="advertiseForm" id="advertiseForm" method="post" >
<br /><br /><br />
<select name="stories" id="stories" required="required"/>
<option value="Stories" >Number of stories</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="morethan4">More than 4</option>
<select/>
<label for="stories">Please select for number of stories</label>
<div id="stories-error" class="error-box" style="color:#FF0000"></div>
<br /><br /><br />
<select name="bedrooms" id="bedrooms" required="required"/>
<option value="Bedrooms" >Number of bedrooms</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<select/>
<label for="numbedrooms">Please select for number of bedrooms</label>
<div id="bedrooms-error" class="error-box" style="color:#FF0000"></div>
</form>
</body>
I have two SELECT elements at my form and form elements are sent to server using AJAX using data: $("form").serialize(),.
</body>
<script>
function sendtoServer() {
$.ajax({
url: "advertisementdatavalidationatserver.php",
type: "POST",
data: $("form").serialize(),
success: function(ret){
alert(ret.message);
if(ret.error == true){
if(ret.message.indexOf("Storieserror")>=0){
$('#stories-error').css('display', 'block');
$('#stories-error').html('Please enter number of stories at your building');
}else{
$('#stories-error').html('');
}
if(ret.message.indexOf("Bedroomserror")>=0){
$('#bedrooms-error').css('display', 'block');
$('#bedrooms-error').html('Please enter number of bedrooms at your building');
}else{
$('#bedrooms-error').html('');
}
}else{
$('#stories-error').html('');
$('#bedrooms-error').html('');
}
},
error: function(){
// the AJAX request failed as in timed out / bad url etc.
}
});
}
</script>
</html>
My PHP code at server side for validation is
<?php
$data = array();
$data['error'] = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_POST['stories'] == "Stories"){
$data['error'] = true;
$data['message'][] = "Storieserror";
}
if ($_POST['bedrooms'] == "Bedrooms"){
$data['error'] = true;
$data['message'][] = "Bedroomserror";
}
}
// then echo the $data array you have built as JSON to use in jquery.
//This will be what is returned in your AJAX request
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($data);
?>
The problem here is for SELECT for bedrooms, no matter how I change option values to 1,2,3,4,.., the server side always comes back as Bedroomserror, that means no matter how I change other option values, client side always send 'Bedrooms' value to server.
Stories is working fine.
What could be the problem?
EDIT:
Now I found my problem. I see the serialized data as
alert($("form").serialize());
What the serialized data is shown in the attached image, interesting thing there is there are repeated data (underlined). The first one is fine stories=3&bedrooms=2&bathrooms=2. Then there is another repeated message with bedrooms=Bedrooms&bathroom=Bathrooms, I think my PHP code caught the second one and the value is never changed.

When recreating your code for testing here, I did not encounter the problem you describe. Selecting a numbered option for bedrooms did not display an error, and the returned value was correct.
To troubleshoot this type of issue, I'd suggest the following:
Make sure the values being serialized by your sendToServer javascript function are what you expect. Output them via console.log() or similar to check that what you select in the form is actually being sent to the PHP script.
I had to makes some changes to the code you provided to get it working. My assumption here is that you already have this in place, but it's not included in your question so I've referenced the changes I made below, as they were required to get the test working:
Add a valid DOCTYPE and head tag to the HTML markup
Add an input button to the form for submission
Add a script tag which pulls in jQuery
Wrap the call to your sendToServer function in a $(document).ready(function(){}); call, triggered by a click event on the input submit element (or however you submit the form)
[Optional] I added an else section after your if statement checking the $_POST['bedrooms'] value, so that I could check what the selected value was
Hope this helps.

in your html form code place a hidden field
<input type="hidden" id="bedroomsVal" name="bedroomsVal" value="" />
in php code check value of bedroomsVal
if ($_POST['bedroomsVal'] == "Bedrooms"){
//your logic
}
in js do this
$(document).ready(function(){
$("#bedroomsVal").val($("#bedrooms option:selected").text());
$("#bedrooms").change(function(){
$("#bedroomsVal").val($("#bedrooms option:selected").text());
});
})

At the first step you need to pass the parameters from your AJAX code to PHP page. then you can check the posted value in your PHP section.
HTML
<select name="stories" id="stories" required="required"/>
<option value="Stories" >Number of stories</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="morethan4">More than 4</option>
</select>
<select name="bedrooms" id="bedrooms" required="required"/>
<option value="Bedrooms" >Number of bedrooms</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<select/>
JavaScript
<script>
function sendtoServer() {
$.ajax({
url: "advertisementdatavalidationatserver.php",
type: "POST",
data: {story: $('#stories').val(), bedroom: $('#bedrooms').val()},
success: function(ret){
// Any logic when return TRUE;
},error: function(){
// the AJAX request failed as in timed out / bad url etc.
}
});
}
PHP
Check the all posted parameters
<?php
if(! isset($_POST)){
// return FALSE;
}
else
{
// check the posted parameters
// write your query;
// return TRUE or retrieved value
}
?>

Related

update select option element with Ajax result

i have two select option list with values retrieved from db .
<select id="userid" onchange="selSuj()">
<option value="1" selected="selected">text1</option>
<option value="2">text2</option>
<option value="3">text3</option>
</select>
<select id="subject">
<div id="determineSubj">
<option value="1" selected="selected">text1</option>
<option value="2">text2</option>
<option value="3">text3</option>
</div>
</select>
<script>
function selSuj(){
var x = $('#userid').val();
$.ajax({
type:'POST',
url:'same page url',
data:{
'userid':x
},
success: function(result){
document.getElementById("determineSubj").innerHTML = result;
}
})
;
}
the first select option(userid),when option selected, should populate the corresponding values in the second select option(subject), using the user option value(eg 1,2,3) as search p.key to the subject db.
I have tried using ajax, it worked out well on alert(result), but does not update the second select option values. please help.
A select should not contain a <div>.
As we can see from this brief demo, doing so makes the div inaccessible to JavaScript, because it doesn't consider it to be a valid part of the DOM:
document.addEventListener("DOMContentLoaded", function() {
console.log(document.getElementById("determineSubj"));
});
<select id="subject">
<div id="determineSubj">
<option value="1" selected="selected">text1</option>
<option value="2">text2</option>
<option value="3">text3</option>
</div>
</select>
In any case, even if it was valid, it's entirely unnecessary for your purpose. You can just update the HTML of the select element directly.
Change the HTML to:
<select id="subject">
<option value="1" selected="selected">text1</option>
<option value="2">text2</option>
<option value="3">text3</option>
</select>
And the "success" callback to:
success: function(result) {
document.getElementById("subject").innerHTML = result;
}
and there shouldn't be any problem.

Codeigniter dropdown pass wrong value to controller

I have a dropdown list with 5 options, whenever I click the submit button in the modal, the value posted to the controller is not the one I had selected.
Here is my view code
<div class="form-group">
<div class="col-md-4">
<select class="form-control" name="procode" id="procode" >
<option value="AOC">AOC</option>
<option value="ATN">ATN</option>
<option value="AOC">APS</option>
<option value="ATN">ADS</option>
<option value="AOC">ATW</option>
<option value="ATN">ATB</option>
</select>
</div>
</div>
And my ajax code for submiting the data to controller is here
var url;
url = "<?php echo site_url('person/ajax_add_claim')?>";
$.ajax({
url : url,
type: "POST",
data: $('#formclaim').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status)
{
$('#modal_form').modal('hide');
$('#modal_form').removeData();
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error');
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]);
}
}
$('#btnSave').text('save');
$('#btnSave').attr('disabled',false);
},
error: function (jqXHR, textStatus, errorThrown)
{
$('#btnSave').text('save');
$('#btnSave').attr('disabled',false);
}
});
This is a silly question to answer. But here you go:
<div class="form-group">
<div class="col-md-4">
<select class="form-control" name="procode" id="procode" >
<option value="AOC">AOC</option>
<option value="ATN">ATN</option>
<option value="APS">APS</option>
<option value="ADS">ADS</option>
<option value="ATW">ATW</option>
<option value="ATB">ATB</option>
</select>
</div>
</div>
Do you notice the difference?
The option in your dropdown contains similar values, that might be the cause of the problem.
<option value="AOC">AOC</option>
<option value="ATN">ATN</option>
<option value="AOC">APS</option>
<option value="ATN">ADS</option>
<option value="AOC">ATW</option>
<option value="ATN">ATB</option>
Try replacing the values with some other data. Just to test, whether the code is working or not.
Show us a bit of controller code to see what and how you are displaying the dropdown data.
Can you please share your controller function and reload_table function of Javascript. i think you are not returning accurate data from Controller function. You should use like this.
$drop_downdata = $this->db->function(your db query);
/* you pass this data to view like this create a page with this name dropdown_page.php */
$dropdown_view['page'] = $this->load->view('dropdown_page',array('data'=>$drop_downdata),TRUE);
$this->output->set_content_type('application/json')->set_output(json_encode($dropdown_view));
View Page dropdown_page.php
<?php foreach($data as $value): ?>
<li><?=$value->column_name?></li>
<?php endforeach; ?>
you will simple get this Drop down in this way
`$("#dropdown_id or class").html(response.page)`.
It will show your dropdown according to your request

Unable to return value of dropdown value in PHP

I am trying to retrieve a dropdown value, but the value isn't being returned in PHP. It returns as empty. I have other dropdowns in the form, but the only difference between them and this one is that there is a function associated to it. Which the javascript actually returns.
Thanks for your help. Code for the dropdown is below.
function validateDays() {
var e = document.getElementById("age_category");
var age_category = e.options[e.selectedIndex].text;
if (age_category == "Sub-Junior") {
console.log("Success");
} else {
console.log("Not Sub-Junior");
}
}
<?php
if(isset($_POST['submit'])){
echo $age_category = $_POST['age_category']
}
?>
<form action="my_page.php" method="POST">
<div class="form-group">
<!-- AGE CATEGORY -->
<select class="form-control" name="age_category" id="age_category" onchange="validateDays();" required>
<option value="">Age Category</option>
<option value="Sub-Junior">Sub-Junior</option>
<option value="Junior">Junior</option>
<option value="Open">Open</option>
<option value="Master 1">Master 1</option>
<option value="Master 2">Master 2</option>
<option value="Master 3">Master 3</option>
<option value="Master 4">Master 4</option>
</select>
</div>
</form>
You trying get submit value:
$_POST['submit']
and You need age_category:
$_POST['age_category']
You are trying to check isset function on $_POST['submit'] but "submit" reference doesn't exists anywhere in your form.
First create a button or something else and name it "submit" and then submit your form.
Currently you are not submitting your form in your code
Problem solved. When I was checking to see if it was empty. I was actually assigning it to be empty.
So it looked like this
if($age_category = "")
instead of
if($age_category == "")

Ajax Post request not working?

I am trying to build a form where the user fills information in and clicks submit. Upon clicking, the page will never refresh. Form processing and data handling will happen after the user clicks.
I am trying to use jQuery and Ajax to accomplish this, so far this is what I have:
HTML
<form class="article_information_form" action="" method="POST">
<label>Title </label>
<input type="text" name="articleTitle"> <br>
<label>Article URL: </label>
<input type="text" name="articleUrl"> <br>
<p>Number of pages</p>
<select name="numPages">
<option value="" selected></option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
</select>
<br>
<?php echo $message;?> //For Debugging
<input type="submit" name="article_info_btn" value="Submit">
</form>
PHP
if (isset($_POST["articleTitle"], $_POST["articleUrl"], $_POST["numPages"])) {
$message = "Success!"; //For debugging
}
Ajax
$(document).on('submit', '.article_information_form', function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
url : '',
success : function(data) {
alert("Success!");
}
})
})
Upon clicking the submit button, the success window popup alert is shown.
Though, the $message variable never prints out "success!" This means that its not processing the PHP $_POST.
How do I make it so that Ajax sends the information to the PHP $_POST?
$( ".article_information_form" ).on( "submit", function( event ) {
event.preventDefault();
$.post(window.location , $( this ).serialize() , function(result){
alert(result);
});
});
You didnt attach the data payload!!
Since you wanted the entire thing to be on a single page, this would be a possible way:
Full code for easy understanding:
<?php
//exececuted only if POST request as in the ajax below.
if($_SERVER[ 'REQUEST_METHOD']==='POST' ){
//your processing here
header( 'Content-Type: application/json');
//lets set the receivedToServer property to what data we got
$data = array();
$data['receivedToServer'] = $_POST;
//output data as json
echo json_encode($data);
//kill the page once the data is displayed
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
</head>
<body>
<form class="article_information_form" action="" method="POST">
<label>Title </label>
<input type="text" name="articleTitle">
<br>
<label>Article URL: </label>
<input type="text" name="articleUrl">
<br>
<p>Number of pages</p>
<select name="numPages">
<option value="" selected></option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
</select>
<br>
<input type="submit" name="article_info_btn" value="Submit">
</form>
</body>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
$('.article_information_form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '',
data: $(this).serialize(),
success: function(data) {
//the processed data available as data variable.
//lets log the data received at server property we set before
console.log(data.receivedToServer);
alert(data.receivedToServer.articleTitle);
}
});
})
</script>
</html>
You are not pass data to your method so it is not working. So first you will check how many argument have in method, then you send same number of string in params.
You should note one thing about argument are same name as use in method argument name.
$(document).on('submit', '.article_information_form', function(e)
{
e.preventDefault();
$.ajax({
type : 'POST',
url : '',
params : {articleTitle: 'Titlename', articleUrl : 'URLName',numPages : 'PagesNo'}
success : function(data)
{
alert("Success!");
}
})
});
On your form add an ID, in our case I put an id="form_submit" and action="action.php", you need to replace it with your own path where the action should do.
<form id="form_submit" class="article_information_form" action="action.php" method="POST">
also this line of the form,
<input type="button" id="submit" name="article_info_btn" value="Submit">
change the type type="bumit" to type="button" to prevent default submission.
and the jquery,
$('#submit').click(function() {
var submit_url = $(this).parent('form').attr('action');
$.ajax({
type : 'POST',
url : submit_url,
data : $('#form_submit').serialize(),
dataType : 'json',
success : function(data) {
alert("Success!");
}
})
})
This line var submit_url = $(this).parent('form').attr('action'); get the path on the action="" and use that path to passed data.
You need to add data to your ajax call:
$(document).on('submit', '.article_information_form', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
//url: '', by default is the current page url.
data: $('.article_information_form').serialize(),//This line
success: function(data) {
$('.article_information_form type["submit"]').before("<div>"+data+"</div>")
}
})
})
PHP:
if (isset($_POST["articleTitle"], $_POST["articleUrl"], $_POST["numPages"])) {
echo "Success!"; //For debugging
exit();
}
Like the others have said, you need to add a data parameter to your $.ajax() call.
Your other question - reading the comments - is about how you can get the PHP $message variable to show up without a page load.
That is, unfortunately, impossible without a page-refresh because PHP is rendered on the server side.
What I would suggest, is creating another PHP file that handles the logic that you're trying to create, and then using AJAX to throw the response back onto the current page. Achieving what I believe you want to do.
So! Example time.
first.php
<!doctype html>
<html>
<head><title>First</title></head>
<body>
<form id="myForm">
<input name="email" type="email" />
<button>Go!</button>
</form>
<div id="message"></div>
<script>
$('#myForm').on('submit', function(event){
event.preventDefault();
$.ajax({
type: 'POST',
data: $().serialize(); // send the form data to..
url: 'second.php', // your new PHP page
complete: function(xhr, status){
console.log('xhr', xhr);
console.log('status', status);
$('#message').text(status);
}
});
});
</script>
<body>
</html>
second.php
<?php
if (isset($_POST["email"]) {
echo "Success!";
} else {
echo "Error!";
}
?>
1- Your Ajax Code :-
<script>
$(function() {
$(".article_information_form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: "process_page.php",
type: "post",
data: $(this).serialize(),
success: function(html) {
$('#msg').html(html);
}
});
});
});
</script>
2- To print AJAX response add the following "div" under the "body" tag :-
##<div id='msg' ></div>
3- Create a PHP page "process_page.php" to receive the submitted data and then send the result
<?php
$numPages = $_POST['numPages'];
echo $numPages; //anything you echo here will be displayed in the <div id='msg'> at the main page
?>
good luck

Select2 - Multiple tags not working

I'm trying to use Select2 (https://select2.github.io) to allow a user to type multiple tags into a field before submitting a form. In my Laravel PHP app, I'll then take those tags, determine if they exist and add them into a database.
My problem is that I can't seem to get Select2 to recognise there are multiple tags being entered by the user. When I interrogate the form data, I only see the LAST tag a user typed as opposed to ALL the tags.
My Select2 element is:
<select class="tags-field" name="tags" data-tags="true" data-placeholder="TAGS" multiple="multiple">
</select>
and my JQuery is:
$(function() {
$(".tags-field").select2({
maximumSelectionLength: 3,
tokenSeparators: [','],
});
}
There are no Javascript errors and it works perfectly fine except I cannot detect ALL the tags.
To cause PHP to make all the selected choices available as an array, suffix your select name with a pair of square brackets, like this:
<select class="tags-field" name="tags[]" data-tags="true" data-placeholder="TAGS" multiple="multiple">
If this form is sent to a PHP program, the value of $_POST['tags'] will be an array. Note that the square brackets in the form control name aren't a part of the array key. You would process such a form like this:
<?php
$tags = $_POST['tags'];
// Note that $tags will be an array.
foreach ($tags as $t) {
echo "$t<br />";
}
?>
References here: http://bbrown.kennesaw.edu/papers/php2.html
use hidden input field in order to send all values
use onsubmit event to set the value of the hidden field
HTML:
<form method="post" action="post.php">
<select multiple id="e1" style="width:300px" name="_state">
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>
<input type="hidden" name="state" value="" />
<input type="submit"/>
</form>
JQ:
$("#e1").select2();
$('form').submit(function () {
var newvalue = '';
var value = $('select[name="_state"]').val();
if (value) {
newvalue = value;
}
$('input[name="state"]').val(newvalue);
})

Categories