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>
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 am trying to display the POST data of my form to the same page with Ajax. This is working fine but I am new to OOP and my class which builds an array with the POST content is getting overwritten on every request.
I understand I could post the data to a JSON file or Database but I wanted it to be solely displaying a "growing" array.
Index.php
<html>
<head>
<head>
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
<link href="https://fonts.googleapis.com/css?family=Poppins:400,500,600,700,800" rel="stylesheet">
</head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function () {
var frm = $('form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
$("#response").html(data);
}
});
ev.preventDefault();
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="flex40">
<div class="container40">
<form id="form" action="response.php" method="post">
<input name="postName" type="text" placeholder="Name" required>
<select name="postEyeColour">
<option>Blue</option>
<option>Red</option>
<option>Yellow</option>
<option>Green</option>
</select>
<button name="submit" type="submit">New Person</button>
</form>
<div class="character-table">
<table id="response"></table>
</div>
</div>
</div>
</div>
</body>
</html>
response.php
<?php
require_once 'Classes/Person.php';
$character = new Person;
if (isset($_POST['postName'])) {
$character->createNewPerson();
$character->getPersonList();
}
?>
Classes/Person.php
<?php
class Person {
private $personList = array();
public function createNewPerson() {
// Build Array From Post Data
$newPerson= array(
"Name" => $_POST['postName'],
"Eye Colour" => $_POST['postEyeColour']
);
//Push New Person to data array
$this->personList[] = $newPerson;
}
public function getPersonList() {
print_r($this->personList);
}
}
?>
What happens is that the data is posted to the array but every time I add some more data it is resetting the Array with the new data not appending it.
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',
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.
I have the following php script which works flawlessly in normal circumstances (i.e. visiting the page directly):
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="stylesheet" type="text/css" href="css/contact_search.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.watermarkinput.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).click(function() {
$("#display").hide();
});
var cache = {};
$("#searchbox").keyup(function() {
var searchbox = $(this).val();
var dataString = 'searchword=' + searchbox;
if (searchbox.length < 3 ) {
$("#display").hide();
} else {
$.ajax({
type: "POST",
url: "contact_search/search.php",
data: dataString,
cache: false,
success: function(html) {
$("#display").html(html).show();
}
});
return false;
});
});
jQuery(function($) {
$("#searchbox").Watermark("Search for Group");
});
</script>
</head>
<body bgcolor="#e0e0e0">
<div class="body">
<div class="liquid-round" style="width:100%;">
<div class="top"><span><h2>Contacts List</h2></span></div>
<div class="center-content">
<img src="images/search.gif" style="float:right;" />
<input type="text" id="searchbox" maxlength="20" value="<?php echo $_SESSION['hello'];?>" />
<div id="display"></div><div style="clear:both;"></div>
</div>
<div class="bottom"><span></span></div>
</div>
<div class="liquid-round" style="width:97%;">
<div class="top"><span><h2>My Messages</h2></span></div>
<div class="center-content" style="min-height:200px;">
</div>
<div class="bottom"><span></span></div>
</div>
</div>
</body>
</html>
HOWEVER - when I add the following piece to the top of the page, the javascript/jquery functions simply stop working altogether.
<?php
session_start();
if( $_SERVER['SERVER_PORT'] == 80) {
header('Location:https://'.$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"]);
die();
}
?>
These pages require login so I need to ensure they are https protected but this error messes all that up. Any ideas what could be causing the issue?
It's probably the browser not displaying insecure (http) content on https pages, there's a simple fix though, use a scheme relative URL, like this:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
This way you'll get http://ajax.googleapis.com/.... on the http:// version of your page and https://ajax.googleapis.com/.... on the https:// version.
Since session_start produces HTTP-Headers I recommend to do the port check before session_start.
But, these lines should not affect your JS in any circumstances, because the redirect to HTTPS is independend from the fact if your site is working via HTTPS. So, if you are not sure, remove the lines and access your page with HTTPS. Bring JS to work there. And afterwards implement the redirect.