This is the error message found on google chrome:
POST http://localhost/display/register/registerUser 500 (Internal Server Error)
My project file name is "display".
One controller file named "register" ,it has a function called "registerUser". All it does is getting user's input, and compare it with database to see if the name is used or not, if valid store it into database and give them a success message, if not valid give a error message.
$username=$this->input->post('name');
$password=$this->input->post('password');
$result=$this->user->checkExistUser($username);
if(!$result){
$data=array(
'username'=>$username,
'password'=>md5($password)
);
$this->user->register($data);
echo "<script>alert('You have success registered');</script>";
$this->load->view('home_view');
}
else{
echo "<script>alert('Sorry, this email address has been used!');</script>";
$this->load->view('registerView');
}
This is my view file named registerView
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome to Stock game</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js">
</script>
</head>
<body>
<div id="container">
<h1>Welcome to Stock game!</h1>
<div id="body">
<p>This is the register page</p>
</div>
<div>
<form name="userform" id="userform" >
<input type="text" name="name" placeholder="Name"/>
<input type="text" name="password" placeholder="Password"/>
<button name="submit" value="submit">Register</button>
</form>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('form#userform').on('submit',function(e){
e.preventDefault();
var name=$("#name").val();
var password=$("#password").val();
$.ajax({
type:'POST',
url:'register/registerUser',
data:
{'name':JSON.stringify(name),'password':JSON.stringify(password)},
dataType:'JSON',
success: function(response){
if(response=="success"){
alert("Yes login");
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
});
});
</script>
</div>
<br/>
</body>
</html>
I have tested the controller and model class with a simple form post(form action=xxx, method=post) and it is no error.
I searched almost every stackoverflow questions about this, but i still cannot fix it, I hope someone can help me.
Spent around 5hrs on this question, I did a simple step and found the bug. What i do is modified name and password value by myself, so don't care what is the input, just to test if the data i modified will be sent to controller or not, the result is yes, it is stored in my database. So the bug should be the way how i read the input, after i put (id="name" before name="name") in the tag for name, and did the same thing for password tag, the server not give me 500 anymore.
You cannot load a view in ajax call
$this->load->view('home_view');
the above is wrong in the controller
change the controller to this code
$username=$this->input->post('name');
$password=$this->input->post('password');
$result=$this->user->checkExistUser($username);
if(!$result){
$data=array(
'username'=>$username,
'password'=>md5($password)
);
$this->user->register($data);
echo "1";
}
else{
echo "0";
}
in view file change your code to the below code
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome to Stock game</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<div id="container">
<h1>Welcome to Stock game!</h1>
<div id="body">
<p>This is the register page</p>
</div>
<div>
<form name="userform" id="userform" >
<input type="text" name="name" placeholder="Name"/>
<input type="text" name="password" placeholder="Password"/>
<button name="submit" value="submit">Register</button>
</form>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('form#userform').on('submit',function(e){
e.preventDefault();
var name=$("#name").val();
var password=$("#password").val();
$.ajax({
type:'POST',
url:'<?php echo base_url()."register/registerUser"; ?>',
data: {'name':name,'password':password},
success: function(response){
if(response=='0'){
alert("Failed");
// with the result you can redirect to the view that is in controller
window.href.location = '<?php echo base_url()."yoursuccesscontroller/yoursuccessfunction"; ?>';
}
else {
alert('Success');
//with failure
window.href.location = '<?php echo base_url()."yourfailurecontroller/yourfailurefunction"; ?>';
}
}
});
});
});
</script>
</div>
<br/>
</body>
</html>
with the result you can redirect to the view that is in controller
Append the base url in your ajax
url:<?php echo base_url(); ?>'register/registerUser',
Related
I just need to display names of the array using ajax. Following code is working but the result ( Nilantha Ruwan Nimal Shamitha Alex) is just display and disappears.
Index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
</head>
<body>
<div class="container" style="margin-top:50px";>
<form >
<div class="form-group">
<input type="text" id="name" class="form-control" placeholder="Enter Name....">
</div>
<div class="form-group">
<button class="btn btn-success" id="btn">Enter</button>
</div>
</form>
<div class="msg"></div>
</div>
<script type="text/javascript" src="assets/js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
var name = $("#name").val();
$.post("ajax.php",{ajax_name:name},function(response){
$(".msg").html(response);
})
.fail(function(error){
alert(error.statusText);
})
})
})
</script>
</body>
</html>
ajax.php
<?php
if(isset($_POST['ajax_name'])){
$store = array("Nilantha","Ruwan","Nimal","Shamitha","Alex");
foreach($store as $names) {
echo $names,"<br>";
}
}
?>
Try the following code.
<script type="text/javascript">
function submit() {
jQuery("form").submit(function(e) {
e.preventDefault();
var name = jQuery("#name").val();
jQuery.ajax({
type: 'POST',
url: 'ajax.php',
data: {ajax_name:name},
success: function(response) {
jQuery(".msg").html(response);
jQuery('#name').val('');
},
error: function() {
console.log("Something wrong");
}
});});
}
jQuery(document).ready(function() {
submit();
});
</script>
I would suggest looking at the network tab of Chrome Devtools and ensuring that the AJAX call isn't running twice. I would think that if the query ran twice but the second one did not have any name attached then it would return blank once the first one had received its response.
I have code with single page PHP method
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
<?php
if(isset($_POST['submit'])){
$date=$_POST['date'];
}else{
$date=date('Y-m-d');
}
?>
<form action="" method="post" id="formId">
<input type="text" name="date" id="datepicker">
<input type="submit" name="submit">
</form>
<?php echo $date; ?>
<script>
$(function() {
$('#datepicker').datepicker({
autoclose: true
})
});
</script>
how, if i want to use ajax to keep the page not to reload? please help me
ok so here is quick tutorial. ajax helps you to submit your form without page loading. You have to use action="somepage.php". when you click it it will pass the values there right away. so here is basic coding
<form id="formId">
<input type="text" name="dte" id="dte">
<button type="button" id="buttonsubmit">submit</button>
</form>
and ajax should be look like. In my coding id="buttonsubmit" is button id so when user will click it it run the function and takes the values
var dte;
$("#buttonsubmit").click(function(){
dte = $("#dte").val();
$.ajax({
url:"somepage.php",
method:"POST",
data:{dte: dte},
success: function (data){
if(data == "done"){
window.location='http://somedomain.com/';
}
}
});
});
in somepage.php you will have
<?php
if(isset($_POST['dte'])){
$date=$_POST['dte'];
echo "done";
}else{
$date=date('Y-m-d');
}
?>
note: i am writing echo "done"; in success method it will come and
according to code when success will see it will redirect the page
I am trying to do a post request using angular and getting the response as the html code of index.html. I am using zurb's foundation for apps.
<!doctype html>
<html lang="en" ng-app="application">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Foundation for Apps</title>
<link href="./assets/css/app.css" rel="stylesheet" type="text/css">
<script src="./assets/js/foundation.js"></script>
<script src="./assets/js/templates.js"></script>
<script src="./assets/js/routes.js"></script>
<script src="./assets/js/app.js"></script>
</head>
<body>
<div class="grid-frame vertical">
<div class="grid-content shrink" style="padding: 0;">
<ul class="primary condense menu-bar">
<li><a><strong>opt1</strong></a></li>
<li><a ui-sref="pros"><strong>opt2</strong></a></li>
</ul>
</div>
<div ui-view class="grid-content" >
</div>
</div>
</div>
</body>
</html>
home.html is by set as root so it will be displaying a login form
<form ng-controller="LoginController as login" ng-submit="login.loginProcess()">
<div class="grid-block">
<div class="grid-content">
<input type="text" name="username" ng-model="login.user.username">
</div>
<div class="grid-content">
<input type="password" name="password" ng-model="login.user.password">
</div>
<div class="grid-content">
<input type="submit" value="submit">
</div>
</div>
</form>
This is my app.js file
(function() {
'use strict';
var application = angular.module('application', [
'ui.router',
'ngAnimate',
//foundation
'foundation',
'foundation.dynamicRouting',
'foundation.dynamicRouting.animations'
])
.config(config)
.run(run)
;
config.$inject = ['$urlRouterProvider', '$locationProvider'];
function config($urlProvider, $locationProvider) {
$urlProvider.otherwise('/');
$locationProvider.html5Mode({
enabled:false,
requireBase: false
});
$locationProvider.hashPrefix('!');
}
function run() {
FastClick.attach(document.body);
};
application.controller('LoginController',['$scope','$http',function($scope,$http){
this.user = {};
this.loginProcess = function(){
console.log(JSON.stringify(this.user));
var postData = JSON.stringify(this.user);
var config = {method: 'POST', url: '/login.php', data:postData};
$http(config)
.success(function(data, status, headers, config) {
console.log(data);
})
.error(function(data, status, headers, config) {
$scope.errorMsg = 'Unable to submit form';
});
};
}]);
})();
Now as soon as i submit the form I am able to fetch the data properly from the form but it is not being posted properly since the html code of index.html is being displayed in the console when the success function runs.Please suggest a solution so that i will be able to fetch the data from the php file.
<?php
echo $_REQUEST['username'];
?>
and its not working even if I use
file_get_contents("php://input");
In login.php write your php code before any html code starts and add a die() before any html code starts.
login.php
<?php
/*
php code to login
*/
die();
?>
<html>
....
</html>
Hello so I have 2 submit buttons with different names (btn1, btn2) in my html form and what I am trying to do is to submit to another page without refreshing page. So what I wanted to do is if I click btn1 submit it will do something and if I click btn2 it will do another thing. My code in the html page is this
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Percentage</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$('#myForm').on('submit',function(e) {
$.ajax({
url:'update.php',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000); //===Show Error Message====
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<form method="POST" id="myForm">
Input Amount: <input type="text" name="txt_amount" required placeholder="Input number"> <br /> <br />
<span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
<input type="submit" name="btn1"> <input type="submit" name="btn2">
</form>
</body>
</html>
And the code in my update.php page
<?php
if(isset($_POST['btn1'])) {
//insert query
} else if(isset($_POST['btn2'])) {
//another insert query
}
?>
I actually got it working if I only have 1 submit button and no if(isset()) thing in the update.php page. What can I do to use 2 submits and with issets in another page without refreshing the main page?
$(this).serialize();
The above code statement doesn't include name of the submit button as a key value pair.
So, as people have suggested before me, you should use button instead of submit button. Something like this.
HTML and JS
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Percentage</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$('#btn1, #btn2').on('click',function(e) {
var datastr = $(this).serialize() + "&button_id="+$(this).attr('id');
$.ajax({
url:'update.php',
data:datastr,
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000); //===Show Error Message====
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<form method="POST" id="myForm" action="update.php">
Input Amount: <input type="text" name="txt_amount" required placeholder="Input number"> <br /> <br />
<span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
<button id="btn1">Button1</button><button id="btn2">Button2</button>
</form>
</body>
</html>
AND PHP would be:
<?php
if($_POST['button_id'] == 'btn1') {
//do something
} else if($_POST['button_id'] == 'btn2') {
//do something else;
}
?>
Use this, may useful for you
try
$('#myForm').on('submit',function(e) {
e.preventDefault();
});
OR
<button type="button">
Use on click event on the button and add the value attribute to the submit button, the value of the click button will be pased to the php file
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Percentage</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$('input[type="submit"]').on('click',function(e) {
e.preventDefault();
$.ajax({
url:'update.php',
data:{'txt_amount':$('input[name="txt_amount"]').val(),'btn': $('input[type="submit"]').val()}
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000); //===Show Error Message====
}
});
});
</script>
</head>
<body>
<form method="POST" id="myForm">
Input Amount: <input type="text" name="txt_amount" required placeholder="Input number"> <br /> <br />
<span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
<input type="submit" name="btn1" value="btn1"> <input type="submit" name="btn2" value="btn2">
</form>
</body>
</html>
php:
<?php
if($_POST['btn'] == 'btn1') {
//do something
} else if($_POST['btn'] == 'btn2') {
//do something else;
}
?>
I want to post simple form with ajax and update content of div (id result), but I get redirected to server.php file.
index.php:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script src="js/jquery.js"></script>
<script src="js/ajax.js" type="text/javascript"></script>
<form id="wbForm" action="server.php" method="POST">
Date1: <input type="text" name="date1" value="2000-01-21"><br>
Date2: <input type="text" name="date2" value="2000-01-02"><br>
<input type="submit" name="submit" value="Submit">
<div id="result"></div>
</form>
</body>
</html>
ajax.js:
$(document).ready(function showHint(form) {
$.ajax({
type:'POST',
url: 'server.php',
data:$('#wbForm').serialize(),
success: function(response) {
$('#wbForm').find('.result').html(response);
}});
});
server.php:
<?php
$input=$_POST;
//... compute something
echo "result";
?>
String "result" should appear in div with id=result, but I get redirected to /server.php where I can see "result", why?
HTML
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script src="js/jquery.js"></script>
<script src="js/ajax.js" type="text/javascript"></script>
<form id="wbForm" action="server.php" method="POST">
Date1: <input type="text" name="date1" value="2000-01-21"><br>
Date2: <input type="text" name="date2" value="2000-01-02"><br>
<input type="submit" name="submit" value="Submit">
<div id="result"></div>
</form>
</body>
</html>
ajax.php
$(document).on("ready", function(){
//Form action
$("#wbForm").on("submit", function(event){
// Stop submit event
event.preventDefault();
$.ajax({
type:'POST',
url: 'server.php',
data:$('#wbForm').serialize(),
success: function(response) {
$('#wbForm').find('.result').html(response);
}});
});
});
server.php
<?php
$input = $_POST;
print_r( $input );
?>
Happy Codding!!
There are several issues. First, you are getting redirected to server.php when you hit submit because of your form action "server.php". If you want the AJAX call to happen when clicking the button you should put the AJAX call in a JavaScript function and call that function onclick()
The reason the jQuery .AJAX call isn't triggering success is because it's expecting JSON. Try:
<?php
header("content-type:application/json");
$input=$_POST;
//... compute something
echo json_encode("result");
?>
Hope this helps.