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>
Related
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
I am trying to send a JSON string to a PHP file via ajax. The issue is that the variable I'm posting over is not being delivered when I use the JQUERY ajax method as shown below:
<DOCTYPE html>
<html>
<head>
<title>Assignment 4</title>
<!-- 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.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-sm-4"></div>
<div class="col-sm-4">
<form action="json.php" method="POST">
<div class="form-group">
<label for="email">Username:</label>
<input type="text" class="form-control" id="userid" name="userid">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="pwd">
</div>
<button type="submit" class="btn btn-default" id='btn' onclick="JSONstring()">Submit</button>
</form>
</div>
<div class="col-sm-4"></div>
<script>
function JSONstring() {
obj = {
username: "",
password: "",
}
obj.username = document.getElementById('userid').value;
obj.password = document.getElementById('pwd').value;
console.log(obj.username + ", " + obj.password);
var jsonObj = JSON.stringify(obj);
$.ajax({
type: 'POST',
url: 'json.php',
data: {
json: jsonObj
},
dataType: 'json'
});
}
</script>
</body>
</html>
Oddly enough when I try and AJAX the old fashioned way, I am able to get the RAW POST data that I would expect:
var jsonObj = JSON.stringify(obj);
request = new XMLHttpRequest();
request.open("POST", "json.php", true);
request.setRequestHeader("Content-type", "application/json");
request.send(obj);
My php file is simply trying to get the variable and dump it:
<?php
$directions = json_decode($_POST['json']);
var_dump($directions);
?>
Can someone please point me in the right direction?
dataType only means that you expect a JSON response.
Try using contentType instead.
$.ajax({
type: 'POST',
contentType: "application/json",
url: 'json.php',
data: {
json: jsonObj
},
dataType: 'json'
});
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.
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"
Currently Im trying to do ajax request using jQuery Mobile. I`m trying to use example on http://www.giantflyingsaucer.com/blog/?p=2574. Yes, it works perfectly. But problems was coming when i tried to use the code inside codeigniter.
Here is my controller :
<?php
class Ajax extends CI_Controller {
function __construct() {
}
function index() {
?>
<!DOCTYPE html>
<html>
<head>
<title>Submit a form via AJAX</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a4/jquery.mobile-1.0a4.min.css" />
<script src="http://code.jquery.com/jquery-1.5.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0a4/jquery.mobile-1.0a4.min.js"></script>
</head>
<body>
<script>
function onSuccess(data, status)
{
data = $.trim(data);
$("#notification").text(data);
}
function onError(data, status)
{
// handle an error
}
$(document).ready(function() {
$("#submit").click(function(){
var formData = $("#callAjaxForm").serialize();
$.ajax({
type: "POST",
url: "callajax",
cache: false,
data: formData,
success: onSuccess,
error: onError
});
return false;
});
});
</script>
<!-- call ajax page -->
<div data-role="page" id="callAjaxPage">
<div data-role="header">
<h1>Call Ajax</h1>
</div>
<div data-role="content">
<form id="callAjaxForm">
<div data-role="fieldcontain">
<label for="firstName">First Name</label>
<input type="text" name="firstName" id="firstName" value="" />
<label for="lastName">Last Name</label>
<input type="text" name="lastName" id="lastName" value="" />
<h3 id="notification"></h3>
<button data-theme="b" id="submit" type="submit">Submit</button>
</div>
</form>
</div>
<div data-role="footer">
<h1>GiantFlyingSaucer</h1>
</div>
</div>
</body>
</html>
<?php
}
function callajax() {
echo "ok";
}
}
I want to display 'ok' in notification. Im trying to call function callajax instead of call from callajax.php is this possible or do I need to create callajax.php?
Ive tried to create callajax.php but it was failed.
Thank you,
You probably want the url to be:
url: "ajax/callajax",
As you are calling the callajax function within the controller ajax.