php and ajax passing form value - php

Hi how would I echo the form input "date" in a PHP file from the code below. (data: "name=Peter&location=Sheffield" + $('input[name="date"]').val(),)
at the moment I have echo "todays date ".$_POST['date']."<br>"; but it doesnt seem to work
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript"
src=http://code.jquery.com/jquery-latest.js>
</script>
<script type="text/javascript">
// This functions starts the ajax to show the output from post.php
function StartAjax(ResultsId){
$.ajax({
type: "POST",
url: "postTest.php",
cache: false,
data: "name=Peter&location=Sheffield" + $('input[name="date"]').val(),
success: function(html, status){
$("#"+ResultsId).append(html);
$('#status').append(status);
}
});
}
</script>
</head>
<body>
<h1> Run Club</h1>
testing
<form>
date: <input type="text" name="date"><br>
</form>
Click Here to see updates from postTest.php
<div id="ResultsId"></div>
<div id="status"></div>
</body>
</html>

You have to put a date key in your query string
data: "name=Peter&location=Sheffield&date=" + $('input[name="date"]').val(),
alternatively you should pass an object to data so jQuery will format the query string for you.
data: {name: "Peter", location: "Sheffield", date: $('input[name="date"]').val()},

function StartAjax(ResultsId){
var date = document.getElementsByName("date").val();
$.ajax({
type: "POST",
url: "postTest.php",
cache: false,
data: "name=Peter&location=Sheffield&date=" + date,
success: function(html, status){
$("#"+ResultsId).append(html);
$('#status').append(status);
}
});
}

Related

.ajax() not sending data to php file

I am having a problem is retrieving data sent to a php file through .ajax() via jquery
Following is my html:
<!-- Jquery tute no 94 onwards -->
<html lang="en">
<head>
<meta charse="utf-8">
<title> jquery4 </title>
<link rel="stylesheet" type="text/css" href="jquery4.css"/>
</head>
<body>
<input id="lo" type="text"> </input>
<input id="ton" type="button" value="Load"> </input>
<div id="content"> </div>
<script type="text/javascript" src="jquery.js"> </script>
<script type="text/javascript" src="jquery4.js"> </script>
</body>
</html>
My jquery4.js is:
$(document).ready(function()
{
$('#ton').click(function()
{
var nm= $('#lo').val();
$.ajax({url: 'page.php', data1: 'name='+nm, success: function(data2)
{
$('#content').html(data2);
}
});
});
});
My page.php is:
<?php
if(isset($_GET['data1']))
{
echo $namer= $_GET['data1'];
}
?>
All the above files are in the same folder, and I have xampp installed.
I guess the error is somewhere in the jquery file where I call the
ajax() function
jQuery ajax doesn't take a data1 parameter. It takes a data parameter, which should be an object of name-value pairs.
$.ajax({
url: 'page.php',
data: {
data1: 'name=' + nm,
},
success: function(data2) {
$('#content').html(data2);
}
});
$.ajax({
type: "GET",
url: "page.php",
data: {
data1: 'name=' + nm,
}
,
success: function(data2) {
$('#content').html(data2);
}
});
Try this:
$(document).ready(function() {
$('#ton').click(function() {
var nm= $('#lo').val();
$.ajax({
url: 'page.php?name=' +nm,
success: function(data2) {
$('#content').html(data2);
}
});
});
});
You don't have to tell jQuery to use GET, as it defaults to that, if nothing else is specified.
So the ajax function does not take an argument called data1, but 'data', this is mostly used for other methods as POST, PUT and DELETE.
I prefer also sending GET requests with a normal query string, like the above example.
You can then check for get GET parameter with PHP, using $_GET['name']

How to call a javascript function from PHP at form submit event

I want to call a javascript function from php at the form submit event. and that javascript function will access the php variables, send them to a php script on another website using ajax. The following code is just a representation.
<?php
....
.....
......
if($_POST["action"]=="xyz"){
$myname = "asim";
echo "<script type='text/javascript'>submitform();</script>";
}
.....
....
...
gotoanotherpagefinally();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function submitform(){
alert("<?php echo $myname; ?>");
$.ajax({
type: 'POST',
data: {
action: 'whatever',
fileID: "<?php echo $myname; ?>",
},
url: 'http://xyz.com/API/query.php'
});
}
</script>
</head>
<body>
<form id="myform">
------
------
<input type="submit" name="submit_details">
</form>
</body>
</html>
I need to call the javascript function from php because the php variables taken by js function are only set by php itself and not the form values or something.
You can catch the submit event using jQuery:
$("#myform").submit(function(e) {
// needed so the default action isn't called
//(in this case, regulary submit the form)
e.preventDefault();
$.ajax(...);
});
you can use :
<form id="myform" onsubmit="submitform()">
You can use jQuery to do this.
$(':input').click(function(){});
then inside this function you can use an ajax request to send the variable to php page that you have.
var variableA, variableB; // variables to be initiated by an ajax request
// ajax request to get variables from php page
$.ajax(
{
url:'php_page_path/source_page.php',
data:"message=getVars",
type: 'post',
success: function(data){
// use the data from response
var obj = JSON.parse(data);
variableA = obj.varA;
variableB = obj.varB;
}
});
// use the variables in this ajax request and do what you want
$.ajax(
{
url:'php_page_path/page.php',
data:"var1="+variableA+"&variableB="+vaiableB ,
type: 'post',
success: function(j){
// use the data from response
}
});
Please changes your code -
<?php
$myname="asim";
?>
<script type="text/javascript">
function submitform(myname){
alert(myname);
$.ajax({
type: 'POST',
data: {
action: 'whatever',
fileID: myname,
},
url: 'http://xyz.com/API/query.php'
});
}
</script>
HTML
<form id="myform" onsubmit="submitform('<?php echo $myname;?>')">
------
------
<input type="submit" name="submit_details">
</form>

I am trying to fetch json data's from .php file.php file i.e stored in server.I have writtened the following code.But I am unable to fetch data

I am new to this jquery and phonegap.I am finding little difficulty in parsing the data from .php file from a local server.Please help me in doing so.
This is my index.html page:
<!DOCTYPE HTML>
<html>
<h2>JSON Parser</h2>
<script type="text/javascript" src="jquery.js"/></script>
<script type="text/javascript">
function parseJSON()
{
var json;
$.ajax({
type: 'POST',
url: 'http://192.168.1.12/training/services/login.php',
cache: false,
// data: $('#abc').serialize(),
dataType: 'json',
success: function(data){
alert(data);
$('#data').append(data);
}
});
}
</script>
</head>
<body onload="parseJSON()">
<p>Employee's Information</p>
<form id="abc" method ="post">
<div id="data"></div>
</form>
</body>
</html>
The login.php file contains a sample json data's as follows:
{"username":"test#test.com","password":"password"}
If you are trying to get the data using php and ajax use jsonp,
in your PHP file add callback for json output:
echo $_GET['callback'] . '('.json_encode($data).')';exit;
apppend callback in your ajax call
Javascript:
$.ajax({
url: 'http://192.168.1.12/training/services/login.php?callback=?',
cache: false,
type: "GET",
dataType: "jsonp",
contentType: "application/json; charset=utf-8",
success: function(data) {
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
And last but not least, dont forget to add domain white list for your localhost
in corodova.xml:
<access origin="http://192.168.1.12"/> OR
<access origin="*"/> to allow all domains
If I have understand correctly you may do something like that.
If your php page send data to your html one, you may use GET instead of POST
<!DOCTYPE HTML>
<html>
<h2>JSON Parser</h2>
<script type="text/javascript" src="jquery.js"/></script>
<script type="text/javascript">
function parse()
{
var json;
$.ajax({
type: 'GET',
url: 'http://192.168.1.12/training/services/login.php',
cache: false,
dataType: 'json',
success: function(data)
{
var obj = jQuery.parseJSON(data);
$('#data').html(obj["username"]);
}
});
}
</script>
</head>
<body onload="parse()">
<p>Employee's Information</p>
<form id="abc" method ="post">
<div id="data"></div>
</form>
</body>
</html>

Show data in real time with AJAX/Jquery/PHP

I am fairly new to PHP but was looking at this tutorial. http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
I want to test a similar concept to display data from my database on a page when someone submits data via a form.
eg there is a page where you choose what color shoes you want and a page with a leaderboard to see how many times each color has been chosen.
I have no problem submitting the form but don't no where to start to look to get the contents to display on the leaderboard using ajax. Can anyone point me in the right direction here please?
you should start with this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Ajax With Jquery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#txtValue').keyup(function(){
$.ajax({
url: '/ajax.php',
type: "POST",
data: "value="+$(this).val,
cache: true,
dataType: "JSON",
success: function(response){
$("#leader-board").append("you choose "+ $(this).val + "color : " +response.count + " times");
}
});
});
});
</script>
</head>
<body>
<label for="txtValue">Enter a value : </label>
<input type="text" name="txtValue" value="" id="txtValue">
<div id="leader-board"></div>
</body>
</html>
and you ajax.php file look like this
<?php
//if your data return result like this so you have to do this process
$data = array("count"=>5);
echo json_encode($data);
?>
You can send you form data and get your response in your div which have an id 'yourDivId' like below. You should to make a one more column 'countcolor' in your table . Increment it when a user request a particular color.
$.ajax({
url: base_path + "/folder/test.php",
data: "id="+id,
type: 'GET',
success: function (resp) { document.getElementById('yourDivId').innerHTML=resp;},
error: function(e){ alert('Error: '+e); }
});
After you submit the form, you need to get the pertinent data, echo it back (if you're using ajax, you want to echo is back using json_encode();), and then put it in the "leaderboard" div. e.g.
Action page for submitting to database
<?php
header('Content type: application/json');
// after you've submitted the data to the database, get the data for the leaderboard
$leaderboard_data = array();
$leaderboard_data = your_function_to_grab_data();
echo json_encode($leaderboard_data);
?>
On the page where you submit the form
$.ajax({
url: 'insert/path/to/action/here',
success: function(data) {
$("div#leaderboard-div").html(data)
}
});

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>

Categories