JSON success is not triggering - php

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);
}
}

Related

How to display JSON data with `vis.js`

I want to display data from MySQL with vis.js.
I get data with JSON, but I am having this error:
Error: Node must have an id
throw new Error("Node must have an id");
-------^
function tampil()
{
$.ajax({
type:"GET",
cache :false,
dataType: "json",
url:"fetch.php",
success: function(data){
console.log(data);
var vertex = new vis.DataSet([
{id:data[0], label:data[1]}
]);
var hubung = new vis.DataSet([
{from:data[2], to:data[3]}
]);
var myDiv = document.getElementById("media");
var data = {
nodes : vertex,
edges : hubung
}
var options = {};
var network = new vis.Network(myDiv,data,options);
}
});
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/vis.js"></script>
<script type="text/javascript" src="js/jquery-2.1.3.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/vis.css" />
</head>
<body>
<button type="button" onclick="tampil()">proses</button>
<div id="media" style="width:500px;height:500px;"></div>
</body>
</html>
and my server sid like this
solved, in JavaScript I've added the following code:
function tampil()
{
$.ajax({
type:"GET",
cache :false,
dataType: "json",
url:"nodes.php",
success: function(data){
console.log(data);
var vertex = new vis.DataSet();
var hubung = new vis.DataSet();
var myDiv = document.getElementById("media");
var data = {
nodes : vertex,
edges : hubung
}
var options = {};
var network = new vis.Network(myDiv,data,options);
$.getJSON('edges.php', function(edges) {
hubung.add(edges);
});
$.getJSON('nodes.php', function(nodes) {
vertex.add(nodes);
});
}
});
}

onClick Ajax data not working

As i'm building an website that needs Ajax for sending POST methods without refreshing the entire page.
I tried using ajax to send data from an onclick event on an LINK-tag, but the ajax code does seem to send an EMPTY post.
This is the php/jquery/ajax code:
<p id="school_content">
</p>
<script src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".toggleThis").click(function(){
var Id = $(this).attr('id');
$.ajax({
contentType: "application/json; charset=utf-8",
url: "id_script.php",
type: "POST",
data: {
'school_name': Id,
},
success: function(data){
alert(Id);
},
});
$("#school_content").load("id_script.php");
});
});
</script>
The LINK-tag has the 'id' of the school of wich the information needs to be shown in the PARAGRAPH with 'id' "school_content" by this jquery part: $("#school_content").load("id_script.php"); .
The var Id = $(this).attr('id'); part works, because he's giving me the right school_name in an alert(); if I ask it to.
The id_script.php needs to get this POST in the usual way, but is does not..
The id_script.php code:
<?php
include('connect.php');
header('Content-Type: application/json');
if(isset($_POST['school_name'])){
$Id = $_POST['school_name'];
$extract = mysqli_query($con, "SELECT * FROM school_kaart WHERE school_name='$Id'");
$numro=mysqli_num_rows($extract);
if(mysqli_num_rows($extract) == '1'){
$row = mysqli_fetch_assoc($extract);
echo 'Yes it works!';
}
else{
echo 'Nope, didnt work!';
}
}
else{
echo 'Not posted!';
}
?>
I'm still getting "Not posted!" in the PARAGRAPH I mentioned earlier. What seems to be the problem?
.load is shorthand for an ajax request so you are actually doing 2 request.
The latter isn't sending any data and so it returns 'Not Posted!';
http://api.jquery.com/load/
try
<script src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".toggleThis").click(function(){
var Id = $(this).attr('id');
$.ajax({
url: "id_script.php",
type: "POST",
data: {
'school_name': Id,
},
success: function(data){
alert(Id);
$("#school_content").html(data);
},
});
//remove this
//$("#school_content").load("id_script.php");
});
});
</script>

How to get the return value of a php function when calling from jQuery?

I have a php function return a string value which will put into html file.
function getDirectionInfo($routeNumber) {
//some code here
$dirinfo = "<p> some text </p>";
return $dirinfo;
}
if (isset($_POST['getDirectionInfo'])) {
getDirectionInfo($_POST['getDirectionInfo']);
}
So in jQuery, I have a following function
$(".onebtn").click(function(){
$("#directioninfo").empty();
var routeNumber = $(this).text();
$.ajax({
url: "./systemView_Function.php",
type: "POST",
data: {"getDirectionInfo": routeNumber},
success: function(data) {
console.log("HIHIHIHI");
$("#directioninfo").append(data);
}
});
})
Now console.log prints the "HIHIHIHIHI", but jQuery does not append the data to html. Anyone know how to get the return value of php function when calling from jQuery?
Instead of return use:
echo json_encode($dirinfo);
die;
It's also good idea to add dataType field to your $.ajax() function params set to json, to make sure, that data in your success function will be properly parsed.
You just need to send the response back using echo
Use var routeNumber = $(this).val(); to get the button value
PHP:
<?php
function getDirectionInfo($routeNumber) {
//some code here
$dirinfo = "<p> routeNumber". $routeNumber." </p>";
return $dirinfo;
}
if (isset($_POST['getDirectionInfo'])) {
echo getDirectionInfo($_POST['getDirectionInfo']);
}else{
echo "not set";
}
AJAX & HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$(".onebtn").click(function(){
$("#directioninfo").empty();
var routeNumber = $(this).val();
console.log("routeNumber = " + routeNumber);
$.ajax({
url: "systemView_Function.php",
type: "POST",
data: {"getDirectionInfo": routeNumber},
success: function(data) {
console.log("data = " + data);
$("#directioninfo").append(data);
}
});
})
});
</script>
</head>
<body>
<div id="directioninfo"></div>
<input type="button" value="12346" class="onebtn" />
</body>
</html>
Thank you for everyone. I have just found that I made a very stupid mistake in jQuery. I should use var routeNumber = parseInt($(this).text()); instead of var routeNumber = $(this).text(); So the following code work to get the return value of php function when calling from jQuery.
in php
function getDirectionInfo($routeNumber) {
//some code here
$dirinfo = "<p> some text </p>";
echo json_encode($dirinfo);
}
if (isset($_POST['getDirectionInfo'])) {
getDirectionInfo($_POST['getDirectionInfo']);
}
in jQuery
$(".onebtn").click(function(){
$("#directioninfo").empty();
var routeNumber = parseInt($(this).text());
$.ajax({
url: "./systemView_Function.php",
type: "POST",
data: {"getDirectionInfo": routeNumber},
dataType: "JSON",
success: function(data) {
$("#directioninfo").append(data);
}
});
})

AJAX success function not executing

I'm trying to create a simple AJAX call for testing, but have encountered a problem. I have nested in my AJAX call a success function which should pop an alert message but it doesn't. Checking firebug, the POST is successful and responds with "A20" (without quotations). Is there something wrong in my code?
index.php (view)
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="init.js"></script>
<script src="jquery-1.10.2.min.js"></script>
</head>
<body>
<button id="your_button">Push me</button>
</body>
</html>
init.js
$(function() {
$('#your_button').bind("click", function() {
var json_data = {"category": "A", "size": "20"};
$.ajax({
url: "posted.php",
dataType: "json",
type: "POST",
cache: false,
data: {"data": json_data},
success: function (data) {
if (!data.error) {
alert('k');
} else {
alert('error!');
}
}
});
});
});
posted.php
$category = $_POST['data']['category'];
$tsize = $_POST['data']['size'];
echo ($category);
echo ($size);
Try this -
$(function() {
$('#your_button').bind("click", function() {
var json_data = {"category": "A", "size": "20"};
$.ajax({
url: "posted.php",
dataType: "json",
type: "POST",
cache: false,
data: json_data,
success: function (data) {
if (!data.error) {
alert('k');
} else {
alert('error!');
}
}
});
});
});
Posted.php
$category = $_POST['category'];
$tsize = $_POST['size'];
//echo ($category);
//echo ($tsize);
echo json_encode($_POST);
Your want json data but you were not echoing json data
this is not right:
data: {"data": json_data}
do like this:
data: {data: json_data}
You need to set proper headers in your PHP and send a valid json response from PHP file. Add these lines to your PHP
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
and echo back some valid json from it like echo '{"auth":"true","error":"false"}';
First you are using two jquery libraries, remove any one of them.
Second replace data: {"data": json_data}, with data: json_data,.
Third on posted.php use $category = $_POST['category'] and $tsize = $_POST['size'];.
Hope it will help you.

Content tabs and select option value to display data ( jquery and php)

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.

Categories