I have a editor embeded in the html page
<div id="editor">
Problem Statement goes here…
</div>
I basically want to store the contents written in editor to a file(preferably in rich text format). I used a script (given below) for storing the contents in a string.(This I used by referring to HTML div text to save and display )
<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
var StoreEditorContent; //declare a variable to save Content
document.getElementById('save').addEventListener("click", SaveText); // adding event listner for onclick for Saving text
function SaveText(){
StoreEditorContent = document.getElementById('editor').innerHTML; // Save the Content into
document.getElementById('editor').innerHTML = ""; // to blank the editor Content
window.onload = function(){
$.ajax({
url: "submit_request.php",
type: "GET",
success: function writeMsg(StoreEditorContent){
//Not sure if this part is right.
}
});
}
}
</script>
This of course is storing in the contents in a string StoreEditorContent. I now want to pass this string to a php function which will write this(StoreEditorContent) to a file.The php file that contains function to write is given below
<?php
function writeMsg($msg){
$file = "myfile.txt";
file_put_contents($file, $msg);
}
?>
I know I need to use ajax here, but cannot figure out how? Any help appreciated.
You need to provide a data: option to $.ajax():
$.ajax({
url: "submit_request.php",
type: "POST",
data: { content: StoreEditorContent },
success: function (response) {
// Do something with the response sent from PHP
}
});
Then your PHP can do:
writeMsg($_POST['content']);
You should use POST rather than GET for large requests because the limit on GET parameters is relatively small.
Related
I'm trying to create a page where a user can upload a file and select the people they want to email it to. Once they click submit, I prevent page refresh and reset their inputs in the form. Now I want to place their previously entered information into a table on the same page (different section of the page).
If you did want to proceed with this concept, you would capture the output of the PHP script in a done() function, insert it in an element on the page, and run eval(). Like this...
$.ajax({
type: "POST",
url: "../FileDrop/dbSystem.php",
data: {tags: JSON.stringify(tags), file:
$('input[name=fileName]').val()};
}).success(function(result) {
$( '#element' ).html(result);
$( '#element script' ).each( () => { $(this).html().eval() })
});
But it would make alot more sense to return data that you use to execute the javascript in your page - that is, keep all that logic together rather than splitting some of it off into a PHP file.
<?php
// php process that checks for 'valid'...
// create a json response
$output = array('valid' => 1);
echo json_encode($output);
?>
.... and in your JS
.success(function(result) {
// result is a stringified JSON object. We need to convert it into an actual JSON object with parse()
result = JSON.parse(result);
// might not matter, but result.valid will be a number which JSON converts into a string. By adding the + right before the variable, that tells JS to use it as a number for the comparison
if (+result.valid == 1) {
$(".outputDiv").show();
}
});
I want to do the following:
<html>
<div id="first"><?php echo time(); ?></div>
<div id="second">My dropdown menu goes here</div>
<div id="third"><?php echo time(); ?></div>
</html>
I have this "example.php" and what I want is that refreshing first and third divs and PHP codes inside them every 1 second without reloading page and changing the state of the second div which will hold a selection from dropdown menu.
So the selection of the dropdown menu should be exact and when I click and open the dropdown menu, the menu must not be closed when a refresh occurs at first and third div.
Also, refresh method of the first and third div must be simultaneous and completely separate processes. Time printing is just for feeding a time changing value to my problem. I will read and print MySQL database data inside these PHP codes.
How can I do that using javascript? Thanks...
To achieve your desired result, You need to utilize Ajax and JSON.
Your PHP script will return fresh data as json which will be fetched via Ajax and then replaced in the target divs.
But before we begin let's learn a bit about Ajax and JSON
What is Ajax?
Ajax is a client-side script that communicates to and from a server/database without the need for a post back or a complete page refresh. Essentially, Ajax is “the method of exchanging data with a server, and updating parts of a web page – without reloading the entire page.”
What is JSON?
JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.
How to integrate it with your script?
We will first define a javascript function named update_data() which fetches the values from the server and then updates the divs with their fetched values.
To do all this, we'll use jQuery as a dependency and will utilize it's jQuery.ajax() method
NOTE - To automatically call the function every second we will also need setInterval method
function update_data() {
$.ajax({
url: 'test.php', // Your PHP script location
type: "GET",
async: true, // refer to reference [1] in my answer
success: function (data) {
// Update the values
$('#first').text(data.time1); // get the value of `time1` key from returned data
// #first targets the element with id="first"
$('#third').text(data.time2);
}
});
}
setInterval("update_data();", 1000);
// calls the function `update_data()` every second
Sample PHP script- (test.php)
<?php
if ($_SERVER['REQUEST_METHOD'] == "GET") {
$data = Array('time1' => time(), 'time2' => time());
// returns the data with mime type `json` instead of `html`
header("Content-Type: application/json; charset=UTF-8");
echo json_encode($data); // converts array into json
}
?>
The above PHP script will return the follwoing JSON structure:
{
"time1": 'value returned by first call to time()',
"time2": 'value returned by repeated call to time()'
}
Full html example (calls external php)-
<html>
<div id="first">Print some value on page load, will be replaced by Ajax</div>
<div id="second">My dropdown menu goes here</div>
<div id="third">Print some value on page load, will be replaced by Ajax</div>
<!-- Include jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function update_data() {
$.ajax({
url: '/test.php', // Your PHP script location
type: "GET",
async: true, // refer to reference [1] in my answer
success: function(data) {
// Update the values
$('#first').text(data.time1); // get the value of `time1` key from returned data
// #first targets the element with id="first"
$('#third').text(data.time2);
}
});
}
setInterval("update_data();", 1000);
// calls the function `update_data()` every second
</script>
</html>
Reference -
1. What does "async: false" do in jQuery.ajax()?
Use http://api.jquery.com/jquery.ajax/
Example:
<script>
$(function(){
$.ajax({
url: "first.php",
})
.done(function( data ) {
if ( data ) {
$('#first').html(data);
}
});
});
</script>
Now, if you are really swimming off the pond, I'll make it easier:
<script>
var t=0;
function fetchFirst()
{
$.ajax({
url: "first.php",
})
.done(function( data ) {
if ( data ) {
$('#first').html(data);
clearTimeout(t);
}
});
}
$(function(){
t=setTimeout(fetchFirst, 1000)
});
</script>
Now you can get the rest from this quick start. Remember to embed jquery before this stuff with
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
and do not make too many requests simultaneously.
Good luck.
Hello everyone I am new to php.
I have been trying out this thing when a user enter a product name need to validate that the product is valid or not.
For that purpose I have used onchange event when the text is entered.The onchange function will call the javascript function.From javascript function I am calling the php which is in the same file.So when I am entering the product name somehow the php function is not working.
Here is my code :
<?php
include 'conf.php';//it contains the php database configuration
session_start();
$quantityRequired=0;
$productName_error="";
if(is_ajax()){
if(isset($_POST["productName"])){
$productName=$_POST["productName"];
$row=mysqli_query($conn,"SELECT * from OrderDetails where ProductName='".$productName."'");
if($row)
{
$result=mysqli_fetch_assoc($row);
$quantityRequired=$result["Quantity"];
}
else
{
$productName_error="The product name is not valid or product does not exist";
echo $productName_error;
}
}
}
function is_ajax() {
$flag=(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
return $flag;
}
?>
<html>
<head>
<title>Order Page </title>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<label for="userName">Username</label><br>
Product Name<input type="text" name="productName" id="productName" onchange="validateProduct()"><?php echo $productName_error?><br>
Quantity Required<input type="text" name="quantityRequired" id="quantityRequired"><br>
Availability<input type="text" name="availability">
<p id="demo"></p>
</form>
<script>
function validateProduct()
{
$.ajax({
type: "POST"
});
}
</script>
</body>
</html>
so the code is when the user enters the product name.The function validate product is called.From validate product it will call the php which is in the same file. is_ajax() function is used to check whether it is the ajax request or not.
A PHP library for Ajax
Jaxon is an open source PHP library for easily creating Ajax web applications. It allows into a web page to make direct Ajax calls to PHP classes that will in turn update its content, without reloading the entire page.
Jaxon implements a complete set of PHP functions to define the contents and properties of the web page. Several plugins exist to extend its functionalities and provide integration with various PHP frameworks and CMS.
How does Jaxon work
Define and register your PHP classes with Jaxon.
$jaxon->register(Jaxon::CALLABLE_OBJECT, new MyClass);
Call your classes using the javascript code generated by Jaxon.
<input type="button" onclick="JaxonMyClass.myMethod()" />
check link https://www.jaxon-php.org/docs.html
There may be other problems I haven't spotted, but the first thing that jumps out to me is that your server-side code runs conditionally:
if(isset($_POST["productName"]))
And that condition was never satisfied because you didn't send any values in the AJAX request:
$.ajax({
type: "POST"
});
Send the value(s) you're looking for:
$.ajax({
type: "POST",
data: { productName: $('#productName').val() }
});
You may also need to specify a couple other options if they don't default correctly. Explicit code is generally better than implicit in many cases:
$.ajax({
url: 'yourUrl.php',
type: "POST",
dataType: 'html',
data: { productName: $('#productName').val() }
});
In general you'll probably want to check the documentation for $.ajax() and see what you can and should tell it. You'll also want to take a look at your browser's debugging tools to see more specifically why and how it fails when testing these things.
Speaking of things you should do, you should read this and this. Your code is wide open to SQL injection attacks at the moment, which basically means that you are executing as code anything your users send you.
var data1 = "Something";
$.ajax({
url: "script.php",
type: "POST",
data: { data1: data1 }
}).done(function(resp) {
console.log( resp )
}).fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus + " - Please try again.")
})
Here you have a script that will send the data1 variable across to the php script. The resp in the done portion is the return you send back from the php script.
If you want to send more data just add it { data1: data1, data2: data2 } and so on.
Just adjust to suit your needs.
I need to save the value of a input type text in a PHP variable as soon as the user writes it. I found that the blur event in JQuery can trigger an event that happens after writing to the input type text, so I have the following:
<script>
$("document").ready( function()
{
$("#primerApellido").blur(function() {
alert('out');
<?php
$primerApellidoForm =
"<script type=\'text/javascript\'>
$('#primerApellido').val();
</script>
";
?>
});
});
</script>
And here is my input type text:
<input type="text" id="primerApellido" name="primerApellido" value="<?php echo $primerApellidoForm?>"/>
So as you can see, I need to save what is typed on the input on the PHP variable as soon as the user leave the text box. Right now it save literally the Javascript variable assignation, not the value that I need.
How can I assing the typed value on the text box to my PHP variable?
I think you may be confusing PHP and Javascript a bit.
PHP only runs on the server.
Javascript only runs on the browsers.
You cannot modify PHP variables from javascript directly.
What you can do however, is make an ajax call to another page to do something with that variable such as save it in the session or into a database.
Check out the Javascript jQuery ajax command. With this command you can run another page without leaving the one you are currently on. You can have that page be a PHP page that receives the variable and performs an action with it.
Try this..
$("#primerApellido").onkeyup(function() {
var user_input = $(this).val();
$.ajax({
type:'GET',
url: 'path/to/your/phppage',
data:{user_input:user_input},
success: function(response) {
//alert(response);
}
});
});
I followed the advice from Mark Carpenter to use Ajax function, below is the code that do what I want:
$("document").ready( function()
$("#primerApellido").blur(function() {
$.ajax({
type: "GET",
url: "destinationURL.php",
data: "primerApellidoForm="+$('#primerApellido').val(),
success: function(msg){
alert( "Data Saved: "+msg);
}
});
});
});
Now the PHP variable "primerApellidoForm" have the value from $('#primerApellido').val() input type.
Not sure what you are trying to do is possible. Once you have loaded the page, there is no way you can run the php code ( You can make ajax requests though ) . Hope the following helps.
How can I use a JavaScript variable as a PHP variable?
you can try this...
<script type="text/javascript">
$("#primerApellido").blur(function() {
<?php $primerApellidoForm = "<script>document.write($(this).val());</script>"?>
});
</script>
I have a problem with ajax and rewrite engin. I made a site, where I use this load more script:
http://www.9lessons.info/2009/12/twitter-style-load-more-results-with.html
Everything works fine on users profile page (I am getting posts from users feedback), when the url looks like this: example.com/user.php?u=ExampleUser
but I have this in .htaccess:
RewriteRule ^u/(.*) user.php?u=$1 [L]
So if I type something like example.com/u/ExampleUser I get the username like:
$username = $_GET['u'];
But in this way when I click on the load more it doesn't load more posts from the user, it just starts to lead the site itself to the div box (like it is an iframe...).
Please help me, it is necessary.
Here is my script, which should load more info from MySQL database($id is userid from DB):
$(function() {
// More Button
$('.more').live("click",function() {
var ID = $(this).attr("id");
if (ID) {
$("#more" + ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: 'lastmsg='+ID+'&user='+<? echo $id; ?>,
cache: false,
success: function(html) {
$("#container").append(html);
$("#more"+ID).remove();
}
});
} else {
$(".morebox").html('The End');
}
return false;
});
});
Not knowing the entire context of your code, it looks like when the ajax call is made, the final url is something along the lines of domain.tld/u/ajax_more.php.
I get around this issue by maintaining a list of constants in the javascript object.
For example, I have a paths.php file that contains this:
<?php
header("Content-Type: text/javascript");
echo "
myNamespace.paths = {
RELATIVE_FOLDER: '<?=RELATIVE_FOLDER?>',
// add more as required...
}
";
?>
This is included in the page just like a regular script (with script tags), and from that point forward, myNamespace.paths will contain your constants, as returned by the server.
In my case, if the URL was "http://www.example.org/path/to/my/dev/env", I would have RELATIVE_FOLDER set to /path/to/my/dev/env/ on the server-side, which would then be included into the paths object.
Later, in your ajax calls:
$.ajax({
type: "POST",
url: myNamespace.paths.RELATIVE_FOLDER + "ajax_more.php",
// ... everything else
});
I notice you have no problem with directly injecting PHP into your scripts. This is not necessarily a bad thing, but it does make it harder for you to minify your js. This is the reason why I went with a separate file to store the constants, instead of directly injecting it into the javascript itself with <?= ... ?> tags.