PHP OOP AJAX Form Submission Array Wont Append - php

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.

Related

Issue with displaying the Jquery Ajax result

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.

jQuery ajax post using FormData() append data element can't find the appended data element after post

I use the code from talkerscode.com to implement file upload using drag and drop. The code is working. Now I would like to add additional input value during in the same ajax post. I add an input tag called "user_id" in the following html code. And I append the element into the formdata object. After the change drag and drop upload still work, but the PHP code complain the $_POST["user_id"] is not defined. Here is my code. Please help!
<html>
<!-- code original from talkerscode.com -->
<head>
<link rel="stylesheet" type="text/css" href="upload_style.css">
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div id="wrapper">
<input type="text" name="user_id", id="user_id" value="1228">
<input type="file">
<div id="drop-area">
<h3 class="drop-text">Drag and Drop Images Here</h3>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function()
{
$("#drop-area").on('dragenter', function (e){
e.preventDefault();
$(this).css('background', '#BBD5B8');
});
$("#drop-area").on('dragover', function (e){
e.preventDefault();
});
$("#drop-area").on('drop', function (e){
$(this).css('background', '#D8F9D3');
e.preventDefault();
var image = e.originalEvent.dataTransfer.files;
createFormData(image);
});
});
function createFormData(image)
{
var formImage = new FormData();
formImage.append('userImage', image[0]);
formData.append('user_id', $('#user_id').val());
uploadFormData(formImage);
}
function uploadFormData(formData)
{
$.ajax({
url: "upload_image.php",
type: "POST",
data: formData,
contentType:false,
cache: false,
processData: false,
success: function(data){
$('#drop-area').html(data);
}});
}
</script>
----------------PHP code -------------------
<?php
if(is_array($_FILES))
{
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
$sourcePath = $_FILES['userImage']['tmp_name'];
$targetPath = "images/".$_FILES['userImage']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
?>
<img src="<?php echo $targetPath; ?>">
<p> user_id = <?php echo $_POST["user_id"] ?> </p>
<?php
exit();
}
}
}
?>
-----------------------------------------------
function createFormData(image) {
var formImage = new FormData();
formImage.append('userImage', image[0]);
formData.append('user_id', $('#user_id').val()); //change formData to formImage
uploadFormData(formImage);
}
From:
formData.append('user_id', $('#user_id').val());
to:
formImage.append('user_id', $('#user_id').val());

Angular $http.post() returning html code

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>

Post form with ajax and update div

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.

get and show constant from external webpage and update when change

this script receive time from www.time.is and from #twd ID and show when click on the send btn.
I have two problems:
1-only show first receive time and don't update when click on send again
2- page refresh and lose data
I have Three problem with below code:
<?php include 'simple_html_dom.php'; ?>
<!DOCTYPE html>
<html>
<head>
<title>Untitled 1</title>
<script src="js/jquery.js"></script>
</head>
<body>
<form action="" method="POST">
<input id="url" name="url" type="text" value="http://www.time.is/">
<input id="address" name="address" type="text" value="#twd">
<input id="send" type="submit" value="get">
</form>
<ul id="times">
</ul>
<script type="text/javascript">
$("#send").click(function(events) {
events.preventDefault();
var url = $("#url").val();
var address = $("#address").val();
var dataString = 'url=' + url + '&address=' + address;
$.ajax({
type: "POST",
url: "read.php",
data: dataString,
success: function() {
var result = "<?php echo getme($url,$address); ?>";
alert(result);
$('#times').append('<li></li>');
}
});
return true;
});
</script>
<?php
function getme($url, $address) {
$html = file_get_html($url);
$code = $html->find($address, 0);
return $code;
}
echo getme($url, $address);
?>
</body>
</html>
any body can help me ..
Thanx all
Try this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function timer(){
$.post( "process.php", function( data ) {
$('#times').append('<li>'+data+'</li>');
});
}
setInterval(function(){timer()},1000);
});
</script>
</head>
<body>
<ul id="times"></ul>
</body>
</html>
And put this in your process.php file:
<?php
include 'simple_html_dom.php';
$html = file_get_html('http://www.time.is/');
foreach($html->find('#clock0') as $element){
echo $element->plaintext;
}
?>
This is my test result:
11:15:43AM
11:15:46AM
11:15:51AM
11:15:53AM
11:15:53AM
11:16:10AM
11:15:52AM
11:15:42AM
11:16:09AM
11:16:17AM
11:16:12AM
Note:
1- It is advisable that you change intervals from 1000 milliseconds (1 second).
2- Don't forget to use clearInterval() after specific repeat.

Categories