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
Related
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']);
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'];
}
This is what is happening: I send data but and I have it coded to echo out on second page. However, it just echoes out on first page. How do I make it so it echoes out on second page not the first page?
The code on second page executes but it executes on first page. I want it on second page.
<!doctype html> FIRST PAGE
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div class="text-center">Button</div>
<input class="form-control" name="cartID" id="cartID" type="hidden" value="<?php echo $order['clientid'] ;?>">
<p id="edit_box"></p>
<script>
$("#scaleButton").click(function() {
var cartID = "hello"
var second = "second";
///////// AJAX //////// AJAX //////////
$.ajax({
type: 'POST',
url: 'user/testing1234.php',
data: {first:cartID,second:second},
success: function( response ){
alert('ajax');
$('#edit_box').html(response);//this is where you populate your response
}//close succss params
});//close ajax
///////// AJAX //////// AJAX //////////
})
</script>
</body>
</html>
SECOND PAGE
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<?php
$first = $_POST['first'];
$second = $_POST['second'];
$third = $_POST['third'];
echo $second;
echo $second;
echo $second;
?>
</body>
</html>
This is what I need I believe:
$( document ).ready(function() {
$("button").click(function() {
var dataPoint = "chunk of data";
///////// AJAX //////// AJAX //////////
$.ajax({
type: 'POST',
url: 'some_page_name.php',
data: {dataPoint:dataPoint},
success: function( response ){
$('#success').html("Sent!!");
}
});
///////// AJAX //////// AJAX /////////
});
And for your HTML Page:
<button>Click me</button>
<div id="success"></div>
Modify as needed.
I'm trying to use jQuery.ajax() to retrieve an html code snippet from table_snippet.html and then replace the element in my html code. My error handler in jQuery.ajax() is being executed instead of the desired success handler.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Table</title>
<link href="address-data-file.css" type="text/css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="ajax_goodness.js" type="text/javascript"></script>
</head>
<body onload="func()">
<div id="div_id">
<p>Use AJAX to retrieve the file table-snippet.html and then replace the div with the contents of that file.</p>
</div>
</body>
</html>
function func(){
jQuery.ajax({
type: "GET",
url: "table_snippet.html",
dataType: "html",
success: function(data){
$("#div_id").html(data);
},
error: function(){
alert("fail");
}
});
}
$(function () {
$.ajax({url:"table_snippet.html",success:function(result){
$("#div_id").html(result);
}});
});
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>