Save text file with PHP using Javascript code - php

This is the code of a simply button.
<input value="Download" type="button" onclick=" inccount();" />
And here this is what inccount(); does:
function inccount() {
var a = parseInt(document.getElementById("num").value);
document.getElementById("num").value = a + 1;
}
As you can see, this function increments by 1 the number I have on the input field num. I'd like to save this number on my server, but if I call a php script with the <form> tag, the page changes.
I want save the content of count on my server without leaving the current page. Who could I do it?
I wrote this simply PHP script for save the content of the input field (that is called num):
<?php
$file = '/dat/count.txt';
$current = $_GET["num"];
file_put_contents($file, $current);
?>

To update a page without leaving it you need to investigate Ajax. From the linked page:
in the AJAX model, web applications are able to make quick,
incremental updates to the user interface without reloading the entire
browser page.
The Ajax call can be to a PHP script that writes to a text file.

You are Posting the Page to the Server. So, the Page will have changes..
You need to use AJAX request from javascript to the Server.
simply with JQuery
$.ajax(
{
url:'/?num=' + $('#num').val(),
type: 'GET',
success: function(response){
alert('Success');
},
error: function(e1,e2,e3){
alert('Error occured, Could not able to make request.');
}
});

Related

Is there a way to call a .php file from the .html without wiping out the view of the document?

I am currently using . . .
<form action="phpcall.php" method="POST">
.
.
.
</form>
to initiate my php file with a few values from an html form, and submission by a button click. This call is intended to store the entered values into MySQL DB, and generate a graph to be displayed on the html page.
Is there no way to use the data sent by the html form, to generate some data and display it within the html page without navigating away from the html page? As in the php file inserts pertinent data onto the html page (in this case an image, some simple database info and other various data).
I realize this is a fairly novice question, and this would almost be behaving like Javascript, but if I need this php file to log information to MySQL, the way to do so is not apparent to me. Perhaps setting up the html page as a php document would suffice -- therein reinstantiating all of the same html structures after each call -- but this doesn't seem elegant, and I from what I understand separate php and html files are the norm.
/e
My current "solution" is to have the .php have a mirrored format, and sort the variables from there.
You could use an Ajax call, similar to this:
<script>
jQuery(document).ready(function() {
$('form').submit(function() {
var data = $('form').serialize();
$.ajax({
type: 'POST',
url: 'phpcall.php',
data: data,
success: function(data) {
//do something here like display a success message
}
}
});
return false;
});
});
</script>
This would process the PHP file without reloading or navigating away form the page

Saving variable data from jQuery to PHP and getting it after page reload

I'm new to PHP and trying to figure this out and still not understanding. I'm trying to take the value of a html text box in jQuery and turn it into a variable I can then store as a (variable or string?) and pull back again after a page refresh.
I want the user to hit a button that then executes the following:
$('.save').click(function () {
// pulls the value from the textarea
var file = $('#subtext').val();
// send to php to hold text
$.ajax({
url: '/mininote/system/data.php',
type: 'POST',
data: { textbox: file },
success: function(data) {
alert('Saved data to php!');
$(save).text('All changes saved.').show().delay(3000).fadeOut(800);
}
});
});
Then receives the post data and stores in the php until the user reloads the page where it pulls data (or checks if there is any) from the php like so and replaces the value of the textbox with the value from the php:
$.ajax({
url: '/mininote/system/data.php',
type: 'GET',
data: { textbox: file },
success: function(data) {
// add text back to text box
$("#subtext").val(data);
}
});
Basically what I'm looking for is below:-
a way to perform an ajax POST to insert the data grabbed from the textbox,
add to PHP
on a page reload use a GET request and replace textbox text with text from the PHP file.
What would I need to put into the PHP code? Or would it be easier to go in another direction? I've gotten this method to work in local storage. I also want browser compatibility for this work.
I don't need to set it up for a bunch of users. Any response that will increase my knowledge on this will help greatly.
EDIT: I'm really looking for something more server-side so it's usable across multiple platforms and devices.
actually jquery-ajax works like below:-
it takes request and
it gives response.
For Your requirement You also need to follow this steps. so for this , You
send request to PHP page then
send response from php page
so replace Your above jquery-ajax code part with below:-
$('.save').click(function () {
// pulls the value from the textarea
var file = $('#subtext').val();
// send to php to hold text
$.ajax({
url: '/mininote/system/data.php',
type: 'POST',
data: { textbox: file },
success: function(data) {
alert('Saved data to php!');
$('#subtext').val(data);
$(save).text('All changes saved.').show().delay(3000).fadeOut(800);
}
});
});
make sure in Your data.php page textbox value has made echo after inserting data to DB. This process would be something like below:-
data.php
<?php
$textbox = $_POST["textbox"];
/*
perform Your DB inser part here
*/
if(data inserted to db)
{
echo $textbox;
}
?>
Hope this will help You.
You could use the following simple PHP script to accomplish your goal:
<?php
session_start();
if (isset($_POST['textbox'])) {
$_SESSION['textbox'] = $_POST['textbox'];
} else {
echo $_SESSION['textbox'];
}
?>
Another option would be to use HTTP Cookies. Just set the cookie with JavaScript using a plugin or something simple such as, document.cookie = "variable=value"; and access it in PHP with, $_COOKIE["variable"].
Hope this helps.
In the PHP code you could use a PHP session variable like so:
$_SESSION['saveMe'] = $saveMe;
Then get it later, even after a refresh, by using the session variable in php as you would normally use any variable.
For more info see http://www.w3schools.com/php/php_sessions.asp
Use a session, like a temporary cookie, like the following.
session_start();
$_SESSION['sessionName'] = $sessionVar;
Then you can destroy the session with, session_destroy();
See more here.
Why you send it to PHP ?
Just saving in client-side with cookie is better and access in PHP with $_COOKIE
Download jQuery.cookie from :
carhartl/jquery-cookie
and do :
$('.save').click(function () {
// save data from textarea to cookie
var data = $.trim($('#subtext').val());
$.cookie('TEXTAREA_VALUE', data);
});
and go to read by PHP :
<?php
echo $_COOKIE['TEXTAREA_VALUE'];
?>
and to remove :
$.removeCookie('TEXTAREA_VALUE', { path: '/' });
Okay friend !
Ajax is mainly used for sending data without reloading the webpage - from client(js) to serverside(php) or from serverside(php) to client(js). Make sure that name-attribute is given in the textarea and that method is set to post in the form. If I understand your issue correctly you could do something like this:
<?php
session_start();
if (isset($_POST['subtext'])) {
$_SESSION['subtext_value'] = $_POST['subtext'];
}
if (isset($_SESSION['subtext_value'])) {
$subtextValue = $_SESSION['subtext_value'];
}
else {
$subtextValue = '';
}
?>
<html>
<body>
<form action="/mininote/system/data.php" method="post">
<textarea id="subtext" name="subtext"><?php echo $subtextValue;?></textarea>
<input type="submit" value="ok" />
</form>
</body>
</html>

Why does a submission form work, but my ajax doesn't?

I am trying to create a button on my chat that will allow someone to print the conversation. So I made the button that runs a PHP script that creates a new file, writes the conversation to file, and also writes the following jQuery.
jQuery AJAX Call
function OnBeforeUnLoad () {
$.ajax({
type: 'GET',
url: 'deleteFile.php',
data: {
pageName: ".$pageName."
},
dataType: 'text',
success: function(data){alert('Good bye 1!');}
});
return;
}
HTML Put into page
<br/><br/><form method="get" action="deleteFile.php"> <input type="submit" value="Close this Window"/>
<input type="text" value="'.$pageName.'" name="pageName" style="visibility:hidden"/></form>
deleteFile.php
<?php
$pageName = $_GET['pageName'];
$fullURL = 'PrintPage'.$pageName.'.php';
unlink($fullURL);
echo '<script>window.close();</script>';
?>
When the page shows up and I click the "Close this Window" button it does exactly what I want. It deletes the file and closes the window. But I do not get the same results when I close the window (aka OnBeforeUnLoad()). I even tried triggering submit by giving the form an id of deleteFiles and then doing $('#deleteFiles').submit() and it still didn't work.
How do I get the AJAX to work within the OnBeforeUnLoad function?
The form calls the data pageName but the ajax calls it url.
You probably don't want to prefix and suffix the value with . characters either.
Feel like a dummy.... After making all those changes... I found out all I needed to do was add
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
to the header.
Because I was dynamically creating the page in php, I forgot I needed to readd the jQuery.
Always the small things.. Thanks everyone for the help.

Using ajax for form submission with multiple forms generated by php on page

I have a page with multiple forms that do the same thing, acting as a like button for each post in the page, and right next to it the number of likes inside a div named "likes".$id, so I can identify where to write the likes count after the ajax call. I was trying to use jQuery ajax function, but I couldn't set what div to write the results of the function.
$.ajax({
type:'POST',
url: 'likepost.php',
data:$('#like').serialize(),
success: function(response) {
$('#like').find('#likediv').html(response);
}
});
And how would I access the data on likepost.php? I am terrible with javascript, so I hope someone could help me and explain how the jQuery function really works, because I've been copying and pasting it without really knowing what I was doing.
Would this work?
$(function () {
$("#likebutton").click(function () {
var id = $('input[name=id]'); // this is me trying to get a form value
$.ajax({
type: "POST",
url: "likepost.php",
data: $("#like"+id).serialize(), // the form is called like+id e.g. like12
success: function(data){
$("#likes"+id).html(data); // write results to e.g. <div id='likes12'>
}
});
});
});
I put this in the code but when the button is clicked, the usual post refreshing page is done. Why is that?
Making a mini-form, serializing it, and POSTing it seems like a lot of heavy lifting when all you really want to do is send the ID to the likepost.php script.
Why not just retrieve the ID and post it to the script?
First let's break down your function:Type is the type of the request we're making, you specified POST here. This means in your PHP file you'll access the data we're sending using $_POST. Next up is URL which is just the url of where you're sending the data, your php file in this case.
After that is data, that is the data we're sending to the url (likepost.php). You're serializing whatever has a ID of "like" and sending it to the php file. Finally success is a function to run once the request is successful, we get a response back from the PHP and use it in the function to output the response.
As for the multiple forms I'd recommend doing something like:
http://www.kavoir.com/2009/01/php-checkbox-array-in-form-handling-multiple-checkbox-values-in-an-array.html
Here's documentation on the stuff we talked about, if you're every confused about jquery just break it down and search each part.
http://api.jquery.com/serialize/
http://api.jquery.com/jQuery.ajax/
you can try :
function submitform(id) {
var jqxhr = $.post('./likepost.php',$("#"+id).serialize(), function(data) {
$("#"+id).find('#likediv').html(data);
}, "json")
return false;
}
in form:
<form method="post" id="likeForm" onsubmit="return submitform(this.id);">
<input..... />
<input type="submit" value="Submit" />
</form>
in likepost.php add first line:
if ($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
header("location: " . $_SERVER['HTTP_REFERER']);
exit();
}
you can see more : http://api.jquery.com/serialize/
working for me.

Form auto submit ajax not working

I'm passing some variable from one file to another php file that contains a form via jQuery ajax. On The form page where data is being passed to have the following code in it, The values are getting passed in properly and and fields are getting populated with the correct entries, i'm able to very this with firebug response, but page is not automatically submitting. Is their anything i should be looking for that is preventing form from auto submitting. If i access the form page directly, i can see auto submit works.
<?php
$title = $_POST['title'];
$wrapper = $_POST['wrapper'];?>
<form action="test.php" method="post" id="publish">
<input type="text" value="<?php echo $title ?>" name="title">
<textarea name="wrapper"><?php echo $wrapper?></textarea>
<input type="submit" value="Submit">
</form>
<script>
window.onload = function(){
document.getElementById('publish').submit();
}
</script>
ajax code that is sending the values looks like this
$.ajax({
type: "POST",
url: "process.php",
data: {
title: 'test',
wrapper: 'testing123'
},
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Spot the difference:
getElementById('publishForm')
id="publish"
From what I see the auto submit is linked to the 'publishForm'
However, your form Id is "publish"
This is probably the cause of the code not working.
Perhaps you should show us the caller code instead of the handler code. Most likely what you're dealing with is the JS not being run during the AJAX call - the PHP page processing is server side.
You could look into sending the form using PHP Curl instead of JS? That would probably address the issue where it works loaded directly, but fails when called from another page.
As far as I understood, that HTML is being loaded through AJAX, right? If so, then window.onload will not be fired since the page was already loaded (AJAX doesn't count). Just do this:
<script type="text/javascript">
document.getElementById('publish').submit();
</script>
EDIT
To break this down:
Your code on SourcePage.php(I made up this name for reference) is posting data to process.php via an AJAX request
process.php then injects "title" & "wrapper" into the html markup and returns html with some javascript to SourcePage.php
You're then expecting that displaying the resulting string (msg) of the returned html on SourcePage.php will get the javascript in that string to execute.
To get this working, you'll need to do a few things.
Parse out the incoming javascript from the html.
Inject the incoming parsed HTML into SourcePage.php's markup.
Pass the parsed out JavaScript into JavaScript's eval function.
Doing this should bring the page from the process.php and successfully execute the JavaScript code on SourcePage.php.
If you were expecting that the JavaScript would run on the server, then I'm afraid you're mistaken as the server(php runtime) will not execute the JavaScript on the server. Perhaps a redirect on the server will accomplish your goal (whatever that may be).
Original
Try this out: http://jsfiddle.net/NiceGuy4263/eJLMS/

Categories