I'm having trouble parsing response from $.ajax - json

I'm trying to modify some old code of mine to include comments for photos. The photos are acquired using $.ajax and the response is in html.
My modification is to get the comments as a json object and then parse the previously attained html inserting the comments where appropriate. Here is the [latest incarnation] of my code (I've tried many different alternatives)
$.ajax({
type:"POST",
url:"<?php echo $_SERVER['PHP_SELF']; ?>",
data:"ajax_loadbigthumbs=true&section=<?php echo $_GET['section']; ?>",
dataType : "html",
success: function(html){
jhtml = $(html);
$.getJSON( "/commentsjson.php?getcomments=true&section=<?php echo $_GET['section']; ?>", function( data ) {
$.each(data,function(i,item){
//alert(item.comment); <--- this works so I know the data is coming back correctly
console.log(jhtml.find('#comments_' + item.photoid).attr("id")); // this shows 'undefined'
jhtml.find('#comments_' + item.photoid).css("display","block").html("<p>" + item.name + " said " + item.comment + "</p>");
});
$("#largethumbscontainer").append(jhtml);
});
}
});
But this isn't working. The console.log line (as a test) returns 'undefined' and the following line (jhtml.find) has not found anything to modify.

var $comment = $('#comments_' + item.photoid, jhtml);
if ($comment.length)
$comment.css("display","block").html("<p>" + item.name + " said " + item.comment + "</p>");

I fixed it, buy appending the html to an already existing element, and then appending the comments to that element....
$.ajax({
type:"POST",
url:"<?php
echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8");
?>",
data:"ajax_loadbigthumbs=true&section=<?php echo $_GET['section']; ?>",
dataType : "html",
success: function(html){
jhtml = $(html);
$("#largethumbscontainer").append(jhtml);
largethumbs = $("#largethumbscontainer");
$.getJSON( "/commentsjson.php?getcomments=true&section=<?php
echo $_GET['section'];
?>", function( data ) {
$.each(data,function(i,item){
largethumbs
.find('#comments_' + item.photoid)
.css('display','block')
.append('<p>' +
item.name +
' said: <span style="font-style:italic;">' +
item.comment +
'</span></p>');
});
});
}
});

Related

How to use POST in ajax

I created a page where after loading the data will appear. I am using github url and ajax POST. But the data is not showing. What should I fix from the code that I have made?
<div id="content">
</div>
window.onload = function(){
$.ajax({
type: 'POST',
url: 'https://raw.githubusercontent.com/bimobaskoro/hewan/main/kucing.json',
dataType: 'application/json',
sucess: function (data) {
html = '<div class="content" id="content"></div>'
html += '<h1>' + data.judul + '</h1>'
html += '<p>' + data.isi + '</p>'
html += '</div>'
document.getElementById('content').innerHTML += html;
},
error: function() {
}
});
}
Consider the following.
$(function(){
$.getJSON("https://raw.githubusercontent.com/bimobaskoro/hewan/main/kucing.json", function (data) {
var html = $("<div>", {
class: "content"
});
$("<h1>").html(data.judul).appendTo(html);
$("<p>").html(data.isi).appendTo(html);
$("#content").append(html);
});
}
As GitHub is not apart of the same domain, you may encounter CORS issues. If so, you might consider JSONP.
Why would you use post to a json file. Get method is enough.
$.ajax({
url: 'https://raw.githubusercontent.com/bimobaskoro/hewan/main/kucing.json',
success: function (data)
{
var html = '<div class="content" id="content">';
var obj=JSON.parse(data);
obj.forEach((e)=>{
html += '<h1>' + e.judul + '</h1>'
html += '<p>' + e.isi + '</p>'
});
html += '</div>'
document.getElementById('content').innerHTML = html;
}
});

Pass parameter to href of a table cell in ajax

I'm new to use ASP.net for web app programming. I'm using the following ajax function aiming to send a parameter to the controller with the name of yyy. However, no matter how I manipulate the variable {id} in this case, the controller either get the string {id} or null. The variable of {id} is actually storing an integer value, for example, 3. I want to pass the integer 3 to the controller. Please help! Thanks!
$.ajax({
type: "GET",
url: "http://localhost:8086/xxx",
crossDomain: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var testData = '';
$.each(data, function (key, value) {
testData += '<tr>';
var id = value.testDataID.toString();
testData += '<td style="cursor:pointer">' + '<a href="http://localhost:8087/xxx/yyy?param="+{id}>' + value.serialNumber + '</a>' + '</td>';
testData += '<td>' + value.testDataID + '</td>';
testData += '<td>' + value.sN + '</td>';
testData += '</tr>';
});
$('#testDataTable').append(testData);
}
});

using AJAX to call one query from a PHP file which has multiple

I would like to use AJAX to call a single query in a php file which has multiple but I'm not entirely sure how to go about doing this.
In essence the php file will have three PDO queries which will be update, delete and add. Currently it just has the update query.
How would i add a second query to the file and get AJAX to call particular query?
The AJAX code:
function updateCall() {
var data = $('#updateForm').serialize();
$.post('ManageCourses_DeleteSubmit.php', data, function(response){
$("#updateForm").html(response);
//'soft'reload parent page, after a delay to show message
setTimeout(function(){
$('#editModal').modal('hide')
location.reload();
},2000);
}).fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
the php file:
<?php
include "db_conx.php";
try
{
$db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $db_conx->prepare("UPDATE course_details SET course_title = :course_title
WHERE course_code = :course_code");
$course_title = $_POST['course_title'];
$course_code = $_POST['course_code'];
$sql->bindParam(':course_title', $course_title, PDO::PARAM_STR);
$sql->bindParam(':course_code', $course_code, PDO::PARAM_STR);
/*** execute the prepared statement ***/
$sql->execute();
/*** success message ***/
$message = "<p class='text-success'> Record Successfully Updated <span class='glyphicon glyphicon-ok'/></p>";
}
catch(Exception $e)
{
$message = 'Message: ' .$e->getMessage();
}
die($message);
?>
Any examples?
Thanks!
The $.ajax() code block looks like this:
$.ajax({
type: "POST",
url: "receiving_file.php",
data: 'selected_opt=' + opt + '&something_else=' +someelse+'&more_stuff='+more_stuff,
success:function(data){
alert('This was sent back: ' + data);
}
});
Note the data: line
Just use another variable to identify which PHP routine you will call. Something like:
data: 'myrequest=add&selected_opt=' + opt + '&something_else=' +someelse+'&more_stuff='+more_stuff,
versus
data: 'myrequest=delete&selected_opt=' + opt + '&something_else=' +someelse+'&more_stuff='+more_stuff,
Then, in your PHP file, test for that variable:
<?php
$req = $_POST['myrequest'];
if ($req == 'add'){
//do the add
}else if ($req == 'delete'){
//etc
}
Alternately, you can use a single $.ajax() code block, and use a variable to determine which PHP function to call:
if (useraction=='add') {
myreq = 'add';
}else if(useraction=='del') {
myreq = 'delete';
}
//later on in the code...
$.ajax({
type: "POST",
url: "receiving_file.php",
data: 'myrequest=' +myreq+ '&selected_opt=' + opt + '&something_else=' +someelse+'&more_stuff='+more_stuff,
success:function(data){
alert('This was sent back: ' + data);
}
});

Looping through AJAX result and post to HTML,

I have the following AJAX code for processing a returned results from the database,
$.ajax({
type: 'POST',
async: true,
url: "../../../avocado/private/functions/measures.php",
data: {name:selectedValue},
success: function(data, status){
var selectedData = JSON.parse(data);
console.log(selectedData);
document.getElementById("measures").innerHTML = "<div id=\"measures\">"
+ "<table class=\"table table-condensed\">"
+ "<tr><th>desc1</th><td>"+selectedData[0][6]+"</td></tr>"
+ "<tr><th>desc2</th><td>"+selectedData[0][7]+"</td></tr>"
+ "<tr><th>desc3</th><td>"+selectedData[0][8]+"</td></tr>"
+ "<tr><th>desc4</th><td>"+selectedData[0][9]+"</td></tr>"
+ "</table>"
+ "</div>";
},
error: function(xhr, status, err) {
alert(status + ": " + err);
}
});
The data returned is a 2D array, like this below,
Array[5]
0: Array[14]
1: Array[14]
2: Array[14]
3: Array[14]
4: Array[14]
so what I want to do is to loop each array and display the inner information on the HTML page but I have no idea how I should go about doing it.. this code only returns the values stored on index[0].
Can I please get some help?
==============================================================================
UPDATED
So I tried to use Jquery.append() like the following below..
jQuery.each( selectedData, function( i, val ) {
$("measures").append(
"<table class=\"table table-condensed\">"
+ "<tr><th>desc1</th><td>"+selectedData[i][6]+"</td></tr>"
+ "<tr><th>desc2</th><td>"+selectedData[i][7]+"</td></tr>"
+ "<tr><th>desc3</th><td>"+selectedData[i][8]+"</td></tr>"
+ "<tr><th>desc4</th><td>"+selectedData[i][9]+"</td></tr>"
+ "</table>"
);
});
/*
document.getElementById("measures").innerHTML = "<div id=\"measures\">"
+ "<table class=\"table table-condensed\">"
+ "<tr><th>desc1</th><td>"+selectedData[0][6]+"</td></tr>"
+ "<tr><th>desc2</th><td>"+selectedData[0][7]+"</td></tr>"
+ "<tr><th>desc3</th><td>"+selectedData[0][8]+"</td></tr>"
+ "<tr><th>desc4</th><td>"+selectedData[0][9]+"</td></tr>"
+ "</table>"
+ "</div>";
*/
now..its not appending any values to the div #measures at all...
I have not tried the code. But I hope this will help you.
document.getElementById("measures").innerHTML = "<div id=\"measures\">";
$.each( selectedData, function( index, value ){
$.each( index, function( index2, value2 ){
$('#measures').append(value2);
});
});

How to show Json data to the dialog box in html

I am a beginner in the ajax, dom, jsonm etc in web application. my project is to use jquery UI to parse json data and show all of data from database and retrive one data by id, it's part of create, retrieve, update, and delete. so retrieving is key function here. I can get all data and populate datatable with all data no problem.
"aoColumns" :[
{"mData" : "image"},
{"mData" : "name"},
{"mData" : "type"},
{"mData" : "description"},
{"mData" : "price"},
{"mData" : "id",
"mRender" : function(data, type,full)
{return '<a href="#" id="'+ full.id +
'" class="id">Details</a>'; }
}
-->to fetch all the data
var findById= function(id) {
console.log('findById: ' + id);
$.ajax({
type:'GET',
url: rootUrl + '/' + id,
dataType: "json",
success: renderList
});
};
var renderList = function(data){
var list = data == null?[] : (data instanceof Array ? data : [ data ]);
///////////////////////////////////
solution1//////////////////////////////////////////////////
$.each(list, function(index, pet){
var row="<tr>" + "<td>" + pet.type + "</td>"
+ "<td>" + pet.price + "</td>"
+ "<td>" + pet.contact_no+ "</td>"
+ "<td> "+ pet.contact + "</td>"
+ "</tr>";
//$(tblRow).appendTo("#entrydata tbody");
$(row).appendTo('dialogTable tbody');
});
to retrieve more details
the result(in xml) show this if I click the "details " link by checking element,
<pet>
<contact>bob.hoskins#lgfriday.com</contact>
<contact_no>5-(254)756-8567</contact_no>
<description>Great companion for up to 75 years</description>
<id>42</id>
<image>bird</image>
<name>Amazon</name>
<price>40</price>
<type>BIRDS</type>
</pet>
(failed)
net::ERR_CONNECTION_REFUSED
the data is coming back in MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML so I can check data type easily but cant make connection to it to show in dialog box
<div id="dialog" title="More Information">
<table id="dialogTable" style="width: 350px;">
<thead>
<tr id="findById">
<th>Type</th>
<th>Price</th>
<th>Contact</th>
<th>Email</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
I resolved the problem. I had set var rooturl = http://localhost/xxx/rest/xxx"; instead of rooturl = "http://localhost:8080/xxx/rest/xxx" . It solved the cross origin connection and connection failure problem and now it renders.