How to save DIV content to HTML file using AJAX/JQuery/PHP? - php

I am struggling with getting this code to work. My intention is to be able to save the contents of a div to an html file, so that I can recall it later...
It works partially, in that if I change $data=$_POST['id'] to $data=$_POST['memory'] in readInput.php it will indeed save any text I enter into the input named 'memory' to an html file, and will correctly save the file with whatever name I give it. Where it fails is if I try to grab the data of DIV 'readDiv' and its contents $data=$_POST['id']; it will save a blank html page, with whatever name I gave it... Here is the code:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>readInput</title>
<meta name="description" content="HTML5 web page">
<meta name="keywords" content="HTML5">
<meta name="author" content="You">
<meta charset="UTF-8">
<link href="jquery-ui.htm" rel="stylesheet" type="text/css">
<script type="text/javascript" src="jquery-latest.htm"></script>
<script name="saveMemory" type="text/javascript">
$(document).ready(function() {
$('#saveMemory').click(function() {
//e.preventDefault();
var content = $('#readDiv').html(); // orig
//var content = document.getElementById('readDiv').value; // test
$.ajax({
type: 'POST',
url: 'readInput.php',
data: {id: content}
//dataType: "html" // test
});
});
});
</script>
</head>
<body onload="document.readWrite.writeInput.focus();"><!--form name.input name.focus!-->
<div id="formContainer" style="display:block">
<form name="readWrite" action="readInput.php" method="POST">
<input name="memory" placeholder="...enter text here..." type="text">
<input name="readMemory" id="readMemory" class="readMemory" placeholder="...read..." type="text">
<input id="writeInput" name="writeInput" class="writeInput" placeholder="...write..." type="text">
<input class="saveMemory" id="saveMemory" name="saveMemory" value="...saveMemory..." type="submit">
</form></div>
<div name="readDiv" id="readDiv" class="readDiv">
<div id="writeDiv" class="writeDiv" title="writeDiv">test text
<div id="topDropbox" class="topDropbox" title="topDropbox">
<img src="car.jpg">
</div></div></div>
</body></html>
readInput.php:
<?php
$writeInput = $_POST['writeInput'];
$data = $_POST['id'];
$fileName = ("memories/$writeInput.html");
$fileHandle = fopen($fileName, 'w+') or die("Cannot open file");
fwrite($fileHandle, $data);
fclose($fileHandle);
echo($fileName);
echo($data);
?>
It probably looks like a horrible hack job to you pros because I have tried so many bits of code, and I am sure I am just missing something silly, but I am at a loss...thank you anyone for any help!

This update should do the trick:
$(document).ready(function() {
$('#saveMemory').click(function(e) {
e.preventDefault();
var content = $('#readDiv').html(); // orig
//var content = document.getElementById('readDiv').value; // test
$.ajax({
type: 'POST',
url: 'readInput.php',
data: {id: content, writeInput : $('#writeInput').val()}
//dataType: "html" // test
}).done(
function( data ){
$('#result).html( data);
}
);
});
});
Changes:
Added e to the click function. It provides the function with a reference to the event object.
Uncommented e.preventDefault() so the form won't execute breaking the ajax call.
Added writeInput to the post data.
Added a callback (.done). When the request is finished this function will execute writing the responseData into writeDiv
Add the following div directly in the body tag.
<div id="result" style="background-color: #f4f4f4;width:100%;height:300px;overflow: auto"></div>

Related

Ajax Query Isn't Going Through to PHP Script

I am trying to run a simple scenario in which: a form is submitted -> jquery ajax request for JSON data -> PHP script reads from the database and encodes to JSON -> data is shown on my page.
the fields on the MySQL are: Name and Password
step 1 - my form - Search.php
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="Query.js"></script>
<title></title>
</head>
<body>
<form method="post" id="formoid" action="">
<input type="text" name="enterpass" placeholder="Enter Password">
<input type="submit" name="subbpass">
</form>
<input type="text" id="showname"><br/>
<input type="text" id="showpassword">
step 2 - my jquery file- Query.js
$(document).ready(function(){
$("#formoid").submit(function(){
alert("form submitted") // this alert goes through
var passid = $("#enterpass").val();
$.ajax({
url: "ModelQuery.php",
method: "POST",
dataType: "JSON",
data: {args: passid},
success: function(data)
{
console.log('ajax successfully sent'); // this alert isn't working
$("#showname").text(data.Name); // data isn't showing here
$("#showpassword").text(data.Password);
console.log(data); // or here ...
}
});
});
});
and lastly, my php -- ModelQuery.php -- I omitted some code lines but that script is the normal script for reading from the database and has worked for me in the past.
<?php
if(isset($_POST['args'])) {
$arg = $_POST['args']
$CON = mysqli_connect('127.0.0.1','root','','testdb');
// ....
$QUERY = "SELECT * FROM testtable where Password = '$arg'";
// ...
while($row = mysqli_fetch_array($RESULT))
{
$jsonresults["Name"] = $row['Name'];
$jsonresults["Password"] = $row['Password'];
}
echo json_encode($jsonresults);
}
the alert in the Jquery script right after the form is submitted does go through, but the ajax itself doesn't show anything, neither on the console nor on my two textboxs.
What am I doing wrong here?
Thank you very much!
I figured out the issue, which consisted of 3 different problems:
1) my input textbox <input type="text" name="enterpass" placeholder="Enter Password"> didn't have id attribute, only name
2) as #RamRaider suggested, I changed it to button and gave it id as well.
3) one of the lines in the php didn't have ; at its end..
Thanks you!

How to pass the values to php script using ajax?

I have written a code to pass values of input fields to a php script using ajax but it is not working. Can anyone suggest how to rectify this code ? I want to display the values passed through ajax in the php file.
ex.php
<?php
$temp = $_POST['start_date'];
$name = $_POST['end_date'];
echo $temp.$name;
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").change(function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
$.ajax({
method: "POST",
url: "ex.php", // path to php file
data: { start_date: fname, end_date: lname } // send required data here
})
.done(function( msg ) {
});
});
});
</script>
</head>
<body>
<form action="#" method="post" name="form1">
<input type="text" name="fname" id="fname"/>
<input type="text" name="lname" id="lname"/>
</form>
</body>
</html>
try using below code :
<?php
$temp = $_POST['start_date'];
$name = $_POST['end_date'];
echo $temp.$name;
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").change(function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
var post = "&start_date=" + fname + "&end_date=" + lname;
$.ajax({
'url': ex.php,
'data': post,
'type': 'POST',
'success': function (data)
{
}
});
});
});
</script>
</head>
<body>
<form action="" method="post" name="form1">
<input type="text" name="fname" id="fname"/>
<input type="text" name="lname" id="lname"/>
</form>
</body>
</html>
Add an element to your makeup
<span id="idOfSomeElementYouWantToUse"></span>
and in your callback set it's text.
.done(function( msg ) {
$("#idOfSomeElementYouWantToUse").text(msg);
});
Add a div to your page and use html() to append the data that comes from the ajax request
<body>
<form action="#" method="post" name="form1">
<input type="text" name="fname" id="fname"/>
<input type="text" name="lname" id="lname"/>
</form>
<div class="ajax-result"></div>
</body>
js:
$("input").change(function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
$.ajax({
method: "POST",
url: "other_file.php", // path to php file
data: { start_date: fname, end_date: lname }, // send required data here
success:function(data){
$(',ajax-result').htm(data);
}
});
Note: from what i can tell you are ajaxing to the same page,i strongly suggest you create a new php file(other_file.php) with your logic in it
From what I can understand from your comment above, you want to insert textbox value to the database, to do this you don't want to call ajax on textChange event because at that time not all value will be present, I suggest adding submit button to the form and call ajax on form submit.
Here is the main file:
ajax_ex.php (You should name it as per your requirement)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<form id="frmInsert" method="post" name="form1">
<input type="text" name="fname" id="fname"/>
<input type="text" name="lname" id="lname"/>
<input type="submit" value="Insert" />
</form>
<div id="msg">
</div>
</body>
<!-- You should put javascript at bottom -->
<script src="jQuery-2.1.4.min.js"></script>
<script type="text/javascript">
$("#frmInsert").submit(function(e){
var fname = $("#fname").val();
var lname = $("#lname").val();
$.ajax({
method: "POST",
url: "insert.php", // path to php file
data: { start_date: fname, end_date: lname } // send required data here
})
.done(function( msg ) {
msg = $.trim(msg);
if (msg == 'true') {
$('#msg').html("Data is inserted successfully");
}else {
$('#msg').html("Data insertion failed");
}
});
e.preventDefault();
});
And you should not call the same file in ajax, I recommend that you create individual file that will be called in ajax, this file will handle all back-end processing.
insert.php
<?php
//Check if post data is available (You should also check for particular attribute if it is available)
if (!empty($_POST)) {
$temp = $_POST['start_date'];
$name = $_POST['end_date'];
//Insert Data into database
// Your code
$result = 'true'; //check for operation if it is success and store it in result
//Echo result so you can check if insert is success of not in your ajax callback.
echo $result;
}
?>

Manipulating Form Values After jQuery.load

Good evening everyone,
I am currently trying to cleanup my inline JS and break it up into its own .js file, as well as breaking up some of my code into functions. Below I provide my code, I have an HTML file with an empty div named #main. On document ready I want to call my firstLoad function. It simply calls $("#main").load("login.php"); Seems simple enough, however my next step is that on submit of the form I want to serialize the submitted data, turn to string and submit via post. This for some reason will work if I hard code the form into the index.php file, but not if I use .load to fill in #main. I can't figure out why this is, I am sure it's simple if someone could explain it little that would be wonderful. My code follows:
UPDATE
After more searching I came across this thread that says the following:
As it turns out, the jquery .load() function is working flawlessly,
and I'm approaching this wrong.
Once the .load() function completes successfully, it calls any
"callback" function included by the programmer, just like any other
jquery function that accepts a callback as one of its "arguments". The
.load() function is complete once it either errors or successfully
begins the HTML replacement and loading of new content, but that is
IT! The content will then take however long it takes to load, but your
.load call is already complete before that. Therefore, expecting the
callback to run after the .load content has loaded will only
disappoint you. ;)
I hope others can learn from this just as I did, including those who
thought what I thought was the case. Proof: as stated in the jquery
ajax .load page, the callback is executed when the request completes,
not when the load completes. Eureka. Whoops.
Which leads to the follow up question, how can I manipulate the form after the load content has been added to the DOM? This is surely a simple fix, but I am new to AJAX and could use a nudge in the right direction. I notice adding a document(ready) within the login.php script works properly as it is added with the html, but it doesn't seem like the cleanest way of doing things, as I'm trying to keep out inline JS. Any more advice?
/UPDATE
PHP/HTML
index.php
<?php
session_start();
$sessionNumber = session_id();
?>
<!doctype html>
<!-- Conditional comment for mobile ie7 blogs.msdn.com/b/iemobile/ -->
<!--[if IEMobile 7 ]> <html class="no-js iem7" lang="en"> <![endif]-->
<!--[if (gt IEMobile 7)|!(IEMobile)]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<title>MyMobile</title>
<meta name="description" content="">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="img/h/apple-touch-icon.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="img/m/apple-touch-icon.png">
<link rel="apple-touch-icon-precomposed" href="img/l/apple-touch-icon-precomposed.png">
<link rel="shortcut icon" href="img/l/apple-touch-icon.png">
<meta http-equiv="cleartype" content="on">
<link rel="stylesheet" href="css/style.css">
<script src="js/libs/modernizr-2.0.6.min.js"></script>
</head>
<body>
<div id="container">
<header id="header">
<img alt="Logo" src="img/logo.png" />
<div id="blackHead">Please sign-in to continue</div>
</header>
<div id="main" role="main">
</div>
<footer id="footer">
<div id="greyFoot">
© 2012 ACME<br />
<pre id="result"></pre>
</div>
</footer>
</div> <!--! end of #container -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.7.1.min.js"><\/script>')</script>
<script type="text/javascript" src="js/firstLoad.js"></script>
</body>
</html>
login.php
<?php session_start();
$sessionNumber = session_id();
?>
<!-- begin login form -->
<?php if(isset($_SESSION['sessionemail'])){ ?>
Logout
<?php }else { ?>
<form id="logForm" name="login" method="post" action="#">
<label for="sessionemail">Email</label><br />
<input id="sessionemail" type="email" name="sessionemail" autofocus="autofocus" autocapitalize="off" maxlength="150" required="true" value="" class="inputText" /><br />
<label for="password">Password</label>
<input id="password" type="password" name="password" required="true" value="" class="inputText" /><br />
<br />
<input type="hidden" name="sessionid" id="sessionid" value="<?php echo $sessionNumber; ?>" />
<input type="hidden" name="subtocall" id="subtocall" value="g2.web.login.sub" />
<input type="submit" value="Sign-In" name="submit" class="submitBox" />
</form><!-- end login form -->
<?php } ?>
And finally, my JS/Jquery
firstLoad.js
//function serializes our object
(function($){
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
//firstLoad function runs on document ready
//it loads the login form into the main div and slides
//the container down
(function($){
$.fn.firstLoad = function(){
return this.each(function() {
$("#container").slideUp("slow", function(){
$("#main").load('./login.php', function(){
$("#container").slideDown("slow", function(){
});
});
});
});
};
})(jQuery);
//logParse takes the loginResponse from the server
//changes from string to object, runs a check for authentication then
//manipulates the object dropping excess keys and adding new relevant ones for
//the intial to do list call
(function($){
$.fn.logParse = function(xml){
return this.each(function() {
//parse the JSON login check string from the XML response
var loginResponse = $(xml).find('string').text();
//setup isBad variable for error check
var isBad = false;
//convert to JSON object from parsed string data
loginResponse = $.parseJSON(loginResponse);
//check if the sessionID is correct and user authenticated properly
if((loginResponse.SESSIONID != "<?php echo $sessionNumber; ?>") || (loginResponse.ISAUTHENTICATED == 0)){isBad = true;}
//if error flag is raised alert and bounce back to login
if(isBad){
alert("Unauthorized connection, please try again.");
}
//if there are no errors
else{
alert("so far so good!");
//set up a new JSON object for to do list passback
//and import the values from the lognResponse object
//var todoPost =
}
});
};
})(jQuery);
$(document).ready(function(){
//hide screen for slidedown
//$("#container").addClass("noShow");
//allow cross domain scripts
$.support.cors = true;
//call firstLoad function to slide in the login prompt
$("#main").firstLoad(function(){
//create JSON object to store form input for AJAX POST
//create submit listener
$("#logForm").submit(function(){
alert("inside submit");
//parse form into formObj for data passing and manipulation
var formObj = JSON.stringify($("form").serializeObject());
//output initial formObj into result pane
$("#result").text(formObj);
$("#main").text("submitted: " + formObj);
//AJAX POST call
$.ajax({
//type of communication
type: "POST",
//action for form
url: "http://mydomain.com/JSONService.asmx/G2WebRequest",
//data to be passed
data: "request="+ formObj,
//type of data passed in
contentType: "application/x-www-form-urlencoded; charset=utf-8",
//enable cross domain
crossDomain: "true",
//data type returned from webservice
dataType: "xml",
//if login POST was successful
success: function(xml){
alert("post successful");
$.logParse(xml);
},
//if login POST failed
error: function(XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
});
You are probably setting up the listener on $("#logForm") before the login form is fully loaded into the DOM. This would explain why the login form works when hardcoded. You can test this by alert($("#logForm").length);- this will be zero if not found.
If this is the case you will need to ensure you wait until the login page is completely loaded before attempting to attach the listener. I would probably make firstLoad call a function once load completes.
Good luck.
JQuery.on() solved this issue. Took me a while to figure that out.

jquery-ajax: pass values from a textfield to a php variable (same a file)

jquery-ajax: pass values from a textfield to php file and show the value
i made a variation of the link above this time using only one file and no div tag.
test.php
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var dataString = $("#inputtext").val();
$.ajax({
type: "POST",
url: "test.php",
data: "dataString=" + dataString,
success: function(result){
window.location.reload(true);
}
});
window.location.reload(true);
});
});
</script>
</head>
<body>
<input type="text" id="inputtext">
<input type="button" id="submit" value="send">
<?PHP
if(isset($_POST['dataString'])){
$searchquery = trim($_POST['dataString']);
print "Hello " . $searchquery;
}
?>
</body>
</html>
value from dataString won't show. why?
Sorry for the question, but what's the point of using ajax to reload the same page?? Use it to call another page and then load the result, not the way you're doing it.
Try this
In test.php:
$("#submit").click(function(){
var dataString = $("#inputtext").val();
$.ajax({
type: "POST",
url: "anothepage.php",
data: dataString,
success: function(result){
$('#result').html(result).
}
});
return false; //so the browser doesn't actually reload the page
});
And you should actually use a form, not just inputs. And use the name attribute for them, or php won't pick the value! ID is for javascript and css.
<form method="POST" action="">
<input type="text" id="inputtext" value="" name="inputtext">
<input type="submit" id="submit" value="send" name="submit">
</form>
<div id="result"> <!-- result from ajax call will be written here --> </div>
In anotherpage.php:
if(isset($_POST['inputtext'])){
$searchquery = trim($_POST['inputtext']);
echo htmlentities($searchquery); // We don't want people to write malicious scripts here and have them printed and run on the page, wouldn't we?
}
When you refresh the page using JavaScript, you lose any POST parameters you sent to the page. That is one reason why you never saw any valid results.
You are also missing the benefits from using AJAX - A motivating reason to deploy AJAX is to remove the requirement to refresh the page while still accepting and processing user input.
If you prefer to process the data from AJAX on the same page that is serving the HTML, here is a working example based on your supplied code.
<?php
if( isset($_POST['dataString']))
{
echo 'Hello ' . trim( $_POST['dataString']);
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Testing jQuery AJAX</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var dataString = $("#inputtext").val();
$.ajax({
type: "POST",
url: "test.php",
data: "dataString=" + dataString,
success: function( data){
alert( data);
}
});
});
});
</script>
</head>
<body>
<form action="test.php" method="post">
<input type="text" id="inputtext" />
<input type="button" id="submit" value="send" />
</form>
</body>
</html>

jQuery AJAX live update on multiple elements on the same page

I'm delving into some AJAX and I'm trying to utilise jQuery.
I have an index page which links to multiple pages and next to each page is a view count.
I would like the view count to refresh and automatically update every couple of seconds so that those on the page can view live updates of the page counts.
I've come accross the following script that works well based on a single Ajax element on the page, but what about 10 or more?
Is there a more efficient way (short of cutting and pasting the statement 10 times) to get all the fields to update individually?
<?php
// File: ajax.php
// Ajax refresh hits
if(isset($_GET['refresh'])){
// Uses the get_page_views() function which takes an ID and retreives that page view count. The ID is passed by the AJAX script.
if($_GET['refresh'] == 'hits') echo get_page_views($_GET['id']);
};
?>
This si the code to the HTML page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax - PHP example</title>
<script language="javascript" type="text/javascript" src="jquery-1.3.2.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
//ajax.php is called every second to get view count from server
var ajaxDelay = 1000;
setInterval(function(){
// Refresh details.
$('#zone-111').load('ajax.php?refresh=hits&id=111');
$(#zone-222').load('ajax.php?refresh=hits&id=222');
$(#zone-333').load('ajax.php?refresh=hits&id=333');
$(#zone-444').load('ajax.php?refresh=hits&id=444');
$(#zone-555').load('ajax.php?refresh=hits&id=555');
}, ajaxDelay);
});
</script>
</head>
<body>
<div align="center" id="zone-111">--</div>
<br />
<div align="center" id="zone-222">--</div>
<br />
<div align="center" id="zone-333">--</div>
<br />
<div align="center" id="zone-444">--</div>
<br />
<div align="center" id="zone-555">--</div>
<br />
</body>
</html>
Any suggestion on how I can make this script/code more efficient would be greatly accepted.
Kind regards,
P.
Send all of the ids at once as a JSON array. On the server side, build a JSON object containing key/value pairs of the ids/counts. Then iterate through the keys on the client when you get the result and set each count in turn in the related DIV.
$(document).ready(function(){
//ajax.php is called every second to get view count from server
var ajaxDelay = 1000;
var ids = [];
$('[id^="zone-"]').each( function() {
ids.push( this.id );
});
setInterval(function(){
$.ajax({
url: 'ajax.php',
dataType: 'json',
type: 'get',
data: { refresh: 'hits', ids: ids },
success: function(data) {
for (var key in data) {
var div = $('#zone-' + key).html( data[key] );
}
}
});
}, ajaxDelay);
});
Thanks for the JSON suggestions, I wasn't quite sure how to implement it though and I've come up with this solution that works quite well so far. Feedback would be great.
<script type="text/javascript" language="javascript">
$(document).ready(function(){
setInterval(function(){
$('.views').each(function(){
$(this).load('ajax.php?id='+this.id);
});
}, 5000);
});
</script>
And in the HTML you just assign the class 'views' to the element that you want updated and the store the 'ID' as the id eg:
<p class="views" id="123"><!-- content appears here. --></p>

Categories