Using jQuery in MySQL php - php

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.

Related

send selected dropdown value to another PHP page

I do not use submit button
I want the selected value from the user sent to the test1.php page, but when the user selects an option nothing happen in the page, and the value is not sent to the test1.php page
Is there any mistake in my code, or did I miss something ?
test2.php
<?php include_once 'database.php';
?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function() {
$('.category').change(function() {
var category = $('.category option:selected').val();
alert('category changed to ' + category);
$.ajax({
method: "POST",
url: "test1.php",
data: {
category1: $(this).val()
},
success: function(data) {
console.log(data);
}
});
});
});
</script>
</head>
<p> Filter By Category</p>
<select id="category" class="category">
<?php
$query = mysqli_query($conn,"select * from category ");
while($category = mysqli_fetch_array($query)) {
echo "<option value='" . $category['cat_name'] . "'>" . $category['cat_name'] . "</option> ";
}
?>
</select>
test1.php
<?php
include_once 'database.php';
if (isset($_POST['category1'])) {
$category = $_POST['category1'];
echo $category;
}
?>
is that all your file ? did you forget to include jquery ?
I just did the same script as yours but in html, and console said $ not found, after add jquery that's working
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function() {
$('.category').change(function() {
$.ajax({
method: "POST",
url: "https://webhook.site/2d574d22-5570-46f2-b5bd-343d715adff4",
data: {
category1: $(this).val()
},
success: function(data){
console.log(data);
}
});
});
});
</script>
</head>
<body>
<p> Filter By Category</p>
<select id="category" class="category">
<option value='1'>One</option>
<option value='2'>two</option>
</select>
</body>
</html>
here is the webhook to check your request, it is like test1.php but just for debugging purpose https://webhook.site/#!/2d574d22-5570-46f2-b5bd-343d715adff4/e3406220-f58e-45be-a4ef-13d8d3e0b0d3/1
here are some advices:
inspect your page using developer tools, maybe there are some errors
check with console.log .val()
hope this help

Passing a variable from Php dropdown list to Ajax

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>

ajax textbox value no response auto suggestion

I'm trying to create an auto-suggestion AJAX box but there is no response from the server.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<head>
<title></title>
<?php
include 'search.php';
?>
<script>
$(document).ready(function() {
$("#textbox1").keyup(function() {
$.ajax({
type: "GET",
url: "search.php",
data: {textbox1: $(this).val()},
success: function (data) {
$("#main").html(data);
}
});
});
});
</script>
<form method="POST">
enter keyword to search<br>
<input type="text" name="textbox1" id="textbox1">
<br><br>
<div id="main"></div>
</form>
</head>
<body>
this is search.php
<?php
include 'connection.php';
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$search_value = $_POST['textbox1'];
$query = "SELECT username FROM users WHERE username LIKE '" . $search_value . "%'";
$conn_status = mysqli_query($conn, $query);
while($row = $conn_status->fetch_assoc())
{
echo $row['username'] . '<br>';
}
}
?>
You Missed Following
Ajax Request is Get And you use POST request in PHP
Second is not matter but it is good practice if you define action in
Change Code As follow
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<head>
<title></title>
<?php
include 'search.php';
?>
<script>
$(document).ready(function() {
$("#textbox1").keyup(function() {
$.ajax({
type: "POST",
url: "search.php",
data: {textbox1: $(this).val()},
success: function (data) {
$("#main").html(data);
}
});
});
});
</script>
<form method="POST" action="">
enter keyword to search<br>
<input type="text" name="textbox1" id="textbox1">
<br><br>
<div id="main"></div>
</form>
</head>
<body>

get and show constant from external webpage and update when change

this script receive time from www.time.is and from #twd ID and show when click on the send btn.
I have two problems:
1-only show first receive time and don't update when click on send again
2- page refresh and lose data
I have Three problem with below code:
<?php include 'simple_html_dom.php'; ?>
<!DOCTYPE html>
<html>
<head>
<title>Untitled 1</title>
<script src="js/jquery.js"></script>
</head>
<body>
<form action="" method="POST">
<input id="url" name="url" type="text" value="http://www.time.is/">
<input id="address" name="address" type="text" value="#twd">
<input id="send" type="submit" value="get">
</form>
<ul id="times">
</ul>
<script type="text/javascript">
$("#send").click(function(events) {
events.preventDefault();
var url = $("#url").val();
var address = $("#address").val();
var dataString = 'url=' + url + '&address=' + address;
$.ajax({
type: "POST",
url: "read.php",
data: dataString,
success: function() {
var result = "<?php echo getme($url,$address); ?>";
alert(result);
$('#times').append('<li></li>');
}
});
return true;
});
</script>
<?php
function getme($url, $address) {
$html = file_get_html($url);
$code = $html->find($address, 0);
return $code;
}
echo getme($url, $address);
?>
</body>
</html>
any body can help me ..
Thanx all
Try this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function timer(){
$.post( "process.php", function( data ) {
$('#times').append('<li>'+data+'</li>');
});
}
setInterval(function(){timer()},1000);
});
</script>
</head>
<body>
<ul id="times"></ul>
</body>
</html>
And put this in your process.php file:
<?php
include 'simple_html_dom.php';
$html = file_get_html('http://www.time.is/');
foreach($html->find('#clock0') as $element){
echo $element->plaintext;
}
?>
This is my test result:
11:15:43AM
11:15:46AM
11:15:51AM
11:15:53AM
11:15:53AM
11:16:10AM
11:15:52AM
11:15:42AM
11:16:09AM
11:16:17AM
11:16:12AM
Note:
1- It is advisable that you change intervals from 1000 milliseconds (1 second).
2- Don't forget to use clearInterval() after specific repeat.

How to use different pages for form input and results using AJAX

So, I have a search form in a php page (top.php) which is an include for the site I'm working on, one php page where all the mySQL stuff happens and the results are stored in a variable and echoed (dosearch.php) and lastly a php page where the results are displayed in a div through jQuery (search.php). This is the javascript code:
$(document).ready(function(){
$('#search_button').click(function(e) {
e.preventDefault();
var searchVal = $('#search_term').attr('value');
var categoryVal = $('#category').attr('value');
$.ajax({
type: 'POST',
url: 'dosearch.php',
data: "search_term=" + searchVal + "&category=" + categoryVal,
beforeSend: function() {
$('#results_cont').html('');
$('#loader').html('<img src="layout/ajax-loader.gif" alt="Searching..." />');
if(!searchVal[0]) {
$('#loader').html('');
$('#results_cont').html('No input...');
return false;
}
},
success: function(response) {
$('#loader').html('');
$('#results_cont').html(response);
}
});
});
});
The #search_term and #category fields are in top.php, the other divs (#loader and #results_cont) are in search.php. How would I go by in order to make the form submit and display the results in search.php from the top.php without problems? It works perfectly if the form and javascript are in search.php but I can't seem to separate those and make it work. What am I doing wrong?
PS. Sorry if I'm not clear enough, am at work, really tired. :(
SPLITTING:
<? include('functions-or-classes.php'); ?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<? include('js-script.php'); ?>
</head>
<body>
<? include('results-div.php'); ?>
<? include('search-form.php'); ?>
</body>
</html>
You should just respect this order then you can split the code in different pieces and include it into your main php file;
PS: peraphs your code should look like this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
$(function() {
$('#search-form').submit(function(e) {
e.preventDefault();
var searchVal = $('#search_term').val();
var query = $(this).serialize(); // search_term=lorem&category=foo
if (!searchVal) {
$('#results_cont').html('No input...');
} else {
$('#results_cont').html('<div id="loader">'+
'<img src="layout/ajax-loader.gif" alt="" /><div>');
$.ajax({
type: 'POST',
url: 'dosearch.php',
data: query,
success: function(response) {
$('#results_cont').html(response);
}
});
}
});
});
</script>
</head>
<body>
<form id="search-form">
<input type="text" id="search_term" name="search_term" />
<select id="category" name="category">
<option value="foo">foo</option>
<option value="bar">bar</option>
</select>
<input type="submit" name="search_button" />
</form>
<div id="results_cont"></div>
</body>
</html>
you can make your search_button redirect to your search.php an do the work when the pages is loaded instead of doing it on the click event.
and use $_GET['Search'] on the search page
and your url should look like this
/search.php?Search=1337

Categories