Cannot display JSON data in a table using jQuery and AJAX - php

I am trying to display data fetched as JSON from MySQL DB using PHP into an HTML element say a table. Below is my code for this:
<!DOCTYPE html>
<html>
<head>
<title>Test Ajax</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#display").change(function()
{
var type = document.getElementById('display').value;
$.ajax(
{
//create an ajax request to load_page.php
type: "POST",
url: "DBOperations.php",
data : "type=" +type,
dataType: "text", //expect text to be returned
success: function(response)
{
var tr = $('<tr>');
tr.append('<td>' + response.client_id + '<td>');
tr.append('<td>' + response.client_name + '<td>');
tr.append('<td>' + response.client_title + '<td>');
tr.append('<td>' + response.client_type + '<td>');
$('#myTable').append(tr);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('error: ' + textStatus + ': ' + errorThrown);
alert(response);
}
});
});
});
</script>
</head>
<body>
<form>
<select id="display" name="clienttype" onchange="showClient(this.value)">
<option value="">Select a Client:</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
</form>
<br>
<table id="myTable">
<tr>
<th>ClientID</th>
<th>ClientName</th>
<th>ClientTitle</th>
<th>ClientType</th>
</tr>
</table>
</form>
</body>
</html>
Here is what i am getting from php as JSON:
[{"client_id":"1","0":"1","client_name":"asdf","1":"asdf","client_title":"asdf","2":"asdf","client_type":"a","3":"a"}]
Besides if i set the datatype in AJAX to json, it displays the error as in this question:
how to remove parsererror: SyntaxError: Unexpected token < in JSON at position 0
So i keep it as either html or text which at least displays the response wtihout the error. but i need to format the response and feed it to another element.
Thanks in advance.

$.ajax(
{
//create an ajax request to load_page.php
type: "POST",
url: "DBOperations.php",
data : {"type :" +type},
dataType: "text", //expect text to be returned
success: function(response)
{
var data = response.d;
var tr = $('<tr>');
tr.append('<td>' + data .client_id + '<td>');
tr.append('<td>' + data.client_name + '<td>');
tr.append('<td>' + data.client_title + '<td>');
tr.append('<td>' + data.client_type + '<td>');
$('#myTable').append(tr);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('error: ' + textStatus + ': ' + errorThrown);
alert(response);
}
});
try this one.

First of all, if you're expecting a JSON string back from server then you should put dataType: "json" in your AJAX request. And second, your success callback function should be like this:
success: function(response){
var tr = $('<tr>');
tr.append('<td>' + response[0].client_id + '<td>');
tr.append('<td>' + response[0].client_name + '<td>');
tr.append('<td>' + response[0].client_title + '<td>');
tr.append('<td>' + response[0].client_type + '<td>');
$('#myTable').append(tr);
}
Update(1): Based on the question link you shared, it's clearly visible that you're creating and outputting json string in the wrong way, your PHP and AJAX code should be like this:
PHP code:
try{
$dsn = 'mysql:host=localhost;dbname=practice_db'; //your host and database name here.
$username = 'root';
$password = '';
//Connect to database
$conn = new PDO($dsn, $username, $password);
$query = "SELECT * FROM client WHERE client_type = :client_type";
//Prepare and Execute Query
$stmt = $conn->prepare($query);
$stmt->bindParam(':client_type', $type);
$stmt->execute();
$rows = $stmt->fetchAll();
echo json_encode($rows);
}catch (PDOException $ex){
echo "There was a problem executing the Query: " . $ex->getMessage();
}
AJAX code:
$.ajax({
type: "POST",
url: "DBOperations.php",
data : "type=" + type,
dataType: "json",
success: function(response){
$.each(response, function(key,value) {
var tr = $('<tr>');
tr.append('<td>' + value.client_id + '<td>');
tr.append('<td>' + value.client_name + '<td>');
tr.append('<td>' + value.client_title + '<td>');
tr.append('<td>' + value.client_type + '<td>');
$('#myTable').append(tr);
});
},
error: function(jqXHR, textStatus, errorThrown){
alert('error: ' + textStatus + ': ' + errorThrown);
alert(response);
}
});

Related

Jquery Get Reqeust Not Displaying Data

Ok, I have two pages. getprofilecomment.php and getprofilecomment.js. The get getprofilecomment.php is functioning, but the getprofilecomment.js is not working for some reason. It is not displaying any content. The div id is correct. Here is the code:
$(function()
{
var userId = $(#userid).val();
$.ajax({
url: "api/getprofilecomment.php",
method: "GET",
data: userId,
cache: false,
success: function(comment){
$(#usercommentdiv).apprend('<li>' + comment.user_name + ':' + comment.profile_comment + ',' + comment.time_added + '</li>');
}
});
});
Once again, the json_encode is echoing the content successfully to the page.
<?php
include ("../db/database.php");
include ("../classes/profilecommentclass.php");
session_start();
$profileCommentHandler = new ProfileComment($db);
$userId = $_GET['userId'];
$profileComment = $profileCommentHandler->getComment($userId);
echo json_encode($profileComment, JSON_FORCE_OBJECT);
?>
Hi you are missing id (usercommentdiv) in quotes,
success: function(comment){
$('#usercommentdiv').apprend('<li>' + comment.user_name + ':' + comment.profile_comment + ',' + comment.time_added + '</li>');
}

jQuery ajax request giving error : undefined

I'm trying to recieve data in JSON from online php code, I'm getting undefined error
The website i'm retrieving from is https://www.orba.com.ng/getemployees.php
I'm using jQuery
localStorage['serviceURL'] = "https://www.orba.com.ng/";
var serviceURL = localStorage['serviceURL'];
var scroll = new iScroll('wrapper', { vScrollbar: false, hScrollbar:false, hScroll: false });
var employees;
$(window).load(function() {
setTimeout(getEmployeeList, 100);
});
function getEmployeeList() {
$('#busy').show();
$.getJSON(serviceURL + 'getemployees.php', function(data) {
$('#busy').hide();
$('#employeeList li').remove();
employees = JSON.parse(data.items);
$.each(employees, function(index, employee) {
$('#employeeList').append('<li><a href="employeedetails.html?id=' + employee.id + '">' +
'<img src="img/' + employee.picture + '" class="list-icon"/>' +
'<p class="line1">' + employee.firstName + ' ' + employee.lastName + '</p>' +
'<p class="line2">' + employee.title + '</p>' +
'<span class="bubble">' + employee.reportCount + '</span></a></li>');
});
setTimeout(function(){
scroll.refresh();
});
});
}
$(document).ajaxError(function(event, request, settings, thrownError) {
$('#busy').hide();
alert("Failed: " + thrownError.error);
});
I'm getting error code undefined
It was a CORS issue, Quite easy to fix. Search on google

How to get ajax value and store in PHP variable?

custom.js file:
$(document).ready(function() {
$("#company_name").keyup(function() {
$.ajax({
type: "POST",
url: "http://localhost/capms_v2/ca_autocomplete/getcompanyName",
data: {
keyword: $("#company_name").val()
},
dataType: "json",
success: function(data) {
//alert(data);
if (data.length > 0) {
$('#DropdownCompany').empty();
$('#company_name').attr("data-toggle", "dropdown");
$('#DropdownCompany').dropdown('toggle');
} else if (data.length == 0) {
$('#company_name').attr("data-toggle", "");
}
$.each(data, function(key, value) {
if (data.length >= 0)
$('#DropdownCompany').append('<li role="displayCountries" ><a role="menuitem DropdownCompany" id=' + value['company_id'] + ' Address1=' + value['company_address1'] + ' Address2=' + value['company_address2'] + ' city=' + value['company_city'] + ' state=' + value['company_state'] + ' pincode=' + value['company_zip'] + ' class="dropdownlivalue">' +
value['company_name'] + '</a></li>');
});
}
});
});
$('ul.txtcountry').on('click', 'li a', function() {
$('#company_name').val($(this).text());
$('#company_id').val($(this).attr("id"));
// $('#company_address1').val($(this).text());
$('#tableCityID').html($(this).attr("id"));
$('#tableCityName').html($(this).text());
$('#Address1').html($(this).attr("Address1"));
$('#Address2').html($(this).attr("Address2"));
$('#city').html($(this).attr("city"));
$('#state').html($(this).attr("state"));
$('#pincode').html($(this).attr("pincode"));
});
});
I was getting id in span id="tableCityID" but if I store the value and pass the value to mysql it was not fetching the value
$com = '<span id="tableCityID">';
and if I echo the select query
echo $sql="select * from ca_job WHERE job_status!='Closed' AND job_customer_name = '".$com."'";
I get the result with not completed single codes
select * from ca_job WHERE job_status!='Closed' AND job_customer_name = '15
If anybody faces this problem, please help me. Thanks in advance.
just use the </span>
like this
$com = '<span id="tableCityID"></span>';

Display new row inserted after ajax callback

Here there is my code which insert a row in ajax, it's working perfectly.
I need to display the new row that the user inserted inside my select multiple without reload the page but i don't know how to do ..
Thank you for you help
Ajax call :
$('#insertForm').on('click', function(){
var form_user = $('input[name=form_user]').val();
var form_intitule = $('input[name=form_intitule]').val();
var form_organisme = $('input[name=form_organisme]').val();
var form_date = $('input[name=form_date]').val();
var form_benefice = $('textarea[name=form_benefice]').val();
var form_dispositif = $('#form_dispositif').val();
var form_entpro_ActionAutre = $('input[name=entpro_ActionAutre]').val();
$.ajax({
type: "GET",
url: "lib/function.php?insertForm="+insertForm+"&form_user="+form_user+"&form_intitule="+form_intitule+"&form_organisme="+form_organisme+"&form_date="+form_date+"&form_benefice="+form_benefice+"&form_dispositif="+form_dispositif+"&form_entpro_ActionAutre="+form_entpro_ActionAutre,
dataType : "html",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + '--' + textStatus + '--' + errorThrown);
},
success:function(data){
}
});
});
My select multiple in function.php :
$displayFormation = $bdd->prepare('SELECT * FROM FORMATION WHERE form_id_user = :idSalarie ORDER BY form_date DESC');
$displayFormation->bindParam(':idSalarie', $_POST['idSalarie']);
$displayFormation->execute();
$data['formation'] .='
<div class="form-group">
<label for="nomSalarie" class="col-sm-1 control-label" id="nameSelect">Formations</label>
<div class="col-sm-11">
<select name="listeFormation[]" id="listeFormation" class="form-control" multiple>';
while($ligne = $displayFormation->fetch()){
$data['formation'] .='<option value="'. $ligne['form_id'].'">'.$ligne['form_intitule']. " [" . $ligne['form_organisme'] . "]". " [Année : " . dateAnglaisVersFrancaisAnnee($ligne['form_date']) . "]" . " [Bénéfices : " . $ligne['form_benefice'] . "]" . " [Dispositif : " . $ligne['form_dispositif'] . "]".'</option>';
}
$data['formation'] .='
</select>
</div>
</div>';
I am going to make some guesses and also some suggestions. Without knowing what your resulting data is going to be, it's hard to answer fully.
My working example and tests: https://jsfiddle.net/Twisty/053q24dh/
Here is the JQuery I would advise:
$('#insertForm').on('click', function() {
var form_user = $('input[name=form_user]').val();
var form_intitule = $('input[name=form_intitule]').val();
var form_organisme = $('input[name=form_organisme]').val();
var form_date = $('input[name=form_date]').val();
var form_benefice = $('textarea[name=form_benefice]').val();
var form_dispositif = $('#form_dispositif').val();
var form_entpro_ActionAutre = $('input[name=entpro_ActionAutre]').val();
$.ajax({
type: "GET",
url: "lib/function.php",
data: {
"insertForm": insertForm,
"form_user": form_user,
"form_intitule": form_intitule,
"form_organisme": form_organisme,
"form_date": form_date,
"form_benefice": form_benefice,
"form_dispositif": form_dispositif,
"form_entpro_ActionAutre": form_entpro_ActionAutre,
},
dataType: "html",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + '--' + textStatus + '--' + errorThrown);
},
success: function(data) {
// Asumming the page returns the following HTML, or something similar:
// <option value="9">Title [Organize] [Année : 02/02/16] [Bénéfices : 1] [Dispositif : 1]</option>
$("#listeFormation").append(data);
}
});
});
Again, this assumes that the HTML that is being returned to data is a single option tag to be appended to the select object. It looks like your PHP in the Post is looking for POST and your ajax is making a GET, so I am assuming they are different PHP Scripts. If they are not, you need to make sure the PHP knows how to respond properly and is not sending back too much data.
Also, I noticed that insertForm is not defined in this code snippet. If it's defined globally, that's fine, otherwise you need to define it within the scope of this function.

AJAX Post - One variable is not being sent properly

I have four variables I'm trying to pass via AJAX to be processed by some PHP on the same page: newJudgeName, newJudgeSection, newJudgeStatus, and originalJudgeName. The success function echos them out and they're the correct values, it's just the newJudgeStatus variable is not being picked up by my PHP. I've switched newJudgeStatus with newJudgeName in the data line on the AJAX request and then the value is sent just fine (I can see it in the db under Judge Name)... it's only when it's in the original spot in the ajax request that it doesn't work. I'm completely new to Ajax. Any help would be much appreciated.
AJAX:
$.ajax({
type: "POST",
url: "test.php",
data: 'newJudgeName=' + newJudgeName + '&newJudgeSection=' + newJudgeSection + '&newJudgeStatus =' + newJudgeStatus + '&originalJudgeName=' + originalJudgeName,
success: function(){
alert('newJudgeName=' + newJudgeName + '&newJudgeSection=' + newJudgeSection + '&newJudgeStatus =' + newJudgeStatus +'&originalJudgeName=' + originalJudgeName);
}
});
PHP:
if(isset($_POST['newJudgeName'])){
$newJudgeName = $_POST['newJudgeName'];
$newJudgeSection = $_POST['newJudgeSection'];
$newJudgeStatus = $_POST['newJudgeStatus'];
$originalJudgeName = $_POST['originalJudgeName'];
$judgeID = judgeNametoID($originalJudgeName);
$con = mysql_connect("-","-","-");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else {
// connected to database successfully
}
mysql_select_db("cm", $con);
$query = ("UPDATE `casemanagers`.`judges` SET `Name`='$newJudgeName' , `Section`='$newJudgeSection', `Active`='$newJudgeStatus' WHERE `judgeID`='$judgeID';");
$result = mysql_query($query);
mysql_close($con);
}
You have an errant space in your data string:
'&newJudgeStatus =' + newJudgeStatus +
---------------^^^^
// Should be
'&newJudgeStatus=' + newJudgeStatus +
You should send the data this way:
$.ajax({
type: "POST",
url: "test.php",
data: {
'newJudgeName' : newJudgeName,
'newJudgeSection' : newJudgeSection,
'newJudgeStatus' : newJudgeStatus,
'originalJudgeName' : originalJudgeName
},
success: function(){
alert('newJudgeName=' + newJudgeName + '&newJudgeSection=' + newJudgeSection + '&newJudgeStatus =' + newJudgeStatus +'&originalJudgeName=' + originalJudgeName);
}
});
Instead of manual processing, I'll recommend to put all these inside a form & use following code to send data:
$('#id_of_the_form').serialize();
instead of buggy:
newJudgeName=' + newJudgeName + '&newJudgeSection=' + newJudgeSection + '&newJudgeStatus =' + newJudgeStatus +'&originalJudgeName=' + originalJudgeName ...
See http://api.jquery.com/serialize/

Categories