I am creating content tabs that are showing data depending on the chosen value in the select box list. My problem is that I can´t figure out how to setup that the value of the chosen item(league) stays so all three tabs show data from the chosen item (league). For easier understanding I am trying to do is if the user has chosen Premier League the tabs will show the standings, results and goalscorers from that league.
Here is my code:
HTML:
<!Doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src=jquery.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<ul id="nav">
<li>Standings</li>
<li>Results</li>
<li>Goalscorers</li>
<li><select name="selecting" class="selecting">
<option value="0">--Choose a league--</option>
<?php
$sql=mysql_query("select * from leagues ORDER BY id ASC LIMIT 6");
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$data=$row['name'];
echo '<option value="'.$id.'">'.$data.'</option>'; } ?>
</select></li>
</ul>
<div id="content"> </div>
Jquery (script.js)
$(document).ready(function(){
$(".selecting").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax ({
type: "POST",
url: "tab1.php",
data: dataString,
dataType: "html",
cache: false,
success: function(data)
{
$("#content").html(data).show();
}
});
$.ajax({
type: "POST",
url: "tab2.php",
data: dataString,
dataType: "html",
cache: false,
success: function(data)
{
$("#content").html(data).show();
}
});
$.ajax({
type: "POST",
url: "tab3.php",
data: dataString,
dataType: "html",
cache: false,
success: function(data)
{
$("#content").html(data).show();
}
});
});
$('#content').load('tab1.php');
$(' ul#nav li a ').click(function() {
var page = $(this).attr('href');
$('#content').load(page + '.php');
return false;
});
});
Here is a tab file, all three are the same just the sql queries are different.
tab2.php
#$id=$_POST['id'];
if(!empty($id))
{
$mysql = mysql_query(" SELECT * from results WHERE leagueid = '$id' ORDER BY matchday asc LIMIT 10 ");
$matchday = "";
while ($row = mysql_fetch_array($mysql)) {
if($matchday != $row['matchday']) {
$matcday = $row['matchday'];
echo 'Matchday: '.$row['matchday'].'<br>';
}
echo ''.$row['hteam'].' '.$row['hgoals'].' : '.$row['agoals'].' '.$row['ateam'].'<br>';
}`
I thank in advance for the help.
Best regards.
hey please edit your code if you have coded the same then please ping again because the written here is full of bugs like described bellow
You have not initialized the jquery($(document).ready(function(){});)
You have a php syntax error on the page where you are extracticting the result
You have coded a very bad script.
Related
I am having trouble with my JSON payload. The success function does not fire.
Thanks in advance for any help that can be provided.
JLS
I get the value in the console so I know the query works okay but it is not in a key/value pair it just echos "VALUE" and does not triggers success.
//JS file ***UPDATED***
$(document).ready(function(){
// code to get all records from table via select box
$("#school").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'school='+ id;
$.ajax({
url: 'cif_submit.php',
dataType: "json",
data: dataString,
cache: false,
success: function(data) {
if(data) {
alert(data);
}
}
});
})
});
//Here is the php ***UPDATED***
if($_REQUEST['school']) {
$stmt = $conn->prepare("SELECT streetname FROM schoolinfo WHERE fullschoolname = :schoolname");
$stmt->execute (array(':schoolname' =>$_REQUEST['school']));
while($mydata = $stmt->fetch()) {
echo json_encode($mydata);
} }
}
The JSON RESPONSE is:
{"streetname":"Colbeck Road, PO Bag 7200","0":"Colbeck Road, PO Bag 7200"}
I think changing the schooldata to data will fix the issue.
Don't forget that change() event gets called when you unfocus the input.
https://api.jquery.com/change/
Tried with this code and worked perfectly.
JS
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
<input id="school" type="text">
<script>
$(document).ready(function(){
// code to get all records from table via select box
$("#school").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'school='+ id;
$.ajax({
url: 'a.php',
dataType: "json",
data: dataString,
cache: false,
success: function(schooldata) {
if(schooldata) {
alert('success');
//$("#streetname").text(schooldata.streetname); TRIED THIS NO JOY
//$("#streetname").hide(); TRIED THIS NO JOY
}
}
});
})
});
</script>
</body>
</html>
PHP
if($_REQUEST['school']) {
$datas = array();
$datas[] = array('streetname' => 'test');
foreach ($datas as $data) {
$data = $data['streetname'];
//$streetname = trim(json_encode($data), '"');
//echo json_encode($data);
echo json_encode($data, true);
}
}
I'm trying to display the search result of my page under the the search area. So I used AJAX to display the result in a div. but I could'nt get it work.
I have three main pieces, the div, the searchResult page and the ajax function
<input type="text" name="studentName">
<button type="submit" name="searchByName" onclick='get_info();'>بحث</button>
<div id="searchResult"><b></b></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function get_info() { // Call to ajax function
$.ajax({
type: "POST",
url: "NameSearchResult.php", // Name of the php files
data: {name: <?php echo $_POST['studentName']; ?>},
success: function(html)
{
$("#searchResult").html(html);
}
});
}
and my search Page:
<?php
include_once 'dbConfigBDO.php';
$studentName = $_POST["name"];
$counter=0;
$emptyString = "لايوجد";
$sql = "SELECT * FROM Student";
$result = $conn->query($sql);
$row_count = $result->rowCount();
if ($row_count > 0){
.......... }
Now when I search nothing appears, although it works when I put all the code in one page (which would be messy in term of the appearance of the result!).
From function return the output as per below:
return json_encode($result);
In ajax call use dataType:"json" and show your html
Example ajax call:
$.ajax({
type: "POST",
dataType:"json",
url: "NameSearchResult.php", // Name of the php files
data: {name: $("#studentName").val()},
success: function(html)
change code like this
<input type="text" name="studentName" id="studentName">
<button type="submit" name="searchByName" onclick='get_info();'>بحث</button>
<div id="searchResult"><b></b></div>
<script>
$.ajax({
type: "POST",
url: "NameSearchResult.php", // Name of the php files
data: {name: $("#studentName").val()},
success: function(html)
{
$("#searchResult").html(html);
}
});
}
</script>
inside ajax success method try catch what you are getting
success: function(html)
{
console.log(html);
}
if you getting something then your code must be work.
I am trying to show loading image until php excutes, the query works on the second page but the results aren't showing on the first page, I know I am missing something here, can someone help me out? I am new to jquery or ajax thing.
home.php
<html>
<head>
<!--Javascript-->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$('#loading_spinner').show();
var post_data = "items=" + items;
$.ajax({
url: 'list.php',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('.my_update_panel').html(data);
},
error: function() {
alert("Something went wrong!");
}
});
$('#loading_spinner').hide();
</script>
<style>
#loading_spinner { display:none; }
</style>
</head>
<body>
<img id="loading_spinner" src="image/ajax-loader.gif">
<div class="my_update_panel">
<!--I am not sure what to put here, so the results can show here-->
</div>
list.php I tested the query and it prints the rows.
<?php
include_once("models/config.php");
// if this page was not called by AJAX, die
if (!$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') die('Invalid request');
// get variable sent from client-side page
$my_variable = isset($_POST['items']) ? strip_tags($_POST['items']) :null;
//run some queries, printing some kind of result
$mydb = new mysqli("localhost", "root", "", "db");
$username = $_SESSION["userCakeUser"];
$stmt = $mydb->prepare("SELECT * FROM products where username = ?");
$stmt->bind_param('s', $username->username);
$stmt->execute();
// echo results
$max = $stmt->get_result();
while ($row = $max->fetch_assoc()) {
echo $row['title'];
echo $row['price'];
echo $row['condition'];
}
?>
The HTML. Put the img inside of the .my_update_panel div
<div class="my_update_panel">
<img id="loading_spinner" src="image/ajax-loader.gif">
</div>
The JS
var url = 'list.php';
var post_data = "items=" + items;
$('.my_update_panel').load(url, post_data, function() {
$(this +' #loading_spinner').fadeOut('slow');
});
You can find a good selection of loading images that are readily available for download here.
There is a issue with
var post_data = "items=" + items;
Make it
$(document).ready(function(){
$('#loading_spinner').show();
$.ajax({
url: 'list.php',
type: 'POST',
data: {"items":items},
dataType: 'html',
success: function(data) {
$('.my_update_panel').html(data);
$('#loading_spinner').hide();
},
error: function() {
alert("Something went wrong!");
}
});
});
let me know if works for you.
Try To add complete event in the ajax , I hope it will work. Refer
http://api.jquery.com/jQuery.ajax/
<html>
<head>
<!--Javascript-->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$('#loading_spinner').show();
var post_data = "items=" + items;
$.ajax({
url: 'list.php',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('.my_update_panel').html(data);
},
error: function() {
alert("Something went wrong!");
},
complete:function(){
$('#loading_spinner').fadeOut(500);
});
//$('#loading_spinner').hide();
</script>
<style>
#loading_spinner { display:none; }
</style>
</head>
<body>
<img id="loading_spinner" src="image/ajax-loader.gif">
<div class="my_update_panel">
<!--I am not sure what to put here, so the results can show here-->
</div>
It is better to chain the ajax callback functions. adding callbacks as options will be removed from jquery in the future.
http://api.jquery.com/jQuery.ajax/
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and
jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare
your code for their eventual removal, use jqXHR.done(), jqXHR.fail(),
and jqXHR.always() instead.
var post_data = items;
$('#loading_spinner').show();
$.ajax({
url: 'list.php',
type: 'POST',
dataType: 'html',
data: {"items":post_data},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
$('#loading_spinner').hide();
});
I hide the loading_spinner in the always() callback, that way the spinner also disappears when the ajax call throws an error. if this is not working you have to search in your server side code to solve the problem. First of, are you sure the response is html? you might have to set the dataType to text in the ajax call.
I am using Twitter Bootstrap Typeahead for an autocomplete field.
End state goal: The user first enters details into field 1. When they enter details in field 2, ajax passes the query as it is written to a PHP file which queries a database based on what was also entered into field 1.
How do I pass both the query from field 2 and the contents of field 1 to the PHP file and access them.
Here is what I have so far:
HTML FILE:
<div class="field1">
<input type="text" id="field1" data-provide="typeahead" name="field1">
</div>
<div class="field2">
<input type="text" id="field2" data-provide="typeahead">
</div>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/bootstrap.js"></script>
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
PHP FILE:
if (isset($_POST['query'])) {
$db_server = mysql_connect("localhost", "root", "root");
mysql_select_db("db_test");
$query = $_POST['query'];
$other = '**This needs to be field 1**';
$sql = mysql_query("SELECT * FROM table WHERE row1 LIKE '%{$query}%' AND row2 = '$other'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['row1'];
}
echo json_encode($array);}
At the moment, the query part works perfectly and the results are returned (the console also displays the value from 'Field1'. Just need to get that value into the php file at the same time!
Any help would be great
If I understood this correctly, you want to parse both the values of field 1 and 2 to the same AJAX call. This is how you do it.
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query + '&field1=' + textVal,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
Now you just make another $_POST['field1'] in your PHP file.
var userQuery = $('#ID of query input element').val();
var field1 = $('#ID of input 1 element').val();
$.ajax({
type: "POST",
url: '',
data: {query: QueryVariable, input1: input1variable},
success: function(data) {
// code within this block
},
error: function() {
alert('System Error! Please try again.');
},
complete: function() {
console.log('completed')
}
}); // ***END $.ajax call
Ok, so I have this search box in which people typein a food item. When they press the button I need that input to be send to a .php file. That php file will look op the calories of that food item (thats in my database) and output the food item name and calories. All this need to be done without reloading the page so I started figuring out how JQuery works.
However I am stuck, I don't know what to put in the data field of the jquery function and how I can 'catch' that data in the .php file. Can someone give me an idea? thanks a lot! (see the ??????'s for things i don't understand). Also, the data that comes back needs not to be in an alert box in the end, but update some table on my page, how can i do this? which JSON (?) Jquery function do I need?
what I have up until now:
in head:
<script type="text/javascript">
function contentDisp()
{
$.ajax({
type: 'POST',
url: 'getFood.php',
data: '????????',
success: function(data){
alert("Data Loaded: " + data);
}
});
}
</script>
and in body:
<form autocomplete="off">
<p>
Product:
<input type="text" name="food" id="food" class="food_name_textbox" onmouseover="javascript: this.className='food_name_textbox_mouseover';" onmouseout="javascript: this.className='food_name_textbox';" / >
</p>
<button id="zoek" type="button" onClick="contentDisp();">Zoek</button>
</form>
and in getFood.php:
<?php
require_once "config.php";
$id = "??????"
$result = mysql_query("SELECT * FROM voedingswaarden WHERE voedsel='$id'");
$row = mysql_fetch_array($result);
echo json_encode($row);
?>
$.ajax({
type: 'POST',
url: 'getFood.php',
data: {'foodnametextbox' : $('#food').val() },
datatype: "json",
success: function(data){
$('#table').html(data);
}
});
<?php
require_once "config.php";
$id = $_POST['foodnametextbox']; //escape and validate this input before using it in a query
$result = mysql_query("SELECT * FROM voedingswaarden WHERE voedsel='$id'");
$row = mysql_fetch_array($result);
echo json_encode($row);
?>
<script type="text/javascript">
function contentDisp()
{
var textSearch = $("#myText").text();
$.ajax({
type: 'POST',
url: 'getFood.php',
data: textSearch,
success: function(data){
alert("Data Loaded: " + data);
}
});
}
</script>
PHP:
$id = $_POST['textSearch'];