form action not working after ajax successful - php

I have a form with file upload. I want to perform to two task: one is data submit to the database and upload file through ajax and after ajax successful another is going to form action.ajax are work properly but after ajax successful form action is not working
Kindly help
main.php
<!doctype html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
function mycall() {
//disable the default form submission
event.preventDefault();
//grab all form data
var formData = new FormData(document.getElementById('data'));
$.ajax({
url: 'addToMySQL.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
alert(returndata);
}
});
return false;
}
</script>
</head>
<body>
<form method='post' enctype="multipart/form-data" id="data" action="try.php" >
<div class="form-input">
<label for="exampleSelect1" class="col-md-3 control-label">Type of Paper</label>
<div class="col-md-9">
<select class="form-control" id="Otop" name="Otop" required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
</div>
<div class="col-md-12">
<div class="form-input">
<label for="exampleSelect1" class="col-md-3 control-label">Paper upload</label>
<div class="col-md-9">
<input type="file" id="file" name="profileImg" >
</div>
</div>
</div>
<div class="form-input">
<div class="col-sm-12">
<input type="submit" class="btn btn-primary btn-lg btn-block" onclick="mycall()" name="OrderSubmit" value="Order">
</div>
</div>
</form>
</body>
</html>
addToMySQL.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
include("dbconfig.php");
include('class/userClass.php');
$userClass = new userClass();
$Otop = $_POST['Otop'];
$Odiscipline = $_FILES['profileImg']['name'];
$target = "uploads/";
$fileTarget = $target.$Odiscipline;
$result = move_uploaded_file($_FILES['profileImg']['tmp_name'], "uploads/".$_FILES['profileImg']['name']);
$id = $userClass->userOrderInfo($Otop,$Odiscipline, $fileTarget);
if ($id) {
echo "done";
} else {
echo "Notdone";
}
userOrderInfo fuction in userClass.php
/* User Payment */
public function userOrderInfo($Otop, $Odiscipline, $fileTarget)
{
try {
$db = getDB();
$stmt = $db->prepare("INSERT INTO orderinfo(Otop, Odiscipline, fileTarget) VALUES (:Otop, :Odiscipline, :fileTarget)");
$stmt->bindParam("Odiscipline", $Odiscipline) ;
$stmt->bindParam("Otop", $Otop) ;
$stmt->bindParam("fileTarget", $fileTarget) ;
$stmt->execute();
$db = null;
return true;
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}

Ok to get this clear in my head, what your code is doing is this:
The form is filled out and you click "submit" which prevents form
default action from being submitted. Instead this takes the form
data and submits it via ajax to addToMySQL.php
addToMySQL.php then handles the upload of the file and calls userOrderInfo() on userClass.php
userOrderInfo will return either a (string) or (boolean) true both of which PHP will treat as true for the purposes of an if() statement.
addToMySQL.php returns a response of (string) "done" to main.php
The ajax call main.php takes the response from addToMySQL.php and triggers a javascript alert with the content of "done".
Because of the way this has been written, the form will never use it's action property and instead will just constantly try to ajax the content of the form to addToMySQL.php because you are using event.preventDefault();.
Solution
A quick solution would be to either add a javascript redirect to the ajax success method, or add hidden <form> with the action you want to send your user to do and then populate and send it with javascript once the file has uploaded.
Whatever way you decide to do it, I would recommend fixing addToMySQL.phpso it won't constantly send back "done"!

Related

PHP OOP AJAX Form Submission Array Wont Append

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.

Send $_POST and $_FILES together using AJAX data field so that PHP can grab the value?

I have the following form which has
a text field
date field
a file browser.
I am using AJAX to send the $_POST data values to another PHP file to insert into a MySQL database. But I want to move the $_FILES too.
In the $.ajax field, there is data: whereby I can assign those data to be transferred to another PHP file.
I am able to do it with the text field and date fields. How to do it for the $_FILES? My codes are as below
AJAX
<script>
$("#submit").click(function() {
var prjId = $('#prjId').val();
var updatedDate = $('#updatedDate').val();
$.ajax({
type: 'POST',
url: "process.php",
data: {prjId: prjId,updatedDate: updatedDate},
success: function(response) {('#resulting').html(response);}
});
});
</script>
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="icon" type="image/png" href="images/version-control.png">
<meta charset="utf-8">
<link href='https://fonts.googleapis.com/css?family=Raleway:400,300,700,900' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<link rel="stylesheet" type="text/css" href="style.css">
<body>
<body>
<div class="container" id="contactform">
<form method="post" enctype="multipart/form-data">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Project ID</label>
<div class="col-sm-7"><?php if(isset($_POST['prjId'])){echo '
<input type="text" class="form-control" placeholder="Project ID" name="prjId" id="prjId" value="'.$_POST['prjId'].'">';}else{echo'
<input type="text" class="form-control" placeholder="Project ID" name="prjId" id="prjId">';}?>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Updated Date</label>
<div class="col-sm-7"><?php if(isset($_POST['udatedDate'])){echo '
<input type="date" class="form-control" name = "updatedDate" id="updatedDate" value="'.$_POST['udatedDate'].'">';}else{echo '
<input type="date" class="form-control" name = "updatedDate" id="updatedDate">';}?>
</div>
</div>
<fieldset class="form-group ">
<label class="btn btn-default tempPerm" id="techLabelText">
<input class="tempPerm" style="" type="file" name="file" id="techInputBoxValue" />
</label>
</fieldset>
</form>
<div class="cover">
<div id="result"></div>
<input name="submit" id="submit" tabindex="5" value="Send Mail" type="submit" style="width:200px;">
</div>
</div>
</body>
</html>
PHP
<?php include ("../db.php");?>
<?php
$prjId = $_POST['prjId'];
$updatedDate = $_POST['updatedDate'];
if(isset($prjId)){
$sql="INSERT INTO tbl_uploads(prjId, date) VALUES('$prjId','$updatedDate')";
mysqli_query($conn, $sql);
}
?>
The code below automatically includes all fields from the form without manually adding them using the append function.
Also added $(document).ready(function() for fail safe. So the javascript code only takes effect when the whole document is ready.
You can try tinker with these working template.
<script>
$(document).ready(function() {
$("#submit").click(function() {
var FD = new FormData($('form')[0]);
$.ajax({
type: 'POST',
url: "process.php",
processData: false,
contentType: false,
data: FD,
success: function(response) {
$('#resulting').html(response);
}
});
});
});
</script>
process.php
<?php include ("../db.php");?>
<?php
$prjId = $_POST['prjId'];
$updatedDate = $_POST['updatedDate'];
if(isset($_POST['prjId'])){
$target_dir = "uploads/";
$target_file = $target_dir.basename($_FILES["file"]["name"]);
$save_file = basename($target_file); // this holds the filename to save.
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$is_uploaded = move_uploaded_file($_FILES["file"]["tmp_name"], $target_file));
// Modify this query string to add the file uploaded as well.
// Change the query string to use prepared statements for failure safe and for security reasons.
$sql="INSERT INTO tbl_uploads(prjId, date) VALUES('$prjId','$updatedDate')";
mysqli_query($conn, $sql);
}
?>
^ Added a simple file upload handler.
You can use formdata to send your files along with your request like this:
<script >
$("#submit").click(function() {
var formData = new FormData();
var prjid = $('#prjId').val();
var updatedDate = $('#updatedDate').val();
formData.append( 'file', input.files[0]);
formData.append('prjId', prjid);
formData.append('updatedDate', updatedDate);
$.ajax({
type: 'POST',
url: "process.php",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(response) {
$('#resulting').html(response);
}
});
});
</script>
If you submit form using ajax it will not pass $_FILES
you have to create object for that using FormData
note : please add enctype="multipart/form-data in form tag
<form id="upload" enctype="multipart/form-data">
please refer : jQuery AJAX file upload PHP
Thanks

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>

jQuery Mobile: How to correctly submit form data

This is a jQuery Mobile question, but it also relates to pure jQuery.
How can I post form data without page transition to the page set into form action attribute. I am building phonegap application and I don't want to directly access server side page.
I have tried few examples but each time form forwards me to the destination php file.
Intro
This example was created using jQuery Mobile 1.2. If you want to see recent example then take a look at this article or this more complex one. You will find 2 working examples explained in great details. If you have more questions ask them in the article comments section.
Form submitting is a constant jQuery Mobile problem.
There are few ways this can be achieved. I will list few of them.
Example 1 :
This is the best possible solution in case you are using phonegap application and you don't want to directly access a server side php. This is an correct solution if you want to create an phonegap iOS app.
index.html
<!DOCTYPE html>
<html>
<head>
<title>jQM Complex Demo</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<style>
#login-button {
margin-top: 30px;
}
</style>
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script src="js/index.js"></script>
</head>
<body>
<div data-role="page" id="login" data-theme="b">
<div data-role="header" data-theme="a">
<h3>Login Page</h3>
</div>
<div data-role="content">
<form id="check-user" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="username">Enter your username:</label>
<input type="text" value="" name="username" id="username"/>
</div>
<div data-role="fieldcontain">
<label for="password">Enter your password:</label>
<input type="password" value="" name="password" id="password"/>
</div>
<input type="button" data-theme="b" name="submit" id="submit" value="Submit">
</fieldset>
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
<div data-role="page" id="second">
<div data-theme="a" data-role="header">
<h3></h3>
</div>
<div data-role="content">
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>Page footer</h3>
</div>
</div>
</body>
</html>
check.php :
<?php
//$action = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
//$formData = json_decode($_REQUEST['formData']); // Decode JSON object into readable PHP object
//$username = $formData->{'username'}; // Get username from object
//$password = $formData->{'password'}; // Get password from object
// Lets say everything is in order
echo "Username = ";
?>
index.js :
$(document).on('pagebeforeshow', '#login', function(){
$(document).on('click', '#submit', function() { // catch the form's submit event
if($('#username').val().length > 0 && $('#password').val().length > 0){
// Send data to server through ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: 'check.php',
data: {action : 'login', formData : $('#check-user').serialize()}, // Convert a form to a JSON string representation
type: 'post',
async: true,
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
resultObject.formSubmitionResult = result;
$.mobile.changePage("#second");
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all nececery fields');
}
return false; // cancel original event to prevent form submitting
});
});
$(document).on('pagebeforeshow', '#second', function(){
$('#second [data-role="content"]').append('This is a result of form submition: ' + resultObject.formSubmitionResult);
});
var resultObject = {
formSubmitionResult : null
}
I have run into same issue where I am calling another .php page from my index.html.
The .php page was saving and retrieving data and drawing a piechart. However I found that when piechart drawing logic was added, the page will not load at all.
The culprit was the line that calls the .php page from my index.html:
<form action="store.php" method="post">
If I change this to:
<form action="store.php" method="post" data-ajax="false">
, it will work fine.
On using PHP and posting data
Use
data-ajax = "false" is the best option on <form> tag.
Problem is that JQuery Mobile uses ajax to submit the form. The simple solution to this is to disable the ajax and submit form as a normal form.
Simple solution: form action="" method="post" data-ajax="false"

Send JSON to server side using Ajax

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>

Categories