Save form data using AJAX to PHP - javascript

How can I save the form data in a file or a local db (maybe using AJAX) which send the data via form action to an external db?
The source code for my form is here: http://jsbin.com/ojUjEKa/1/edit
What changes (if any) should I make to the code?
EDIT:
Right. So I'm able to store the data into localStorage using AJAX and want to send the data stored across to a file called backend.php. Here's my html file: http://jsbin.com/iSorEYu/1/edit
and here's my backend.php file: http://jsbin.com/OGIbEDuX/1/edit
The AJAX is working absolutely fine to store the fields in localStorage but things go wrong when it tries to send the data across to backend.php. I receive the following errors:
[24-Jan-2014 08:40:34 America/Chicago] PHP Notice: Undefined index: data in /home4/private/public_html/marketer/backend.php on line 7
[24-Jan-2014 08:40:34 America/Chicago] PHP Warning: Invalid argument supplied for foreach() in /home4/private/public_html/marketer/backend.php on line 10
[24-Jan-2014 08:40:58 America/Chicago] PHP Notice: Undefined index: data in /home4/private/public_html/marketer/backend.php on line 7
[24-Jan-2014 08:40:58 America/Chicago] PHP Warning: Invalid argument supplied for foreach() in /home4/private/public_html/marketer/backend.php on line 10
What's the issue here?

LocalStorage would be your best bet. I would suggest using storejs as their API is straight forward, easy to use, and x-browser.
You could then trigger the form values to be stored on the "blur" event of each field.
$('input').on('blur', function (e) {
var el = e.target;
store.set(el.attr('name'), el.val());
});
When you are ready to submit to the server, you could use something like the following:
$('#formID').on('submit', function (e) {
e.preventDefault();
$.post('/my/save/route', store.getAll(), function () { ... });
});
You of course could do all of this without storejs and use vanilla JS to interact with the native LocalStorage API.

PHP:
<h1>Below is the data retrieved from SERVER</h1>
<?php
date_default_timezone_set('America/Chicago'); // CDT
echo '<h2>Server Timezone : ' . date_default_timezone_get() . '</h2>';
$current_date = date('d/m/Y == H:i:s ');
print "<h2>Server Time : " . $current_date . "</h2>";
$dataObject = $_POST; //Fetching all posts
echo "<pre>"; //making the dump look nice in html.
var_dump($dataObject);
echo "</pre>";
//Writes it as json to the file, you can transform it any way you want
$json = json_encode($dataObject);
file_put_contents('your_data.txt', $json);
?>
JS:
<script type="text/javascript">
$(document).ready(function(){
localStorage.clear();
$("form").on("submit", function() {
if(window.localStorage!==undefined) {
var fields = $(this).serialize();
localStorage.setItem("eloqua-fields", JSON.stringify( fields ));
alert("Stored Succesfully");
$(this).find("input[type=text]").val("");
alert("Now Passing stored data to Server through AJAX jQuery");
$.ajax({
type: "POST",
url: "backend.php",
data: fields,
success: function(data) {
$('#output').html(data);
}
});
} else {
alert("Storage Failed. Try refreshing");
}
});
});
</script>

Related

AJAX Sends data to PHP file, but PHP can't get data from $_POST

I am making a page on a website in PHP where a user fills out 3 fields and hits submit. The submit button should call my AJAX function to send the data to a database connection PHP file. I can confirm the data is sent from AJAX (via an alert) and the function returns a Success. This must mean my database query file is not interpreting the data correctly. Please help me understand where I went wrong.
Code from php page where the form is:
<script type="text/javascript">
function storeInvoice() {
//var c_name = document.getElementById('c_name');
//var c_license = document.getElementById('c_license');
//var c_licenseemail = document.getElementById('c_licenseemail');
var data=$('#myForm').serialize();
$.ajax({
url: "/paydb.php",
type: "POST",
data: data,
async:false,
dataType:'html',
success: function (value) {
alert("Sent: "+data);
}
});
}
</script>
Relevant Code from Database php file:
mysqli_select_db($conn, "main_db" );
$c_license = $_POST['c_license'];
$c_name = $_POST['c_name'];
$c_licenseemail = $_POST['c_licenseemail'];
//Another method was attempted below.
//$data=$_POST['serialize'];
//$c_licenseemail = $data['c_licenseemail'];
//$c_license = $data['c_license'];
//$c_name = $data['c_name'];
$query = "INSERT INTO `invoices`(`company`, `licensenum`, `licenseemail`) VALUES ('$c_name','$c_license','$c_licenseemail');";
mysqli_query($conn, $query);
The data is sent as:
c_name=testname&c_license=3&c_licenseemail=testemail%40email.com
Any help is much appreciated!
Please use the
mysqli_query($conn, $query) or die(mysqli_error($conn));
For duplicate key, you need to make the primary key to auto increment in your database.
In your success callback function replace alert(data) with alert(value) and in your database.php file echo any of the post variables to just check whether the values are correctly sent to database.php via ajax post.

Load php function in js file and use function

I have the following php function.
public function dateIndaysoff($mydate=false){
if(!$mydate)return false;
$host = "localhost";
$user = "user";
$pass = "pass";
$databaseName = "database";
$tableName = "table";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
// $db=JFactory::getDbo();
$dbs->setQuery("select date from table WHERE `date`='$mydate'")->query();
return (int) $db->loadResult();
}
This function searches an input value inside a database table column and if it finds then we have a TRUE, else FALSE.
So, i have a jquery inside .js file where i execute a specific action and i want to check if i have a TRUE or FALSE result. In jquery i use a variable called val. So inside jquery in some place i want to have something like this:
if (dateIndaysoff(val)) {something}
Any ideas?
Instead of wrapping the php code in a function you can wrap it in a if($_POST['checkDate']){//your code here}, then in javascript make an ajax request (http://www.w3schools.com/ajax/), which sends a parameter named checkDate and in the success block of the ajax call you can have your code you represented as {something}
function checkDate(){
$.post('yourPhpFile.php', {checkDate:$dateToBeChecked}, function(data){
if(data){alert("true")};
});
};
and the php:
if($_POST['checkDate']){
//your current function, $_POST['checkDate'] is the parameter sent from js
}
Just to work with your current code.
In your php file lets say datasource.php
echo dateIndaysoff()
In your requesting file lets say index.php
$.ajax({
url: "index.php",
context: document.body
}).done(function( data ) {
/* do whatever you want here */
});
You can do it with AJaX. Something like this:
A PHP file with all the functions you are using (functions.php):
function test($data) {
// ...
}
A JS to request the data:
function getTest() {
$.ajax('getTestByAJaX.php', {
"data": {"param1": "test"},
"success": function(data, status, xhr) {
}
});
}
getTestByAJaX.php. A PHP that gets the AJaX call and executes the PHP function.
require 'functions.php';
if (isset($_REQUEST["param1"])) {
echo test($_REQUEST["param1"]);
}
Ok if i got this right i have to do this:
1st) Create a .php file where i will insert my php function and above the function i will put this:
$mydate = $_POST['val'];
where $mydate is the result of the function as you can see from my first post and val is the variable i want to put in $mydate from ajax.
2nd) I will go inside .js file. Now here is the problem. Here i have a code like this:
jQuery(".datepicker").change(function() {
var val = jQuery(this).datepicker().val();
console.log(val);
if (dateIndaysoff(val)) {
console.log("hide");
jQuery('.chzn-drop li:nth-child(9)').hide();
jQuery('.chzn-drop li:nth-child(10)').hide();
} else {
console.log("show");
jQuery('.chzn-drop li:nth-child(9)').show();
jQuery('.chzn-drop li:nth-child(10)').show();
}
});
Inside this code, in the first if, i want to see if the variable val is inside my database table. So, how could i write correctly this jQuery with the Ajax you propose in order for this to work? Also please take a look maybe i have a mistake in my php function (in this function i want to connect with a database and take a TRUE if $myvalue is inside a table column)

Using Ajax and JSON to display PHP echo message in HTML

Ive been trying to connect my PHP file to my HTML file using Javascript/jQuery and json. When the user inputs a number into the input box in the form and submits it, the PHP file should multiply the number by two and send it back to the user.
However when I press the submit button it takes me to the php page instead of displaying the information (processed in the php file) in HTML.
This is my HTML form:
<div id="formdiv">
<form action="phpfile.php" method="get" name="form1" id="form1" class="js-php">
Mata in ett nummer: <input id="fill1" name="fill1" type="text" />
<input type="submit" id="submit1" name="submit1" value="submit">
</form>
This is my Javascript file
$(".js-php").submit(function(e){
var data = {
"fill1"
};
data = $(this).serialize() + $.param(data);
$.ajax({
type:"GET",
datatype:"json",
url:"phpfile.php",
data: data,
success: function (data){
$("#formdiv").append("Your input: "+data)
alert (data);
}
})
e.preventDefault();
});
PHP file:
$kvantitet = $_GET['fill1'];
$y = 2;
$work = $kvantitet * $y;
$bork = $work * $kvantitet;
echo json_encode($work) ."<br>";
echo json_encode($bork);
There are a few things you could do a bit differently here to make this work:
Currently, using both .serialize and $.param your data variable contains something like this:
someurl.php?fill1=1&0=f&1=i&2=l&3=l&4=1&5=%3D&6=1
If you use only .serialize you will get something easier to work with:
?fill1=5
On the PHP side, currently your code outputs something like this:
4<br>8
By adding your values to an array you can get a response back that you can work with:
$result = array();
$kvantitet = $_GET['fill1']; // Lets say this is 5
$y = 2;
$work = $kvantitet * $y;
$bork = $work * $kvantitet;
//add the values to the $result array
$result = array(
"work" => $work,
"bork" => $bork
);
echo json_encode($result);
Which will output:
{"work":4,"bork":8}
Back on the JS side you can then handle the data in your success callback:
$(".js-php").submit(function(e){
data = $(this).serialize();
$.ajax({
type:"GET",
datatype:"json",
url:"phpfile.php",
data: data,
success: function (data){
// *data* is an object - {"work":4,"bork":8}
$("#formdiv").append("Your input: "+data)
console(data);
}
});
// Use return false to prevent default form submission
return false;
});
One way to access the properties in your object is by using dot notation:
data.work //Outputs 4
data.bork //Outputs 8
But here is a really great answer on processing / accessing objects and arrays using JavaScript.
Here is a Fiddle containing your (working) jQuery
You are expecting JSON Data but what you send back is not JSON
Try output the following in your PHP File:
$data['work'] = $work;
$data['bork'] = $bork;
echo json_encode( (object)$data );
Use console.log to inspect incoming data on the AJAX call then handle it according to how you want.
I think you need &
data = $(this).serialize()+'&'+$.param(data);
and as #leonardo_palma mentioned in comments maybe you need to use e.preventDefault(); in the beginning of submit function
and I prefer to use
$(document).on('submit','.js-php',function(){/*code here*/});

Unable to send jQuery variable with string content to PHP using jQuery AJAX function?

The code snippet for the jQuery function looks like:
function addMessage() {
if (textval != "") {
text_string='<div class="alert-box round"><p class="text-left">' + userName + ':' + textval + '</p></div></br>';
alert(text_string);
$.ajax({
type:"POST",
url:"process.php",
data: {'text_string': text_string},
cache:false,
success:function(){
alert("submitted")
}
});
$("input[type=text]:last").val("");
}
enterButton = 0;
}
The process.php code looks like:
<body>
<?php
//$host = "localhost";
$text_string=$_POST['text_string'];
echo "string submitted is".$text_string;
?>
</body>
I get alerts showing value of text_string and then the "submitted", but when I open the php page, it shows an error:
Undefined index: text_string
I've seen various answers, none of them seem to be the case for mine. Is the problem in PHP code or jQuery code or both?
If you want to save the value passed by the AJAX request for the next time you load "process.php", try saving it in the session. So, you could change your code to:
<?php
session_start();
// Store value in session if it is passed
if (isset($_POST['text_string'])){
$_SESSION['text_string'] = $_POST['text_string'];
}
// Read and echo value from session if it is set
else if (isset($_SESSION['text_string'])){
$text_string=$_SESSION['text_string'];
echo "string submitted is".$text_string;
}
?>
Now, your PHP script will store the passed value in the session, and will echo that stored value should you load the page elsewhere. (Another alternative is to store the value in a database...though I'm not sure if you have one set up at the moment.)
Hope this helps! Let me know if you have any questions.

Ajax POST is not posting onclick to current page

Alright so this has been bugging me for a long time now... I have tried everything but I cant get it to work!
So what I want to have is a link that acts as a button, and once you click it, it POSTs an ID number of the button in the form "{ 'id' : id }"
edit-homepage.php:
<script>
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
// after you get response from server
editSlide(id);
});
});
});
</script>
The a href button is created using PHP and I want it to call the ajax function postID( id ) which will post the id so that later I can populate a form via PHP using the posted id.
edit-homepage.php:
echo '<li><a class="inactive" id="slide-'.$info["id"].
'" onClick="postID('.$info["id"].'); editSlide('.$info["id"].'); return false;">'
.'<img src="../images/'.$info["img"].'" width="175"/><p>Edit Slide '
. $info["id"] .'</p></a></li>';
Currently, when I click the link, it opens the alert but it is EMPTY or Undefined. It is supposed to display "ID: 1" for example if the link clicked has a ID of 1.
edit-homepage.php:
<script>
function editSlide($id) {
<?PHP
if (isset ($_POST['id'])) {
echo "alert('success!2');";
}$id = !empty($_POST['id']) ? $_POST['id'] : '';
$data = mysql_query("SELECT * FROM slider WHERE id='$id'") or die(mysql_error());
$info = mysql_fetch_array( $data );?>
document.getElementById("edit-slide-id").innerHTML="Edit Slide #"+$id;
document.getElementById("edit-form").style.display = "block";
document.getElementById("short-title").value="<?PHP echo $info['s_title']; ?>";
}
</script>
Thanks!
With jquery, you don't need to use attributes to attach events, like that:
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
alert('ID:' + response);
// after you get response from server
editSlide(id);
});
});
});
As of server side, try replacing raw
<?PHP echo $_POST['id']; ?>
With
<?php echo !empty($_POST['id']) ? $_POST['id'] : '' ?>
You likely get notice about Undefined index id, which breaks javascript if there is no post data.
UPDATE
edit-homepage.php shold be separated something like that:
if(!empty($_POST)) {
// here you process your post data and return
// only wenever you want to pass to script
// not all the html
} else {
// here you output html and scripts, but don't do request processing
}
You should always remember, that your HTML rendering must always be separated from your logic. It is better to put views in separate files from logic, though it is not required, it is much easier to debug and maintain.
You can not include PHP code that is supposedly to run after the ajax call. The PHP code will be run only to generate the page. Anything you want to include in alert should be provided in the ajax response, in your case the data variable.
You need to use alert('ID: ' + id).
The $_POST['id'] part of the script does not react to the AJAX request. It is whatever the $_POST['id'] value is when the script is output to the browser (i.e. when the page is first loaded).
You will see this if you view the source.
alert ("ID:"+data);
then only you will get response
or
alert("ID"+id);
this will alert the id passes to function
http://jsfiddle.net/U54ME/
$(".checkthisclass").click(function() {
$.ajax({
type: "POST",
url: "edit-homepage.php",
data: { 'id' : $(this).attr("slideid"); },
success: function(data) {
alert(data);
}
});
}
});
--
<ul>
<li><a class="inactive checkthisclass" id="slide-5" slideid = "5" ><img src="http://blog.entelo.com/wp-content/uploads/2013/04/stackoverflow-logo.png" width="175"/><p>Edit Slide 5</p></a></li>
</ul>

Categories

Resources