I am having problem getting the post data in the controller when I send the post request via Jquery Ajax, I have checked with firebug and the form post data is being submitted, but in the controller when I do print_r($_POST); it returns an empty array. What could be wrong ?
Here is the relevant code :
FORM HTML
<form id="contact-form" class="form-horizontal subscribe" accept-charset="utf-8" action="<?= base_url ( 'Contact/' ); ?>" method="post">
<!--Name-->
<div class="form-group">
<label class="sr-only" for="name">Name</label>
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-user" aria-hidden="true"></span></div>
<input id="name" type="text" class="form-control validate" name="name" placeholder="Your full name" value="">
</div>
</div>
<!--Email-->
<div class="form-group">
<label class="sr-only" for="email">Email</label>
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-envelope" aria-hidden="true"></span></div>
<input id="email" type="text" class="form-control validate" name="email" placeholder="Your email address" value="">
</div>
</div>
<!--Message-->
<div class="form-group">
<label class="sr-only" for="message">Message</label>
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-envelope" aria-hidden="true"></span></div>
<textarea id="message" name="message" class="form-control" rows="3" placeholder="Message"></textarea>
</div>
</div>
<!--Submit Button-->
<div class="form-group text-right">
<input id="contact_us" type="hidden" name="contact_us" value="Submit" />
<button type="submit" id="contact_us" class="btn btn-warning" name="contact_us" value="Submit">
Send <span class="glyphicon glyphicon-send" aria-hidden="true"></span>
</button>
</div>
</form>
JAVASCRIPT
<script>
$( '#contact-form' ).submit ( function ( event ) {
event.preventDefault ( );
event.stopPropagation ( );
var $scriptUrl = $( '#contact-form' ).attr ( 'action' );
$.ajax ( {
method : 'POST',
url : $scriptUrl,
data : $( this ).serialize ( ),
cache : false,
processData: false,
contentType: false,
dataType : 'json',
success : function ( data, textStatus, jqXHR ) {
if ( data.success === true ) { alert ('success'); }
else { alert ('failure'); }
},
error : function ( jqXHR, textStatus, errorThrown ) {
alert ( jqXHR.responseText );/*This returns the empty array*/
}
} );
} );
</script>
Controller (index function) (http://mysite/Contact - Localhost-wamp)
public function index ( )
{
print_r($_POST);
}
change data : $( this ).serialize ( ), to data : new FormData($('#contact-form')[0]) remove dataType : 'json' if this didnot work for you please let me know?
If you are using jquery then you should use the syntax as follows:
$.post('url',$("#contact-form").serialize(),function(data){
//here take action on returned data
});
You just change the
data : $(this).serialize(),
to
data : $('#contact-form').serialize(),
In ajax $this not working because when you call $this in ajax then $this call always parent object ajax.
Student x. This may not be your answer, but this is all you need to pass a form
$(function() {
"use strict";
$("#form1").submit(function() {
var data = $("#form1").serialize();
//alert(data); return false;
$.ajax({
url: "/forms/form1",
data: data,
type: "POST",
success: function(msg) {
if (msg) {
$("#display").html(msg);
} else {
$("#display").text("nothing came back For some reason");
}
}
});
return false;
});
});
You can also use this. I use this for all my forms, then I only need 1 script. Of course you would change the success. Just name all your forms with an ID of ajax
(function() {
"use strict";
$('form#ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
$('#display').html(response).delay(8000).fadeOut(1000);
}
});
return false;
});
})(jQuery);
Related
I have problem with AJAX and jQuery. I write function for login to system, but it works only first time. Here is my code:
html in modal:
<form role="form" onsubmit=" return login()" method="post" action="" >
<div class="form-group">
<label for="userName"><span class="glyphicon glyphicon-user"></span>E-mail</label>
<input type="email" name="emailLogin" class="form-control" id="userName" placeholder="e-mail" required>
</div>
<div class="form-group">
<label for="password"><span class="glyphicon glyphicon-eye-open"><span>Password</label>
<input type="password" name="passLogin" class="form-control" id="password" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-success btn-block">Login<span class="glyphicon glyphicon-log-in"></span></button>
</form>
here is jquery:
function login(){
login=document.getElementById('userName').value;
pass=document.getElementById('password').value;
var dataString="emailLogin="+login+"&passLogin="+pass;
$.ajax({
type: "POST",
url: "models/handler/KlientHandler.php",
cache: false,
data: dataString,
success: function(text){
if(text=='0'){
$("#loginError").removeClass('hidden');
}else{
$("#loginOk").removeClass('hidden');
$("#myModal").modal('hide');
$("#loginLi").html("<a id=\"user\">"+login+" (Profile)<span class=\"glyphicon glyphicon-user\"></span></a>");
$("#regLi").html(""+login+" (Logout)<span class=\"glyphicon glyphicon-log-out\"></span>");
}
}
});
return false;
}
You are overwriting your login function with a string.
function foo() {
alert('foo');
foo = function () {
alert('bar');
}
}
<a onclick="foo()">
click me!
</a>
See how the second click here causes a different alert? In your case you're replacing the function with a string instead of a function, causing a syntax error. Don't forget to var your variables.
var login=document.getElementById('userName').value;
var pass=document.getElementById('password').value;
The snippet tests your logic and there was a console error for your login and pass variables. I set them as 'var' and put your success logic in the 'error' section of the ajax request since I cannot reach your server, but it does create the logout button. Is that what you wanted?
function login() {
var login = document.getElementById('userName').value;
var pass = document.getElementById('password').value;
var dataString = "emailLogin=" + login + "&passLogin=" + pass;
$.ajax({
type: "POST",
url: "models/handler/KlientHandler.php",
cache: false,
data: dataString,
success: function(text) {
/* Success logic */
},
error: function() {
alert('Test - success logic');
$("#loginOk").removeClass('hidden');
//$("#myModal").modal('hide');
$("#loginLi").html("<a id=\"user\">" + login + " (Profile)<span class=\"glyphicon glyphicon-user\"></span></a>");
$("#regLi").html("" + login + " (Logout)<span class=\"glyphicon glyphicon-log-out\"></span>");
}
});
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form" onsubmit=" return login()" method="post" action="" >
<div class="form-group">
<label for="userName"><span class="glyphicon glyphicon-user"></span>E-mail</label>
<input type="email" name="emailLogin" class="form-control" id="userName" placeholder="e-mail" required>
</div>
<div class="form-group">
<label for="password"><span class="glyphicon glyphicon-eye-open"><span>Password</label>
<input type="password" name="passLogin" class="form-control" id="password" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-success btn-block">Login<span class="glyphicon glyphicon-log-in"></span></button>
</form>
<div id="loginLi"></div>
<div id="regLi"></div>
<div id="loginOk">Login OK</div>
I want to submit the form when a gcapcha was clicked. I tried submit with (my silly) jquery function that I know. But it's not work.
Here is my code (what's wrong with it).
Javascript
var verifyCallback = function(e) {
document.getElementById("form-contact").submit();
$.ajax({
type : 'POST',
url : 'inc/contact_sent.php',
data : $(this).serialize(),
success : function(data){
$("#contact").html(data);
}
});
return false;
};
var onloadCallback = function() {
grecaptcha.render("captcha", {
sitekey: "xxx",
callback: verifyCallback
})
};
HTML
<div id="contact" class="contact-form">
<form class="ajaxForm detailedsearch inline-style" method="post" id="form-contact">
<input type="text" class="form-control" name="cntc_name" placeholder="Your name" required>
<input type="email" class="form-control" name="cntc_email" placeholder="Your email" required>
<input type="text" class="form-control" name="cntc_tel" placeholder="Your phone">
<input type="text" class="form-control" name="cntc_subj" placeholder="Subject" value="<?=(isset($_POST['ptitle']))?"Queries for $_POST[ptitle]":""?>" required>
<textarea class="form-control" name="cntc_desc" rows="6" placeholder="Your Detail" required></textarea>
<div class="form-group">
<div id="captcha" class="center-captcha"></div>
<div id="gcaptcha" style="transform:scale(0.50);-webkit-transform:scale(0.50);transform-origin:0 0;-webkit-transform-origin:0 0;"></div>
<span class="text-danger">*Please complete the form to proceed.</span>
</div>
<!-- <button type="submit" class="btn btn-success btn-block"><i class="fa fa-envelope-o"></i> Submit Form</button> -->
</form>
</div>
You should do this....
//register a event for form submit
$( "form" ).submit(function( e ) {
e.preventDefault();
$.ajax({
type : 'POST',
url : 'inc/contact_sent.php',
data : $(this).serialize(), //serialize the form data
success : function(data){
$("#contact").html(data);
}
});
});
var verifyCallback = function(e) {
//submit form
$("#form-contact").submit();
return false;
};
var onloadCallback = function() {
grecaptcha.render("captcha", {
sitekey: "xxx",
callback: verifyCallback
})
};
I want to show the user a form sent correctly alert message with javascript using bootstraps built in alerts.
When I run the code I get the object array of the values (inspecting the page at console log). what I want to do is after it is sent, to display a success alert (if it is a success).
there is test4.sj which contains the javascript code and then there is main.php which is the code for the form.
The code that I have so far is in the snippet.
$('form.ajax').on('submit', function() {
var that = $(this),
type = that.attr('action'),
data = {};
that.find('[name]').each(function(index, value) {
//console.log(value);
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
console.log(data);
/* $.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
})*/
return false;
})
<body>
<form method="post" class="ajax">
<div>
<input name="name" type="text" placeholder="Your name" required>
</div>
<div>
<input name="lName" type="text" placeholder="Your Last Name">
</div>
<div>
<textarea name="message" placeholder="Your Message"></textarea>
</div>
<input type="submit" value="Send">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</body>
Just add hidden alert panel and show it on AJAX success.
HTML:
<form method="post" class="ajax">
<div class="alert alert-success js-alert hidden" role="alert">
Form was successfully sent!
</div>
...
<div>
<input name="name" type="text" placeholder="Your name">
</div>
...
<button type="submit" class="btn js-btn">Send</button>
</form>
JS:
$('form').on('submit', function( event ) {
var $form = $( this );
event.preventDefault();
$('.js-alert').addClass('hidden');
$('.js-btn').button('loading');
$.ajax({
url: '/someurl',
type: 'POST',
data: $form.serialize(),
success: function(response){
$('.js-alert').removeClass('hidden');
$('.js-btn').button('reset');
}
});
});
Check the fiddle:
https://jsfiddle.net/xw63db57/1/
you can use ajax jqXHR status and statusCode and based up on that you can write the alert code
success(data, textStatus, jqXHR){
var statusCode = jqXHR.status;
var statusText = jqXHR.statusText;
}
I am finding it difficult to send data to the controller through Ajax post since the object to be sent to the controller cannot be used within the ajax post because of the structure of my code.I am using knockout for data-binding the click event of the Update button.
This is my code
$(document).ready(function () {
var provider = function () {
var self = this;
self.providerID = ko.observable(providerEditInfo.ProviderID);
self.firstName = ko.observable(providerEditInfo.FirstName);
self.lastName = ko.observable(providerEditInfo.LastName);
self.contactEmail = ko.observable(providerEditInfo.ContactEmail);
self.NPI = ko.observable(providerEditInfo.NPI);
self.updateProviderDetails = function () {
$.ajax({
url: "/Provider/UpdateProviderDetails/",
type: "POST",
data: { providerForUpdate }, -- Cant send this
contentType: "application/json; charset=utf-8",
async: false,
success: function (result) {
if (result.url) {
location.href = result.url;
}
}
});
};
self.cancelEdits = function () {
if (confirm("Are you sure you want to Cancel?")) {
window.location.href = "/Provider/ShowTheListOfProviders";
}
};
}; //End of Constructor.
var providerForUpdate = new provider();
ko.applyBindings(providerForUpdate);
});
On the clck of Update Button,I am calling the 'updateProviderDetails' method.
HTML
#model Greenway.Demo.DataAccess.Entity.Provider
<body>
<div class="container">
<h1 class="col-sm-offset-2">Edit Provider Details:</h1>
<br />
<form class="form-horizontal" role="form" id="editProviderDetailsForm">
<div class="form-group">
<label class="col-sm-2 control-label labelfont">First Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" autofocus="autofocus" placeholder="Enter the First Name" id="firstName" name="firstName" data-bind="value:firstName , event: { keypress: allowOnlyAlphabets }">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label labelfont">Last Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" placeholder="Enter the Last Name" id="lastName" name="lastName" data-bind="value:lastName ,event: { keypress: allowOnlyAlphabets }">
</div>
</div>
<div class="form-group text-center">
<button type="Submit" data-bind="click: updateProviderDetails" class="btn btn-primary">Update</button>
<button type="button" data-bind="click: cancelEdits" class="btn btn-primary">Cancel</button>
</div>
</form>
</div>
</body>
<script type="text/javascript">
var providerEditInfo = #Html.Raw(Json.Encode(Model));
</script>
<script type="text/javascript" src="../../App_Scripts/Shared/Functions.js"></script>
Could someone guide me on how I can send the data to the controller with this code structure.I can't put updateProviderDetails outside the constructor because otherwise, I can't bind it.
Use ko.toJSON to serialize your view model to json:
self.updateProviderDetails = function () {
$.ajax({
url: "/Provider/UpdateProviderDetails/",
type: "POST",
data: ko.toJSON(self),
contentType: "application/json; charset=utf-8",
async: false,
success: function (result) {
if (result.url) {
location.href = result.url;
}
}
});
};
This is also in the Knockout Tutorial
I have a form with 5 fields that i am sending with AJAX to a PHP Script that does some simple validation and returns a string.
I have made a little jQuery script for the actual submission, and when i try to send the form i have to click the send button two times.
Update: Url to live site: http://www.dan-levi.no/new/#!/Kontakt
Here are some code:
HTML
<form id="contact_form" class="form-horizontal" action"includes/contact.php" method"post">
<div class="control-group">
<label class="control-label" for="contact_name">Ditt navn og evt. bedrift</label>
<div class="controls">
<input type="text" class="input-large" id="contact_name" name="contact_name" placeholder="Ditt navn og evt. bedrift" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="contact_email">E-post</label>
<div class="controls">
<input type="email" class="input-large" id="contact_email" name="contact_email" placeholder="E-post" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="contact_tel">Telefon</label>
<div class="controls">
<input type="tel" class="input-large" id="tel" name="contact_tel" placeholder="Telefon" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="contact_subject">Emne</label>
<div class="controls">
<input type="text" class="input-large" id="subject" name="contact_subject" placeholder="Emne for melding" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="contact_desc">Din beskjed</label>
<div class="controls">
<textarea rows="10" class="input-large" id="contact_desc" name="contact_desc" placeholder="Din beskjed"></textarea>
</div>
</div>
<div class="text-error pull-right" id="error_message"></div><br>
<input class="btn btn-large pull-right" type="submit" name="" value="Send" /><br>
</form>
javaScript
$(document).ready(function() {
$('#contact_form').submit(function(e) {
data = $('#contact_form').serialize();
$.ajax({
url: 'includes/contact.php',
type: 'POST',
data: data,
})
.done(function(response) {
if (response == 'empty') {
$('#error_message').text('Noen av feltene er tomme.')
} else {
$('.message').html(response);
$('#contact_form').fadeOut('400');
$('#info_line').fadeIn('400').text('Takk for din henvendelse');
};
})
e.preventDefault();
});
});
PHP
$contact_name = $_POST['contact_name'];
$contact_email = $_POST['contact_email'];
$contact_tel = $_POST['contact_tel'];
$contact_subject = $_POST['contact_subject'];
$contact_desc = $_POST['contact_desc'];
if ($contact_name == '' || $contact_email == '' || $contact_tel == '' || $contact_subject == '' || $contact_desc == '') {
echo "empty";
die();
}
echo $contact_name.'<br><br>';
echo $contact_email.'<br><br>';
echo $contact_tel.'<br><br>';
echo $contact_subject.'<br><br>';
echo $contact_desc.'<br><br>';
I cant find out why i have to click the button two times, i have tried some trial and error, read the forum for answers. I tried to serialize the form outsite the submit function, i just cant get this to behave the way i want. All help is greatly appreciated.
Oh, worth to mention. The actual response is that the fields are empty (php validation) the first time i click, but the second time it works as it should.
Make the ajax call using a regular input button instead of a submit button.
$("#button").click(function () { ... ajax ... }
I'm not sure if it makes a difference but have you tried putting what you want to happen afterwards in a success callback?
$(document).ready(function() {
$('#contact_form').submit(function(e) {
data = $('#contact_form').serialize();
$.ajax({
url: 'includes/contact.php',
type: 'POST',
data: data,
success: function(response) {
if (response == 'empty') {
$('#error_message').text('Noen av feltene er tomme.')
} else {
$('.message').html(response);
$('#contact_form').fadeOut('400');
$('#info_line').fadeIn('400').text('Takk for din henvendelse');
};
}
});
e.preventDefault();
});
});
I'm guessing it's because the default action (submit the form) is processing before your $.ajax request. Try making e.preventDefault() first in your submit callback.
$(document).ready(function() {
$('#contact_form').submit(function(e) {
e.preventDefault();
data = $('#contact_form').serialize();
$.ajax({
url: 'includes/contact.php',
type: 'POST',
data: data,
success: function(response) {
if (response == 'empty') {
$('#error_message').text('Noen av feltene er tomme.')
} else {
$('.message').html(response);
$('#contact_form').fadeOut('400');
$('#info_line').fadeIn('400').text('Takk for din henvendelse');
};
}
});
});
});