Ajax Post request not working? - javascript

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

Related

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

Prevent page from reloading after onchange a select menu

I apologize if this is a very simple question, however I am not able to find any answers or don't know what I am doing wrong here.Also I am new to ajax and jquery. Thanks for helping in advance!
I have a select menu which I want to submit to the page on change I have the following:
<from action="" method="post">
<select name="option">
<option value="a">a </option>
<option value"b">b </option>
<option value"c">c</option>
</select></form>
and
<script type="text/javascript" >
$('#option').change, (function(e)
{
e.preventDefault();
$.ajax({
type: 'post',
url: "",
data: $("form.option").serialize(),
success: function() {
}
});
return false;
});
</script>
and to check if it has submitted
<?php
if (isset($_POST['option'])) {
echo '<br />The ' . $_POST['option'] . ' submit button was pressed<br />';
}
?>
The form is submitted fine, however the page is still reloading on change, is there a way to stop the reloading of the page?
Any help would be appreciated!
try this code
<?php
if (isset($_POST['option'])) {
echo '<br />The ' . $_POST['option'] . ' submit button was pressed<br />';
exit;
}
?>
<form action="" method="post">
<select name="option" id="option">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
</form>
<div id="msg">
</div>
<script type="text/javascript" src="../library/jquery-3.2.1.min.js"></script>
<script type="text/javascript" >
$('#option').change(function(e)
{
e.preventDefault();
var data="";
data=$("#option").val();
$.ajax({
type: 'post',
url: "",
data: {option:data},
success: function(result) {
$('#msg').html(result);
}
});
return false;
});
</script>
your output will be in div tag which option is submit the form
you can also display in alert
alert(result);
or using console in developer tool
console.log(result);
Try this
<select id="option" name="option">
<option value="a">a </option>
<option value"b">b </option>
<option value"c">c</option>
</select>
And your jquery should be
<script type="text/javascript" >
$('#option').change(function()
{
var option_val = $(this).val();
$.ajax({
type: 'post',
url: "",
data: "option="+option_val,
success: function(res)
{
alert(res)
}
});
});
</script>
Simple Example :
<?php
if (isset($_POST['option'])) {
echo '<br />The ' . $_POST['option'] . ' submit button was pressed<br />';
die;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>temporary test</title>
</head>
<body>
<select id="option">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</body>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$('#option').change(function(){
var option_val = $(this).val();
$.ajax({
type: 'post',
url: "",
data: "option="+option_val,
success: function(res)
{
alert(res)
}
});
});
</script>
</html>

How to send SELECT element to server using AJAX

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
}
?>

Ajax form duplicating on submit

I have 3 selectboxes the value of each selectbox gets populated based on the selection of the selectbox before it:
selectbox1 =>populates => selectBox2 => populates selectBox 3:
Now when user clicks submit I want to use the values from the selectboxes to query my database
My Problem
When I click submit:
The Whole Form Gets Duplicated (see image below)
So in short the variables are being passed correctly to my php code but the form duplicates on submit...
Code for sending form data
I believe the problem is somewhere in this code
<script type="text/javascript">
jQuery(document).click(function(e){
var self = jQuery(e.target);
if(self.is("#resultForm input[type=submit], #form-id input[type=button], #form-id button")){
e.preventDefault();
var form = self.closest('form'), formdata = form.serialize();
//add the clicked button to the form data
if(self.attr('name')){
formdata += (formdata!=='')? '&':'';
formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
}
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
success: function(data) {$('#resultForm').append(data); }
});
}
});
</script>
HTML
<form method="post" id="resultForm" name="resultForm">
<select name="sport" class="sport">
<option selected="selected">--Select Sport--</option>
<?php
include('connect.php');
$sql="SELECT distinct sport_type FROM events";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['sport_type']; ?>"><?php echo $row['sport_type']; ?></option>
<?php
}
?>
</select>
<label>Tournamet :</label> <select name="tournament" class="tournament">
<option selected="selected">--Select Tournament--</option>
</select>
<label>Round :</label> <select name="round" class="round">
<option selected="selected">--Select Round--</option>
</select>
<input type="submit" value="View Picks" name="submit" />
</form>
You're appending the result.
If you don't want to duplicate then replace the new content with old one.
Just change this
success: function(data) {$('#resultForm').append(data); }
to
success: function(data) {$('#resultForm').replaceWith(data); }
or even
success: function(data) {$('#resultForm').html(data); }
See more details about replacewith here

Passing selected value in SELECT tag using serializeArray

How do i pass the selected value in a SELECT tag with serializeArray?I tried the followng code but when i click post it empties the select tag option.
html
<form action="" name="frm" id="frm" method="post">
<input type="text" name="title_val" value="abc" id="title_val"/>
<select name="test" id="test">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
post
</form>
JS
$( document ).ready(function() {
$('#save').click(function() {
var form = $('#frm');
$.ajax({
url: 'topic.php',
type:'post',
data: form.serializeArray(),
success: function(response) {
$('#test').html(response);
}
});
});
});
php
<?php
echo $_POST['test'];
?>
following code works for me,
data: form.serialize();

Categories