Im want to implement Ajax in php mvc project, i want to add a user into the database using ajax.
i tried to follow a youtube tutorial but couldn't insert the data, here is my index.html page:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1,shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="views/css/bootstrap.min.css" >
</head>
<body>
<div class="container">
<form>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter Email">
</div>
<button type="submit" onclick="saveData()">Add</button>
</form>
</div>
<!-- jQuery first, then Tether, then Bootstrap JS. -->
<script src="views/js/jquery.js"></script>
<script src="views/js/bootstrap.min.js" ></script>
<script>
function saveData(){
var name=$('#name').val();
var email=$('#email').val();
$.ajax({
type: "POST",
url: "?controller=pages&action=add",
data: "name="+name+"&email"+email,
success:function(msg){
alert('Success,ajotuer fil base');
}
});
}
</script>
</body>
</html>
and here is my controller funciton :
public function add(){
if (isset($_POST['name']) || isset($_POST['email'])){
echo 'error couldnt retreive inputs';
}
else {
$name = $_POST['name'];
$email = $_POST['email'];
User::save($name,$email);
}
}
the user.php file
public static function save($name,$email){
$db = Db::getInstance();
$req = $db->prepare("INSERT into user(id,name,email) VALUES ('',?,?)");
$req->bindParam(1,$name);
$req->bindParam(2,$email);
$req->execute();
}
UPDATE 1:Added full index.html file
I see two problems at first glance:
First, in your JS code, you've misspelled function:
success:fucntion(msg){ // <-- fuCNtion should be fuNCtion
alert('Success,ajotuer fil base');
}
Second, in your PHP code, you haven't escaped the quotation mark in your string. If you use a single quotation mark in your string, either use double quotes around the string or escape the single quotation mark:
if (isset($_POST['name']) || isset($_POST['email'])){
echo 'error couldn\'t retrieve inputs'; // or:
echo "error couldn't retrieve inputs";
}
Try that and let us know if that works.
Related
I've put together a codebase that successfully calls Ajax to a PHP server which issues requests to a database. I'm very new to this, but I've been able to successfully update rows in the SQL.
The good news is it doesn't update that row if there are already values in email, name, and redeem time columns. How do I cause the program to make errors if the coupon code has already been redeemed, though?
Is using a test query a possible approach? Or should I try to set up a separate Ajax request..possibly a Get to do a comparative evaluation on submission with the values in the form? But even if that is the case I have no idea how to actually implement that sort of conditional in PHP. Thanks if you have any advice.
//user_process.php
<?php
$con = mysqli_connect(); //<--redacted ;D
//first, test with what should be in the db
//with defaults.
$testcode=$_GET["code"];
$testname="Unredeemed";
$testemail="N/a";
$testredeemed="0000/00/00 00:00:00";
$testquery=mysqli_query($con,"SELECT code,name,email,redeemed FROM codestore WHERE code='$testcode', name='$testname', email='$email', redeemed='$testredeemed'");
if($testcode){
if(!$testquery){
die("Er");
}
}
$code=$_POST["code"];
$name=$_POST["name"];
$email=$_POST["email"];
$redeemed=$_POST["redeemed"];
$query=mysqli_query($con,"UPDATE codestore SET name='$name', email='$email', redeemed='$redeemed' WHERE code='$code',name='Unredeemed',email='N/a',redeemed='0000/00/00 00:00:00'");
if($query){
echo "Your comment has been sent";
}
else{
echo "Error in sending your comment";
}
?>
//user_index.js
function formatDate(date) {
//deleted for readability
}
$("#submit").click(function (event) {
$(".main-content").append("<?php require 'user_process.php';?> ");
// if() each has a value else alert error
var currentDateTime = new Date();
var redeemedOn = formatDate(currentDateTime);
var code = $("#code").val();
var name = $("#name").val();
var email = $("#email").val();
$.ajax({
type: "post"
, url: "user_process.php"
, data: "code=" + code + "&name="+name+"&email="+email+"&redeemed="+redeemedOn
, success: function (data) {
$("#info").html(data);
}
, error: function(){
alert("That code is invalid or has already been redeemed!")
}
});
});
//index.php
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" href="/demo_mini.css">
<title>Search Contacts</title>
</head>
<body>
<div class="main-content">
<form class="form-basic">
<div class="form-row"> <span>Enter your code </span>
<input type="text" name="code" id="code"> </div>
<div class="form-row"> <span>Full Name </span>
<input type="text" name="name" id="name"> </div>
<div class="form-row"> <span>Email</span>
<input type="text" name="email" id="email"> </div>
<div class="form-row">
<button id="submit">Redeem!</button>
</div>
<div id="info" /> </form>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="/user_index.js"></script>
</body>
</html>
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>
For the life of me I can't figure out why the following code is not working. I'm quite inexperienced so any assistance appreciated.
I want to get a simple connection working where an ajax call will return a username from a mySQL DB (this is a precursor to a much larger project). My HTML file is the following:
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="jquery/test-theme.min.css"/>
<link href="jquery/jquery.mobile.icons.min.css" rel="stylesheet" />
<link href="jquery/jquery.mobile.structure-1.4.5.min.css" rel="stylesheet" />
<link href="jquery/app.css" rel="stylesheet" />
<script src="jquery/jquery-2.1.4.min.js"></script>
<script src="jquery/jquery.mobile-1.4.5.min.js"></script>
<script> function login(){
$(document).ready(function(){
var user = $("#username")[0].value;
var email = $("#email")[0].value;
$.ajax({
type: "GET",
url: "http://localhost:8888/test/connection.php",
data: "username="+user+"&email="+email,
success: function(result){
if(result){
$("#message")[0].value = "Success" +result;
}
else{
$("#message")[0].value = "Fail :(";
}
},
error: function(result){
$("#message")[0].value = "Ajax error!"+result;
}
});
});
}
</script>
</head>
<body>
<div data-role="page">
<div data-role="header" data-theme="c">
<h1>Sign Up!</h1>
</div><!-- /header -->
<div role="main" class="ui-content">
<h3>Sign Up</h3>
<label for="txt-first-name">Username</label>
<input type="text" name="txt-first-name" id="username" value="" onkeyup="login()">
<label for="txt-email">Email Address</label>
<input type="text" name="txt-email" id="email" value="" onkeyup="login()">
<input type="text" id="message"></input>
<button id="submit" onclick="login()"> Submit</button>
<div data-role="popup" id="dlg-sign-up-sent" data-dismissible="false" style="max-width:400px;">
</div>
</div><!-- /content -->
</div>
</body>
</html>
And my PHP:
<?php
$user = $_REQUEST['username'];
$email = $_REQUEST['email'];
mysql_connect("localhost:8889","root","root") or die(mysql_error());
mysql_select_db("TEST") or die(mysql_error());
$result = mysql_query("SELECT username, email FROM login WHERE username ='$user'");
while($row = mysql_fetch_array($result)){
if($user = $row["username"]){
echo $row["id"];
}
else{
echo "failed getting user"
}
}
?>
I have a DB called TEST running via MAMP with some entries in the login table for username and email. I just want to get the connection running properly but I'm stumped.
I am new to jquery and phonegap and i am un able to find an answer to my question anywhere.
This is my index.html
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Auth Demo 2</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css" />
<script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>
<script src="jquery.mobile/jquery-1.7.2.min.js"></script>
<script src="jquery.mobile/jquery.mobile-1.1.0.min.js"></script>
<script src="main.js"></script>
</head>
<body onload="init()">
<div id="launcherPage" data-role="page">
<!-- I'm just here waiting for deviceReady -->
</div>
<div id="loginPage" data-role="page">
<div data-role="header">
<h1>Auth Demo</h1>
</div>
<div data-role="content">
<form id="loginForm">
<div data-role="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username" />
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password" />
</div>
<input type="submit" value="Login" id="submitButton">
</form>
</div>
<div data-role="footer">
<h4>© Camden Enterprises</h4>
</div>
</div>
</body>
</html>
And my Js.
function init() {
document.addEventListener("deviceready", deviceReady, true);
delete init;
}
function checkPreAuth() {
console.log("checkPreAuth");
var form = $("#loginForm");
if(window.localStorage["username"] != undefined && window.localStorage["password"] != undefined) {
$("#username", form).val(window.localStorage["username"]);
$("#password", form).val(window.localStorage["password"]);
handleLogin();
}
}
function handleLogin(){
var form = $("#loginForm");
var u = $("#username", form).val();
var p = $("#password", form).val();
//remove all the class add the messagebox classes and start fading
if(u != '' && p!= '') {
$.post("http://www.myaddress.com/loginlogin.php",{ user_name:$('#username', form).val(),password:$('#password', form).val(),rand:Math.random() } ,function(data)
{
if(data=='yes') //if correct login detail
{
//store
window.localStorage["username"] = u;
window.localStorage["password"] = p;
// $.mobile.changePage("some.html");
$.mobile.changePage( "some.html", { transition: "slideup"} );
}
else
{
navigator.notification.alert("Your login failed", function() {});
}
});
} else {
//Thanks Igor!
navigator.notification.alert("You must enter a username and password", function() {});
$("#submitButton").removeAttr("disabled");
}
return false;//not to post the form physically
}
function deviceReady() {
console.log("deviceReady");
$("#loginPage").on("pageinit",function() {
console.log("pageinit run");
$("#loginForm").on("submit",handleLogin);
checkPreAuth();
});
$.mobile.changePage("#loginPage");
}
Non of this is my own work but from here
http://www.raymondcamden.com/index.cfm/2011/11/10/Example-of-serverbased-login-with-PhoneGap
I changed the the example to work with php. This is very simple and only for testing purposes
php here
<?//get the posted values
require_once("backend/functions.php");
dbconn(true);
$username = $_POST['user_name'];
if ($username=='Steven'){
echo "yes";
}else{
echo "no";
}
?>
Now this all works and when the conditions are met the page some.html opens.
Now my question is .
How would i send the username of the logged in person to the page some.html?
once confirmed from the php file.
You should be able to access
window.localStorage["username"]
on your some.html page
I have a html form and I am making the json object as:
var JSobObject=
'{"name":"'+personObject.GetPersonName()+
'","about":"'+personObject.GetAbout()+
'","contact":"'+personObject.GetPersonContact()+'"}';
(Here personObject holds the form data)
trying to post it to Server.php as:
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//var url = "organizePeople.php?people=" + escape(people.toJSONString());
xmlhttp.open("POST","ServerJSON.php?person="+JSobObject,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(JSobObject);
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState==4) {
alert(xmlhttp.responseText);
}
}
I am not getting any response from the server.php In my server i am doing this
$person = $_POST['person'];
$objArray = json_decode($person);
print_r($objArray);
Can anyone help me that what I am doing wrong? I am in the learning stage. Just using JS/AJAX I want to prepare JSON and send it to server and get the response of the object datas.
Thanks in advance
I prefer that, you do this with jQuery. It is JavaScript based library to do things (like this) easier.
$.post({
url: "Server.php",
data: JSobObject,
dataType: "json"
}).done(function(msg) {
alert(msg);
});
You need to download jQuery - of course - to get code to working!
2 thoughts I'm having.
First of all, I'd sugest you move the xmlhttp.onreadystatechange assigment to above the send() call.
Secondly, have you checked with firebug if you're getting any reponse?
Have you tried calling your php page directly, rather than through ajax?
I'm not 100% sure, but probably you'll want something like
$data = json_decode($_POST, true);
$person = $data['person'];
The reason being you're post data is entirely a JSON encoded text string, so you'll need to decode the entire post before you can access the data separately.
You should check the rawpost from php first,
$_POST maybe fill slashes Automatedly
Use this code will help you
<!DOCTYPE html>
<html>
<head>
<title>Servlet Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<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/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="js/jquery.serializeJSON.min.js"></script>
</head>
<body>
<div class="jumbotron text-center">
<h1>Submit form Data to Database in JSON</h1>
</div>
<div class="container">
<div class="row">
<div class="col-sm-3"></div>
<div class="col-sm-5">
<h3>Enter the Details : </h3>
<form name="myform" id="myform">
<div class="form-group">
<label for="fullName">Name:</label>
<input type="text" name="fullName" class="form-control">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" name="email" class="form-control">
</div>
<div class="form-group">
<label for="subject">Subject:</label>
<input type="text" name="subject" class="form-control">
</div>
<div class="form-group">
<label for="mark">Mark:</label>
<input type="number" name="mark" class="form-control">
</form>
</div>
<button type="submit" class="btn btn-success " id="submitform">Submit</button>
</div>
<div class="col-sm-3"></div>
</div>
<script>
$(document).ready(function(){
$("#submitform").click(function(e)
{
var MyForm = JSON.stringify($("#myform").serializeJSON());
console.log(MyForm);
$.ajax(
{
url : "<your url>",
type: "POST",
data : MyForm,
});
e.preventDefault(); //STOP default action
});
});
</script>
</body>
</html>