I need to store data in server-side.I tried to make an Ajax call to PHP:
upload.html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<style>
#test{
padding:20px 50px;
background:#ccc;
color:#000;
}
</style>
<script>
$(function(){
$('#test').click(function(){
$.ajax({
url: "http://localhost:8012/myFolder/upload.php",
type : 'POST',
data: {"foo": "bar"},
processData: false,
contentType: 'application/json'
});
});
});
</script>
</head>
<body>
<button id="test">KLICK</button>
</body>
</html>
upload.php:
<?php
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
fwrite($fh,$_POST['data']);
fwrite($fh,$_POST['foo']);
fwrite($fh,$_POST["foo"]);
fwrite($fh,$_POST[foo]);
fclose($fh);
?>
but It doesn't work.The data is not wrriten to testFile.txt.
I will appreciate your help.
Thanks in advance.
No, JavaScript doesn't have access to writing files as this would be a huge security risk to say the least.
If you wanted to get/store information server-side, though, you can certainly make an Ajax call to a PHP/ASP/Python/etc. script that can then get/store the data in the server. If you meant store data on the client machine, this is impossible with JavaScript alone.
If you are only trying to store a small amount of information for an unreliable period of time regarding a specific user, I think you want cookies.
Updated:
Below is a simple code that you are looking for. There is a simple form with four fields. On clicking of submit, it calls the server file and that PHP file will have the code to write the data to a file.
$("#submit").click(function(){
var paramsToSend = {};
var i = 1;
$("input[name='myanswer[]']").each(function(){
paramsToSend[i] = $(this).val();
i++;
});
$("#dataToSend").html(JSON.stringify(paramsToSend));
$.ajax({
type: "POST",
url: 'URL_HERE/post.php',
data: {params:JSON.stringify(paramsToSend)},
success: function(data) {
console.log("SUCCESS!!!");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inputsl">
<div class="inputt"><input type="text" id="createmyanswer" name="myanswer[]" class="myinput"></div>
<div class="inputt"><input type="text" id="createmyanswer" name="myanswer[]" class="myinput"></div>
<div class="inputt"><input type="text" id="createmyanswer" name="myanswer[]" class="myinput"></div>
<div class="inputt"><input type="text" id="createmyanswer" name="myanswer[]" class="myinput"></div>
</div>
<button id="submit">
Submit
</button>
<div id="dataToSend"></div>
PHP code can be:
file_put_contents('filename.txt', $_POST['params']);
Related
I am trying to send JSON data from page1 on submit button click and try to receive this data dynamically from page2 using AJAX and print the data in console. I don't know the proper syntax to do this. One suggested code which is not appropriate. The code is given:
page1:
<?php
if(isset($_POST["submit"])){
$x = "ok";
echo json_encode($x);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>page1</title>
</head>
<body>
<p>This is page is sending json data on submit button press</p>
<form method="post">
<input type="submit" name="submit">
</form>
</body>
</html>
page2:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
</head>
<body>
<p>Get json data from page1 dynamically using ajax</p>
<script>
setInterval(checkVariableValue, 5000);
function checkVariableValue() {
$.ajax({
method: 'POST',
url: 'page1.php',
datatype: 'json',
success: function(data) {
console.log(data);
}
});
}
</script>
</body>
</html>
What should I write to make it works properly?
You can do like this
session_start();
if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST["submit"])){
$value = 'I am test'; //can be any value
$_SESSION['key'] = $value;
} else if($_SERVER['REQUEST_METHOD']=='POST')){
echo $_SESSION['key'];
}
I'm trying to develop a code that is able to change the font of an element dynamically by using a font file (TTF) uploaded. The code below works fine in Chrome, Opera and Firefox, but doesn't work in IE, Edge and Safari.
<html>
<head>
<style>
#my-font {
margin-top: 50px;
font-size: 20pt;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(function(){
$("#font").change(function(){
// post the font file to the php script that will move the file uploaded to the folder "fonts"
$.ajax( {
url: 'movefontfile.php',
type: 'POST',
data: new FormData($("#send")[0]),
processData: false,
contentType: false,
}).done(function(name){
// set the font face
var f = new FontFace("myfont", "url(fonts/"+name+")", {});
f.load().then(function (loadedFace) {
document.fonts.add(loadedFace);
var fptags = document.getElementById('my-font');
fptags.style.fontFamily = "myfont, sans-serif";
});
});
})
});
</script>
</head>
<body>
<form id="send">
<input type="file" id="font" name="font">
</form>
<p id="my-font">
This is a font text
</p>
</body>
</html>
This is the php code:
<?php
$name = $_FILES['font']['name'];
move_uploaded_file($_FILES['font']['tmp_name'], 'fonts/'.$name);
echo $name;
?>
Someone could help me? I need a code that works in every popular browser. Thanks.
IE and Edge don't have support for the JavaScript FontFace object. You might have better luck dynamically creating the CSS #font-face code, like so:
$.ajax( {
url: 'movefontfile.php',
type: 'POST',
data: new FormData($("#send")[0]),
processData: false,
contentType: false,
}).done(function(data){
$('<style>').text("#font-face {font-family: 'myfont'; src: url('fonts/myfont.ttf');}");
var fptags = document.getElementById('my-font');
fptags.style.fontFamily = "myfont, sans-serif";
});
Try to use the browser debugger by pressing F12 key and check the font on the <p> tag.
<p id="my-font">
Fix it on console window and update your code accordingly.
I find a solution that works in Safari and Edge, but doesn't works to IE yet.
It is very ugly, but works:
<html>
<head>
<style>
#my-font {
margin-top: 50px;
font-size: 20pt;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
var font;
$(function(){
$("#font").change(function(){
// post the font file to the php script that will move the file uploaded to the folder "fonts"
$.ajax( {
url: 'movefontfile.php',
type: 'POST',
data: new FormData($("#send")[0]),
processData: false,
contentType: false,
}).done(function(data){
$('link[rel=stylesheet][href="'+font+'.css"]').remove();
font = data;
$('head').append('<link rel="stylesheet" type="text/css" href="'+data+'.css">');
$('#my-font').css('font-family', 'myfont, sans-serif');
});
})
});
</script>
</head>
<body>
<form id="send">
<input type="file" id="font" name="font">
</form>
<p id="my-font">
This is a font text
</p>
</body>
</html>
And the PHP script:
<?php
$name = $_FILES['font']['name'];
move_uploaded_file($_FILES['font']['tmp_name'], 'fonts/'.$name);
$css = file_get_contents('font-face-aux.css');
$css = str_replace('?FONT_NAME?', $name, $css);
$f = fopen($name.'.css', 'w');
fwrite($f, $css);
fclose($f);
echo $name;
?>
And the auxiliar CSS:
#font-face {
font-family: 'myfont';
src: url('fonts/?FONT_NAME?');
}
I am using the following code and I need to access the input value of the form textbox from php. The form is not submitted to server directly through the form tag. The button is calling a JS function. I need to access the input textbox called stName from the php code. How can I pass this info to php and access it from there? Thank you.
<!DOCTYPE html>
<html><head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="jquery.mobile-1.4.4.min.css">
<script src="jquery-1.11.1.min.js"></script>
<script src="jquery.mobile-1.4.4.min.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script charset="utf-8" type="text/javascript">
function connect()
{
$.ajax({
url:'hostname/reply.php',
headers:{"Content-Type": "application/json"},
type:'POST',
data:$(this),
dataType:'JSON',
error:function(jqXHR,text_status,strError){
alert(strError);},
timeout:60000,
success:function(data){
$("#result").html("");
for(var i in data){
$("#result").append("<li>"+data[i]+"</li>");
}
}
});
}
</script>
</head>
<body>
<center><b>My Students</b></center>
<center>
<form method="POST">
<input type="text" value="John" name ="stName" />
<input onclick="connect()" type="button" value="showStudents" />
</form>
</center>
<center><b>Results</b></center>
<ul data-role="listview" id="result"></ul>
</body>
</html>
serialize the form data ..
change your connect function to this
function connect()
{
$.ajax({
url:'hostname/reply.php',
headers:{"Content-Type": "application/json"},
type:'POST',
data:$('form').serializeArray(),
dataType:'JSON',
error:function(jqXHR,text_status,strError){
alert(strError);},
timeout:60000,
success:function(data){
$("#result").html("");
for(var i in data){
$("#result").append("<li>"+data[i]+"</li>");
}
}
});
}
or simply you can compress your code like this ..
function connect()
{
$.post('hostname/reply.php', $('form').serialize(), function(data){
$("#result").html("");
for(var i in data){
$("#result").append("<li>"+data[i]+"</li>");
}
}
});
}
You need to use the Sterilize Function. data:$( "form" ).serialize()
For Reverence to the function: http://api.jquery.com/serialize/
I also just found this StackOverflow that talks about how to structure the ajax request if you are having problems. Submit form using AJAX and jQuery
I'm trying to retrieve json data from local server in my phonegap android app.
I've put a submit input to get data.I am using the method $.ajax in jquery to do that.
My problem is that when i click the submit, nothing is displayed but the page is refreshed.
I don't see how to fix this.
Could you please help me? Thanks in advance.
(ps: the json returned is correct and i've changed the access in config.xml)
Here is the full code :
<!DOCTYPE html>
<html>
<head>
<title>Application test</title>
<script type="text/javascript" charset="utf-8" src="phonegap-1.2.0.js"></script>
<link href="css/jquery.mobile-1.0rc1.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.6.4.js"></script>
<script src="js/jquery.mobile-1.0rc1.min.js"></script>
<script>
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
}
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$('#testform').submit(function(){
$('#content').html("<b>Chargement...</b>");
$.ajax({
url: "http://localhost/projects/api/getAllCategorie.php"
}).done(function(data){
$("#content").html('<p> ID: ' + data.categories[0].id + '</p>');
log('erreur');
}).fail(function(){
alert("Erreur!!");
$("#content").html('erreur');
log('erreur');
});
return false;
};
</script>
</head>
<body>
<img src= "css/images/logo-annuaire-mayotte.png">
<ul data-role="listview" data-filter="true" data-filter placeholder="Rechercher..." data-inset="true">
<li>Restaurants</li>
<li>Bâtiments</li>
<li>Numéros utiles</li>
</ul>
<form id='testform'>
<div><input type="submit" id="driver" value="Synchronisation" /></div>
</form>
<div id="content">
</div>
</body>
</html>
If you want to connect to your localhost php file use port number(working for me) or IP address of your actual system like this
http:// localhost:8080/projects/api/getAllCategorie.php,(for emulator)
http:// 10.0.2.2/projects/api/getAllCategorie.php
Close your document ready function
$(document).ready(function(){
$('#driver').click(function(event){
event.preventDefault(); // To prevent default action of the form
$('#content').html("<b>Chargement...</b>");
$.ajax({
url: "http://localhost:8080/projects/api/getAllCategorie.php",
dataType:"json",
beforeSend:function(){
alert("Request is going to send now");// place your loader
},
success:function(data){
$("#content").html('<p> ID: ' + data.categories[0].id + '</p>');
log('erreur');
},
error:function(xhr, status, error){
alert(xhr.responseText);
$("#content").html('erreur');
log('erreur');
}
});
return false;
});
});
HTMl : Replace your form tag with this input tag
<div><input type="button" id="driver" value="Synchronisation" /></div>
I am working on a instant search function, currently i am having trouble passing the variable from JS to PHP file. I am also unsure about what to do once i have the results from the query. Any help would be fantastic. This is my current standing.
ERROR
Undefined index: partialSearch in \php\search.php on line 4
test.php
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AJAX SEARCH</title>
<link rel="stylesheet" href="stylesheets/base.css">
<link rel="stylesheet" href="stylesheets/skeleton.css">
<link rel="stylesheet" href="stylesheets/layout.css">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function search(partialSearch){
$.ajax({url:"PHP/search.php",data: partialSearch,success:function(result){
$("#results").html(result);
}});
};
</script>
</head>
<body>
<div class="container">
<div class="one-third column index">
<h3>Search Our Site</h3>
<p>Simply type into the search bar below the video, article you are looking for.</p>
<input type="text" name="partialSearch"onkeyup="search(this.value)"/>
<div id="results"></div>
</div>
</div>
</body>
</html>
search.php
<?php
include 'config.php';
$partialSearch = $_POST['partialSearch'];
$stmt = $mysqli->prepare("SELECT Name FROM videos WHERE Name LIKE ? ");
$stmt->bind_param('s',$partialSearch);
$stmt->execute();
$stmt->bind_result($Name);
while ($row = $stmt->fetch()) {
$searchResults[] = $Name;
echo "<div>".$searchResults."</div>";
}
?>
You should change
data: partialSearch
to
data: {partialSearch: partialSearch} // or {"partialSearch": partialSearch}, which is the same
Where partialSearch is the data's index name.
1.) You did not tell jQuery to post, e.g.
$.ajax({ type: "POST", ... });
You can also use the shorthand ".post" :
$.post{url:"PHP/search.php",data: partialSearch,success:function(result){ $("#results").html(result);
2.) The PHP thinks of a named POST variable. So your partialSearch must be an object like so
partialSearch = { partialSearch : "I AM your variable, NOT the object holding me !!!" }
By default, $.ajax calls sends a GET request, so your $_POST is not valid in your .php file, unless you specify a ..type:"POST".. variable in your $.ajax(.. settings.
Secondly, you need to change this:
$.ajax({url:"PHP/search.php",data: partialSearch,success:function(result){
to this:
$.ajax({url:"PHP/search.php",type:"POST",data:{partialSearch:partialSearch},success:function(result){
It's perfectly ok to pass an object of variables to send.