Pass ajax form value to controller codeigniter - php

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('form.ajax-form').onclick('login_submit', function() {
var obj = $(this), // (*) references the current object/form each time
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
obj.find('[user_email]').each(function(index, value) {
// console.log(value);
var obj = $(this),
email = obj.attr('user_email'),
value = obj.val();
data[email] = value;
});
obj.find('[user_pass]').each(function(index, value) {
// console.log(value);
var obj = $(this),
pwd = obj.attr('user_pass'),
value = obj.val();
data[pwd] = value;
});
$.ajax({
// see the (*)
url: url,
type: method,
data: data,
success: function(response) {
console.log(response);
// $("#feedback").html(data);
}
});
// console.log('Trigger');
return false; //disable refresh
});
});
</script>
<?php echo form_open('welcome/login', array('class' => 'ajax-form','style'=>'z-index: 202')); ?>
<input name="user_email" type="email" class="login_email" placeholder="Email address" required autofocus>
<br />
<input name="user_pass" type="password" class="login_pass" placeholder="Password" required>
<label class="checkbox">
Forgot login details?
<button class="btn btn-lg btn-info" id="login_submit" style="margin-left:20px;">Sign in</button>
</label>
</form>
<?php if(isset($login_error) && $login_error !=='') { ?><div class="alert alert-danger login_err"><?php echo $login_error; ?></div> <?php } ?>
<!-- </div>-->
Hi i am trying to pass the email and password to the controller in codeigniter.
Any idea how to do that please help?

You could simplify a big deal by doing:
$('#ajax-form').submit(function(){
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(response) {
console.log(response);
// $("#feedback").html(data);
}
});
return false;
});

Related

Post and display data on the same page using PHP (MVC) AJAX

I'm trying to post input data and display it on the same page (view_group.php) using AJAX but I did not understand how it works with MVC, I'm new with MVC if anyone could help me it would be very helpful for me.
view_group.php
<script type = "text/javascript" >
$(document).ready(function() {
$("#submit").click(function(event) {
event.preventDefault();
var status_content = $('#status_content').val();
$.ajax({
type: "POST",
url: "view_group.php",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {}
});
});
}); </script>
if(isset($_POST['postStatus'])){ $status->postStatus($group_id); }
?>
<form class="forms-sample" method="post" id="form-status">
<div class="form-group">
<textarea class="form-control" name="status_content" id="status_content" rows="5" placeholder="Share something"></textarea>
</div>
<input type="submit" class="btn btn-primary" id="submit" name="submit" value="Post" />
</form>
<span id="result"></span>
my controller
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
}
first in the ajax url you must set your controller url , then on success result value will be set on your html attribute .
$.ajax({
type: "POST",
url: "your controller url here",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {
$('#result).text(result);
}
});
Then on your controller you must echo the result you want to send to your page
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
echo $status;
}

Ajax html input value appears empty

I am trying to submit a form via ajax post to php but the value of the input tag appears to empty.
I have cross-checked defined class and id and it seems ok. I don't where my mistake is coming from. Here is the code
index.html
<div class="modal">
<div class="first">
<p>Get notified when we go <br><span class="live">LIVE!</span></p>
<input type="text" class="input" id="phone" placeholder="Enter your email adress" />
<div class="arrow">
<div class="error" style="color:red"></div>
<div class="validator"></div>
</div>
<div class="send">
<span>Subscribe</span>
</div>
</div>
<div class="second">
<span>Thank you for<br />subscribing!</span>
</div>
</div>
<script src='jquery-3.3.1.min.js'></script>
<script src="script.js"></script>
script.js
$(document).ready(function(){
function validatePhone(phone) {
var re = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
return re.test(phone);
}
$('.input').on('keyup',function(){
var formInput = $('.input').val();
if(validatePhone(formInput)){
$('.validator').removeClass('hide');
$('.validator').addClass('valid');
$('.send').addClass('valid');
}
else{
$('.validator').removeClass('valid');
$('.validator').addClass('hide');
$('.send').removeClass('valid');
}
});
var phone = $('#phone').val();
var data =
'phone='+phone;
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
});
subscribe.php
```php
$phone = htmlentities($_POST['phone']);
if (!empty($phone)) {
echo 1;
}else{
echo "Phone number cannot be empty";
}
```
An empty results with the error code is all I get. Can any one help me out here with the mistakes I am making. Thanks
Change next
JS:
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
to
$('.send').click(function(){
var data = $('#phone').val();
$.ajax({
type:"POST",
url:"subscribe.php",
data: {phone: data},
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
});
});
If you send a POST request via ajax you need to format data as a JSON object, see my code below.
Replace this:
var data =
'phone='+phone;
with this:
var data = {phone: phone};

cordova app with jquery, php

I'm trying to make a hybrid app using cordova and I want to ask two questions?
One of them is the login, I did it with jquery
<script type="text/javascript">
$(document).ready(function () {
$("#submit_btn").on("click", function(){
var username = $("#username").val();
var pass = $("#pass").val();
$.ajax({
type: "POST",
url: "link",
data: { username: username},
sucess: function () {
}
})
});
});
</script>
Is this a "right" way to do it?
and the best way to connect to a database?
<?php
header('Acess-Controll-Allow-Origin: *');
header('Acess-Controll-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
if(isset($_POST)) {
$username = $_POST['username'];
$pass = $_POST['pass'];
require("connect.php");
$sql = "INSERT INTO fields VALUES ('$username'. '$pass')";
mysqli_query($mysqli, $sql);
}
?>
I'm getting this error:
Notice: Undefined index: $username in /home/wm29tzgj/public_html/areacliente/insert.php on line 7
Notice: Undefined index: $pass in /home/wm29tzgj/public_html/areacliente/insert.php on line 8
<div class="signin-form">
<div class="container">
<form class="form-signin" method="post" id="login-form">
<h2 class="form-signin-heading">Log In to WebApp.</h2><hr />
<div id="error">
<!-- error will be shown here ! -->
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Username" name="username" id="username" />
<span id="check-e"></span>
</div>
<div class="form-group">
<input type="password" class="form-control" placeholder="Password" name="password" id="password" />
</div>
<hr />
<div class="form-group">
<button type="submit" class="btn btn-default" name="btn-login" id="btn-login">
<span class="glyphicon glyphicon-log-in"></span> Sign In
</button>
</div>
</form>
</div>
</div>
Like this :
<script type="text/javascript">
$(document).ready(function () {
$("#submit_btn").on("click", function(){
var username = $("#username").val();
var pass = $("#password").val();
$.ajax({
type: "POST",
url: "http://website.php",
data: {'username': username,"pass":pass },
cache: false,
success: function (data) {
}
});
});
</script>
<script type="text/javascript">
var username="";
var passTxt="";
$(document).ready(function () {
$("#submit_btn").on("click", function(){
username = $("#username").val();
passTxt = $("#password").val();
$.ajax({
type: "POST",
url: "http://website.php",
data: {'username': username,"pass":passTxt },
cache: false,
success: function (data) {
}
});
});
</script>

Checking user availability in registration form. Already an AJAX request is present in the current html file. How can i add another one?

Hey guys i've done a registration where the user registers himself and after submitting the data gets stored automatically. Already in the present html file, i've given an ajax request and the operation for register.php. Now i would like to implement a criteria of "Checking the user availability". Here is where i'm confused. If i give this ajax request, then how will i be able to do the register.php? Please help me out. Thanks.
<body>
<div class="app-block">
<div class="cube"><img src="images/cube.png" class="img-responsive" alt="" /></div>
<form method="post">
<div id="reg-data"></div>
<input type="text" name="username" required="required" placeholder="Enter your name" id="username" />
<input type="password" name="password" required="required" placeholder="Enter your password" id="password" />
<input type="text" name="location" placeholder="Please give your location" id="location" />
<input type="text" name="company" placeholder="Where do you work?" id="company" />
<input type="text" name="designation" placeholder="Provide your designation" id="designation" />
<label for="gender">Gender </label>
<input type="radio" name="gender" required="required" id="gender" value="Male" />Male
<input type="radio" name="gender" required="required" id="gender" value="Female"/>Female
<br/><br/>
<label for="qualification">Qualification</label>
<select name="qualification" value="Qualification" id="qualification">
<option value="SSLC">SSLC</option>
<option value="HSC">HSC</option>
<option value="UG">UG</option>
<option value="PG">PG</option>
</select><br/><br/>
<label for="hobbies">Hobbies </label>
<input type="checkbox" name="hobbies" id="hobbies" value="Cricket" />Cricket
<input type="checkbox" name="hobbies" id="hobbies" value="Music" />Music
<input type="checkbox" name="hobbies" id="hobbies" value="Swimming" />Swimming
<div class="submit"><input type="submit" name="register" value="Register" id="reg" /></div>
<div class="clear"></div>
</form>
<p class="sign">Already Registered? Login</p>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#reg').click(function(e) {
e.preventDefault();
var username = $("#username").val();
if( username == '') {
alert('Enter the username');
header('location: register.html');
} else {
var password = $("#password").val();
if( password == '') {
alert('Enter the password');
header('location: register.html');
} else {
var gender = $("#gender").val();
var qualification = $("#qualification").val();
var hobbies = $("#hobbies").val();
var location = $("#location").val();
var company = $("#company").val();
var designation = $("#designation").val();
}}
$.ajax({
url: "register.php",
type: "POST",
data: "username="+username+"& password="+password+"& gender="+gender+"& qualification="+qualification+"& hobbies="+hobbies+"& location="+location+"& company="+company+"& designation="+designation,
success: function(data, status, xhr) {
$('#reg-data').html(data);
$('#username').val('');
$('#password').val('');
$('#gender').val('');
$('#qualification').val('');
$('#hobbies').val('');
$('#location').val('');
$('#company').val('');
$('#designation').val('');
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message); }
});
});
});
</script>
</body>
Now i've another ajax request, but confused of where to put that.
<script src="jquery-1.8.0.min.js"></script>
<script>
$(document).ready(function(){
$('#username').keyup(check_username);
});
function check_username(){
var username = $('#username').val();
$.ajax({
type: 'POST',
url: 'check_username.php',
data: 'username='+ username,
cache: false,
success: function(response){
if(response == 0){
alert('Username available')
}
else {
alert('Username not available')
}
}
});
}
</script>
You can keep it one after another
there is no harm in concecutive Ajax request in one file
<script>
$(document).ready(function() {
// for user registration
$('#reg').click(function(e) {
e.preventDefault();
var username = $("#username").val();
if( username == '') {
alert('Enter the username');
header('location: register.html');
} else {
var password = $("#password").val();
if( password == '') {
alert('Enter the password');
header('location: register.html');
} else {
var gender = $("#gender").val();
var qualification = $("#qualification").val();
var hobbies = $("#hobbies").val();
var location = $("#location").val();
var company = $("#company").val();
var designation = $("#designation").val();
}}
$.ajax({
url: "register.php",
type: "POST",
data: "username="+username+"& password="+password+"& gender="+gender+"& qualification="+qualification+"& hobbies="+hobbies+"& location="+location+"& company="+company+"& designation="+designation,
success: function(data, status, xhr) {
$('#reg-data').html(data);
$('#username').val('');
$('#password').val('');
$('#gender').val('');
$('#qualification').val('');
$('#hobbies').val('');
$('#location').val('');
$('#company').val('');
$('#designation').val('');
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message); }
});
});
// check username
$('#username').keyup(function(){
var username = $(this).val();
$.ajax({
type: 'POST',
url: 'check_username.php',
data: 'username='+ username,
cache: false,
success: function(response){
if(response == 0){
alert('Username available')
}
else {
alert('Username not available')
}
}
});
});
});
</script>
OR
Create a file registration.js and paste the whole code in it without script tag and include it in your file
<script src='path/to/registration.js'></script>
try with this...
function check_username(){
$.ajax({
type: 'POST',
url: 'check_username.php',
data: 'username='+ $('#username').val(),
cache: false,
success: function(response){
return response;
}
});
}
and in validation
var successStatus = check_username();
if(successStatus != 1){
alert('username already Exist');
return false;
}

jquery/php form in modal window

I have a form in a modal window. When I submit the form through ajax I don't get the success message. My aim is to see the message created in the php file in the modal after submitting the form. Here is the code:
<p><a class='activate_modal' name='modal_window' href='#'>Sign Up</a></p>
<div id='mask' class='close_modal'></div>
<div id='modal_window' class='modal_window'>
<form name="field" method="post" id="form">
<label for="username">Username:</label><br>
<input name="username" id="username" type="text"/><span id="gif"><span>
<span id="user_error"></span><br><br>
<label for="email">Email:</label><br>
<input name="email" id="email" type="text"/><span id="gif3"></span>
<span id="email_error"></span><br><br>
<input name="submit" type="submit" value="Register" id="submit"/>
</form>
</div>
The modal.js
$('.activate_modal').click(function(){
var modal_id = $(this).attr('name');
show_modal(modal_id);
});
$('.close_modal').click(function(){
close_modal();
});
$(document).keydown(function(e){
if (e.keyCode == 27){
close_modal();
}
});
function close_modal(){
$('#mask').fadeOut(500);
$('.modal_window').fadeOut(500);
}
function show_modal(modal_id){
$('#mask').css({ 'display' : 'block', opacity : 0});
$('#mask').fadeTo(500,0.7);
$('#'+modal_id).fadeIn(500);
}
The test.js for the registration of the user
$(function() {
$('#form').submit(function() {
$.ajax({
type: "POST",
url: "test.php",
data: $("#form").serialize(),
success: function(data) {
$('#form').replaceWith(data);
}
});
});
});
And the PHP FILE
<?php
$mysqli = new mysqli('127.0.0.1', 'root', '', 'project');
$username = $_POST['username'];
$email = $_POST['email'];
$mysqli->query("INSERT INTO `project`.`registration` (`username`,`email`) VALUES ('$username','$email')");
$result = $mysqli->affected_rows;
if($result > 0) {
echo 'Welcome';
} else {
echo 'ERROR!';
}
?>
Try putting the returncode from your AJAX call into
$('#modal_window')
instead of in the form
$('#form')
BTW: Why not use the POST or GET method of jQuery? They're incredibly easy to use...
Try something like this.
First write ajax code using jquery.
<script type="text/javascript">
function submitForm()
{
var str = jQuery( "form" ).serialize();
jQuery.ajax({
type: "POST",
url: '<?php echo BaseUrl()."myurl/"; ?>',
data: str,
format: "json",
success: function(data) {
var obj = JSON.parse(data);
if( obj[0] === 'error')
{
jQuery("#error").html(obj[1]);
}else{
jQuery("#success").html(obj[1]);
setTimeout(function () {
jQuery.fancybox.close();
}, 2500);
}
}
});
}
</script>
while in php write code for error and success messages like this :
if(//condition true){
echo json_encode(array("success"," successfully Done.."));
}else{
echo json_encode(array("error","Some error.."));
}
Hopes this help you.

Categories