OK, so I've installed jQuery on my GoDaddy hosting account. I need to display a result in a text box and have done my HTML, which gets a user input, a button click and a results area (div id=status). I want to simply put the result in a box without having to refresh the page. I'm trying this json thing and AJAX to accomplish this and I'm trying to figure out what is wrong with my attempt. Here is the HTML.
<!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">
<script language='JavaScript' type='text/javascript'>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>
<body>
<p>Miles <input name="miles" id="miles" type="text" /> <button type="button" name="getdata" id="getdata">Submit</button></p>
<p></p>
<div id="status">
</div>
<script type="text/javascript" language="javascript">
$('getdata').click(function(){
$.ajax({
url: 'process.php',
type:'POST',
dataType: 'json',
success: function(output_string){
$('#result_table').append(output_string);
}
));
});
</script>
</body>
</html>
and it should be sent to process.php file:
<?php
$hostname = 'myhost.com';
$username = 'ratetable';
$password = 'mypassword';
$miles = (int) $_POST['miles'];
try
{
$db = new PDO("mysql:host=$hostname;dbname=ratetable", $username, $password);
foreach($db->query('SELECT * FROM rates WHERE mileage<= ' . $miles . ' ORDER BY mileage DESC LIMIT 1') as $row) {
$output_string .= '<input type='text' name='answer' value='" . $row['ratepermile'] . "'>';
}
}
echo json_encode($output_string);
catch (PDOException $e) {
echo $e->getMessage();
throw($e);
}
?>
I tried to use an example to construct this and nothing happens...not even the HTML form. What is wrong with this?
Thanks for having a look.
Your selector is wrong $('getdata') should be $('#getdata'), you have to prefix the id with a # to select an element with its id. Also you have to pass the parameters to the post request
$.ajax({
url: 'process.php',
type:'POST',
data: {miles: $('#miles').val()},
dataType: 'json',
success: function(output_string){
$('#result_table').append(output_string);
}
));
Try this,
$('#result_table').val(output_string);
Related
I've got a form (id="my_form_id") and inside the form I have Dropdown list populated using PHP and a query from a Mysql, this mysql query pick the column named grupo and populated the dropdown list, the mysql table field named nombregrupo is put and updated (onchange) in a "input text" named nombregrupo using the Java script function "showname". I've got a text (named "nombregrupon") for typing and changing field nombregrupo.
I want to send the information selected from drop down list (field grupo) and typed in the text (named "nombregrupon") to ajax jquery function, and this ajax function calls a php file (postdata.php) for processing a returning data back to ajax.
I can pass the information entered in the text (named "nombregrupon") to ajax function but I cannot pass the information from dropdown list (grupo) to ajax function, this is the whole code:
<!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=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/JavaScript">
<!--
function MM_goToURL() { //v3.0
var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}
</script>
//Java script function for updating input text nombregrupo
<script language="JavaScript">
function showname(what)
{
what.form.nombregrupo.value=what.options[what.selectedIndex].title
}
window.onload=function() {
showname(document.form1.grupo)
}
</script>
//Ajax Jquery for send data variables grupo and nombregrupon to php
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
$('#my_form_id').on('submit', function(e){
//Stop the form from submitting itself to the server.
e.preventDefault();
var nombregrupon = $('#nombregrupon').val();
var grupo= $('#grupo').val();
$.ajax({
type: "POST",
url: 'postdata.php',
data: { grupo: grupo, nombregrupon: nombregrupon },
success: function(data){
//Send Alert
alert(data);
//Show data returne from php postdata file
$('#result').html(data);
}
});
});
});
</script>
</head>
<body>
<form id="my_form_id" name="form1">
<?php
$con = mysql_connect("localhost","root","mysq1passw0rd");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("llamadas", $con);
//PHPMysql Query for fill dropdown list
$query1 = "SELECT * FROM grupostroncales ".
"WHERE grupo!='$grupox' ORDER BY grupo";
$result1 = mysql_query($query1) or die(mysql_error());
//On change call java script funtion for update Input text nombregrupo
echo "<select name=\"grupo\" onchange=\"showname(this)\">";
while($row1=mysql_fetch_array($result1)){
echo "<option value=\"$row1[grupo]\" title=\"$row1[nombregrupo]\">$row1[grupo]</option>";
}
echo "</select>";// Closing of list box
?>
//Input Text for showing group Name
<input name="nombregrupo" type="text" id="nombregrupo"/>
//Input Text for entering new group Name
<input name="nombregrupon" type="text" id="nombregrupon" />
<input name="submit" type="submit" id="submit" value="Acept" />
<div id="result"></div>
</form>
</body>
</html>
You have a few options:
You can add the id to the select element, as you forgot that
var grupo=$('#grupo').val()
echo "<select name=\"grupo\" onchange=\"showname(this)\">"; <-- no id
//----------------
echo "<select id=\"grupo\" name=\"grupo\" onchange=\"showname(this)\">";
or You can use the name
var grupo=$('select[name="grupo"]').val()
or You can serialze the whole form
$.ajax({
data : $('#my_form_id').serialize(),
...
});
Personally I would just serialize the form
Thanks again, I modified the code addind "select id" and It worked.
Please, Now I'm trying to pass the whole form variables using serialize but I doesn't work, this is my code:
<!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=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/JavaScript">
<!--
function MM_goToURL() { //v3.0
var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}
//Fir
</script>
<script language="JavaScript">
function showname(what)
{
what.form.nombregrupo.value=what.options[what.selectedIndex].title
}
window.onload=function() {
showname(document.form1.grupo)
}
</script>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
var Formvar = $('#my_form_id');
$("#submit").click(function(){
$.ajax({
type: "POST",
url:Formvar.attr("action"),
//url: 'ActualizarGrupoTroncalb.php',
data:Formvar.serialize(),
success: function(data){
//Send Alert
alert(data);
//Show data from mysql query
$('#result').html(data);
}
});
});
});
</script>
</head>
<body>
<form action="ActualizarGrupoTroncalb.php" id="my_form_id" name="form1">
<?php
$con = mysql_connect("localhost","root","mysq1passw0rd");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("llamadas", $con);
//Hago query1 selecciono el Departamento a buscar
$query1 = "SELECT * FROM grupostroncales ".
"WHERE grupo!='$grupox' ORDER BY grupo";
$result1 = mysql_query($query1) or die(mysql_error());
echo "<select id=\"grupo\" name=\"grupo\" onchange=\"showname(this)\">";
while($row1=mysql_fetch_array($result1)){//Array or records stored in $nt
echo "<option value=\"$row1[grupo]\" title=\"$row1[nombregrupo]\">$row1[grupo]</option>";
}
echo "</select>";// Closing of list box
?>
<input name="nombregrupo" type="text" id="nombregrupo"/>
<input name="nombregrupon" type="text" id="nombregrupon" />
<input name="submit" type="submit" id="submit" value="Acept" />
<div id="result"></div>
</form>
</body>
</html>
#lexer, in regards to your second question, you may want to try .serializeArray() instead of serialize().
.serialize() returns a string of values formatted like a query string and that may not be what you are expecting.
FYI - I would have commented to the post but I cannot comment yet.
I changed my code and variables are serialized to php file: ActualizarGrupoTroncalb.php and recieved for php file because I can make a mysql query using variables, but returning data from php to ajax is not show in: <div id="resp"></div>
This my code:
<!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=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/JavaScript">
<!--
function MM_goToURL() { //v3.0
var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}
</script>
<script language="JavaScript">
function showname(what)
{
what.form.nombregrupo.value=what.options[what.selectedIndex].title
}
window.onload=function() {
showname(document.form1.grupo)
}
</script>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$(document).on('ready',function(){
$('#submit').click(function(){
var url = "ActualizarGrupoTroncalb.php";
$.ajax({
type: "POST",
url: url,
data: $("#formulario").serialize(),
success: function(data)
{
$('#resp').html(data);
}
});
});
});
</script>
</head>
<body>
<form method="post" id="formulario">
<?php
$con = mysql_connect("localhost","root","mysq1passw0rd");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("llamadas", $con);
//Hago query1 selecciono el Departamento a buscar
$query1 = "SELECT * FROM grupostroncales ".
"WHERE grupo!='$grupox' ORDER BY grupo";
$result1 = mysql_query($query1) or die(mysql_error());
echo "<select id=\"grupo\" name=\"grupo\" onchange=\"showname(this)\">";
while($row1=mysql_fetch_array($result1)){//Array or records stored in $nt
echo "<option value=\"$row1[grupo]\" title=\"$row1[nombregrupo]\">$row1[grupo]</option>";
}
echo "</select>";// Closing of list box
?>
<input name="nombregrupo" type="text" id="nombregrupo"/>
<input name="nombregrupon" type="text" id="nombregrupon" />
<input name="submit" type="submit" id="submit" value="Acept" />
</form>
<div id="resp"></div>
</body>
</html>
I am working on trying to post to ajax file with jquery and showing result on page posted from. Post gets posted but I get no reply from ajax. Am i missing something here?
form file
<!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>Test Ajax</title>
<script src="js/jquery-1.10.2.js"></script>
</head>
<body>
<form id="myform" />
<input type="text" id="youTyped" value=""/>
<input type="submit" value="Submit">
</form>
<div id="answer"></div>
<script type="text/javascript">
$('#myform').submit(function(){
var youTyped = $("#youTyped").val();
var data = {youTyped:youTyped};
$.ajax({
type: "POST",
url: "scripts/ajaxTest.php",
data: data,
success: function(response){
$("#answer").html(response);
}
});
});
</script>
</body>
</html>
ajax file
<?php
if(isset($_POST['youTyped'])){
$youTyped = $_POST['youTyped'];
}
echo $youTyped;
?>
Well, first of all, you didn't write your form correctly, the elements you want to send are not inside the form.
Second, your js function is not avoiding the form for being sent, so you're reloading the page when submitting the form.
So, to correct it, and get the answer, just change the code to:
<!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>Test Ajax</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
</head>
<body>
<form id="myform">
<input type="text" id="youTyped" value=""/>
<input type="submit" value="Submit">
<div id="answer"></div>
</form>
<script type="text/javascript">
$('#myform').submit(function(e){
// Avoid send the form as a normal request
e.preventDefault();
var youTyped = $("#youTyped").val();
var data = {youTyped:youTyped};
$.ajax({
type: "POST",
url: "scripts/ajaxTest.php",
data: data,
success: function(response){
$("#answer").html(response);
}
});
});
</script>
</body>
</html>
One last thing. To test it, when you're sending and receiving AJAX, if you're using Chrome you can use the development tools to know if you're sending correctly the requests. Just press F12, and then go to Network tab. If you're using correctly AJAX, you'll see how new lines are added when you press the submit button:
You need to return false on form submit. The form is being submited before ajax request. Also add a closing tag for form.
<script type="text/javascript">
$('#myform').submit(function () {
var youTyped = $("#youTyped").val();
var data = {
youTyped: youTyped
};
$.ajax({
type: "POST",
url: "scripts/ajaxTest.php",
data: data,
success: function (response) {
$("#answer").html(response);
}
});
return false;
});
</script>
Try if this code is working:
<body>
<input type="text" id="youTyped" value=""/>
<input type="submit" id="submit" value="Submit">
<div id="answer"></div>
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function(){
var youTyped = $("#youTyped").val();
$.post('scripts/ajaxTest.php',{"youTyped" : youTyped},function(response)
{
$("#answer").html(response);
});
});
});
</script>
</body>
</html>
<!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>Test Ajax</title>
<script src="js/jquery.min.js"></script>
<script type="text/javascript">
$('#myform').submit(function(event){
event.preventDefault();
var youTyped = $("#youTyped").val();
var data = {youTyped:youTyped};
$.ajax({
type: "POST",
url: "ajaxTest.php",
data: data,
success: successMsg,
error: errorMsg
});
});
function successMsg(response){
alert(response);
$("#answer").html(response);
}
function errorMsg(){
alert("Invalid Ajax Call");
}
</script>
</head>
<body>
<form id="myform" />
<input type="text" id="youTyped" value=""/>
<input type="submit" value="Submit">
<div id="answer"></div>
</body>
</html>
As I toyed with the idea, thought that this would make a good addition/contribution to the question.
I added and modified a few things.
One of which being:
If nothing was typed into the form input field, it would return "You typed: Nothing".
PHP:
<?php
if(!empty($_POST['youTyped'])){
$youTyped = $_POST['youTyped'];
echo "You typed: " .$youTyped;
}
else if (empty($_POST['youTyped'])){
echo "You typed: Nothing";
}
?>
i have a simple form where one one field is there which is random javascript file whose name ranges from 1 to 500000 so i have used rand function to populate its field without any issue
i want form to be automatically submitted after loading but i dont want pages to be refreshed and even i dont want field value to be changed after form is submitted. my code is very clear but dont know why it is not working
index.html
<!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=iso-8859-1" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<title>testing</title>
</head>
<body>
<script type="text/javascript" >
$(function() {
$("form1#form1").submit(function() {
var searchBox = $("#searchBox").val();
var dataString = 'searchBox='+ searchBox ;
if(searchBox=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "test34.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
<form method="post" name="form1" id="form1" enctype="multipart/form-data">
<input type="text" class="status" name="searchBox" id="searchBox" value="<?= "".rand(1,2889889).".js"; ?>">
<input class="button" type="submit" value="Submit" /></form>
</body>
</html>
test34.php
<?php
include('connect.php');
$title23 = $_POST['searchBox'];
mysql_query("insert into test (title) values('$title23')");
echo $title23;
?>
but it is not submitting the form automatically please advise
Your selector should probably look like this $("form#form1") instead of $("form1#form1")
After you've bound your submit method to the form, try triggering the submit method by doing this.
return false;
});
$("form1#form1").trigger('submit'); // Here
});
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)
}
});
I am new to using Jquery using mysql and PHP.
I am using the following code to pull the data. But there is not data or error displayed.
JQUERY:
<html>
<head>
<script>
function doAjaxPost() {
// get the form values
var field_a = $("#field_a").val();
$.ajax({
type: "POST",
url: "serverscript.php",
data: "ID="+field_a,
success: function(resp){
$("#resposnse").html(resp);
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
</head>
<body>
<select id="field_a">
<option value="data_1">data_1</option>
<option value="data_2">data_2</option>
</select>
<input type="button" value="Ajax Request" onClick="doAjaxPost()">
Here
<div id="resposnse">
</div>
</body>
and now serverscript.php
<?php
if(isset($_POST['ID'])) {
$nm = $_POST['ID'];
echo $nm;
//insert your code here for the display.
mysql_connect("localhost", "root", "pop") or die(mysql_error());
mysql_select_db("JPro") or die(mysql_error());
$result1 = mysql_query("select Name from results where ID = \"$nm\" ")
or die(mysql_error());
// store the record of the "example" table into $row
while($row1 = mysql_fetch_array( $result1 )) {
$tc = $row1['Name'];
echo $tc;
}
}
?>
Like Mike said, this also worked for me when I put it in the ready function and removed the button onclick. Open up your error console in Firefox and see if it is outputting anything
<?php
if(isset($_POST['ID'])){
echo ($_POST['ID']);
exit;
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title> Heather Alexandra </title>
<script type="text/javascript" src="../intranet/include/js/jQuery/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#ajax").click(function(){
$.ajax({
type: "POST",
url: "test.php",
data: "ID="+$("#field_a").val(),
success: function(resp){
$("#resposnse").html(resp);
},
error: function(e){
alert('Error: ' + e);
}
});
});
});
</script>
</head>
<body>
<div style="margin: 0 auto; width: 822px;">
<select id="field_a">
<option value="data_1">data_1</option>
<option value="data_2">data_2</option>
</select>
<input id="ajax" type="button" value="Ajax Request">
<div id="resposnse"></div>
</div>
</body>
</html>
I just did everything you did except changed the serverscript.php to:
<?php
if(isset($_POST['ID'])) {
$nm = $_POST['ID'];
echo $nm;
}
?>
And the script worked fine. I think all you have to do is get back down to the basics and find out what is actually generating the error. Try using firebug for firefox to see if you are generating any script errors. If not try changing the serverscript.php to use $_GET and type the following address to see what you get: http://yourtestserver/serverscript.php?ID=data_1
Debugging can get tricky when you deal with ajax but if you break it down to it's individual pieces it should make it easier.