Apologies if this has been answered before but I couldn't find what I was looking for. So, I use $.getJSON to send some variables to a php file. The file returns success as true but for some reason always triggers the .fail function.
The weird thing is, it all works fine on my laptop, just not on the computer at university. Connection to the database is fine, like I said everything works and it returns all the correct data but doesn't trigger the success function.
JQuery:
function request_user_review() {
$.getJSON("user_review_list.php", success_user_review).fail(fail_user_review);
}
function success_user_review(response) {
if (response.success) {
var user_review_list = "";
$("#user_reviews .review_cafe").remove();
$("#user_reviews .review").remove();
$("#user_reviews .rating").remove();
$("#user_reviews .review_choice").remove();
for (var i = 0; i < response.rows.length; i++) {
var review_cafe = '<tr id="row_' + response.rows[i].id + '"><td class="review_cafe">'
+ response.rows[i].cafe + '</td>';
var review = '<td class="review">'
+ response.rows[i].review + '</br>Review left: ' + response.rows[i].date + '</td>';
var rating = '<td class="rating">'
+ response.rows[i].rating + '/5</td>';
var review_choice = '<input type="hidden" class="cafe_id" value="' + response.rows[i].cafe_id + '" /><td class="review_choice"><button onclick="request_edit(this.id)" id="edit_' + response.rows[i].id + '" class="btn_edit">Edit</button><button onclick="request_delete_review(this.id)" id="delete_' + response.rows[i].id + '" class="btn_delete">Delete</button></td></tr>';
user_review_list += review_cafe + review + rating + review_choice;
}
$("#user_reviews").html(user_review_list).trigger("create").trigger("refresh");
} else {
$("#review_message").html("Review failed to be loaded!").trigger("create").trigger("refresh");
}
}
function fail_user_review() {
$("#review_message").html("Connection down?").trigger("create").trigger("refresh");
}
PHP:
<?php //user_review_list.php
require_once "sql.php"; //connection to database and query is handled here
require_once "logged_in.php";
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors','On');
$session_id = $_SESSION['userid'][0];
$result = array();
$result['success'] = false;
$query = "SELECT * FROM reviews WHERE user = $session_id;";
if ($result_set = Sql::query($query)) {
$result['success'] = true;
$result['message'] = "Your Reviews" ;
$rows = mysqli_num_rows($result_set);
$result['rows'] = array();
for ($i = 0; $i<$rows; $i++) {
$tmpRow = mysqli_fetch_assoc($result_set);
$php_date = strtotime($tmpRow['date']);
$formatted_php_date = date('M d, Y', $php_date );
$tmpRow['date'] = $formatted_php_date;
$result['rows'][$i] = $tmpRow;
}
} else {
$result['message'] = "Failed to read Reviews" ;
}
print(json_encode($result));
Thanks
James
The messages you get mean you're trying to parse something that's already JSON. My earlier statement about parsing JSON is not going to be of much help here because you're not just getting back a string that needs to be converted to JSON -- which you really shouldn't be with $.getJSON().
You're getting back a JSON with an invalid encoding somewhere along the line, so trying to parse it won't help you. Validate your JSON first and foremost (the error could be due to your differing server settings between machines) using jsonlint, and continue from there.
Related
I'm selecting values from my db in mysql and comparing them with values from JSON. I'm receiving the right results but since I'm using append the results shows up one by one, which looks like animation I would like to get them all at once and show some kind of loading icon while the loop is running, I've tried few different ways but nothing worked.
<?php $sql= "select a_id,b_id,res_a,res_b from betts_gr where u_id='".$u_id[0]."'";
$user_bets = mysqli_query($conn,$sql);
while($user_bets1 = mysqli_fetch_array($user_bets)){
?>
<script>
$(document).ready(function() {
var a_id = "<?php echo $user_bets1[0]?>";
.....
var car = [];
$.getJSON('http://api.football-api.com/2.0/matches?
comp_id = 1204 & from_date = '+today+' & to_date = '+plusmonth+' & Authorization ',
function(data) {
var html = "";
console.log(data);
$.each(data, function(index, value) {
var teama = value.localteam_name;
var teamb = value.visitorteam_name;
.......
function add(name, point) {
car.push({
teamb: teamb,
teama: teama,
form: form,
data: data,
teama_id: teama_id,
teamb_id: teamb_id,
a_res: a_res,
b_res: b_res
});
}
add(teama, teamb, data, form, teama_id, teamb_id, a_res, b_res);
});
for (var n = 0; n < car.length; n++) {
if (car[n].teama_id == a_id && car[n].teamb_id == b_id) {
html += "<tr><td><input type='hidden' name='aid" + n + "'
value = '"+car[n].teama_id+"' > < input type = 'hidden'
name = 'bid"+n+"'
value = '"+car[n].teamb_id+"' > " +
car[n].data +
"</td><td> " + car[n].teama + "</td><td>" + car[n].a_res + "-" +
car[n].b_res + "</td><td> " +
car[n].teamb + '</td><td> you predicted ->' + pred_resa + ' - ' + pred_resb +
'</tr>';
}
}
$(".message").append(html);
});
});
</script>
<?php } ?>
the example for using the Array.map and the template literals instead of the for loop and the plain string concat:
const isTargetTeam = item => item.teama_id == a_id && item.teamb_id == b_id;
const html = car.slice(0) // copy the array car
.filter(isTargetTeam)
.map((item, index) =>
`<tr>
<td>
<input type='hidden' name='aid${index}' value='${item.teama_id}'>
<input type='hidden' name='bid${index}' value='${item.teamb_id}'>
${item.data}
</td>
<td>
${item.a_res}-${item.b_res}
</td>
<td>
${item.teamb}
</td>
<td> you predicted -> ${pred_resa} - ${pred_resb}
</tr>`
).join('')
You should not mix PHP and Javascript like that. Currently this will result in X document.ready functions with X getJSON requests.
If you want to do the API requests from the local client, you should do ONE javascript function where you pass in the selected user_bets as an array. There are different possibilities to determine if all loadings have been finished: either counting up and checking after every callback if the max number is reached, or using Promises and Promise.all().
<script>
var user_bets = <?php echo json_encode($user_bets);?>;
$(document).ready(function () {
Promise.all(user_bets.map(function (id) {
return fetchFromApi(id);
})).then(function(array){
var html = "";
for(var i = 0; i < array.length; i++){
html += processData(array[i]);
}
$(".message").append(html);
});
});
function fetchFromApi(user_id) {
return new Promise(function (resolve, reject) {
$.getJSON()
.done(function (data) {
resolve(data);
})
.fail(function (error) {
reject(error);
});
});
}
function processData(data){
var html = '';
// do your html processing of a single api call here
return html;
}
</script>
Alternatively you can use CURL to do the API requests server-side already.
Thanks for advise I just realize I should get data with one request. I've passed the whole array to js and since I'm not sure how promise.all is working I did two for loops nested and is working fine, the only thing I still can't figure out how to check if the loops are finished so I could add loading icon while loop is running.
function add(name, point) {
car.push({ teamb : teamb, teama : teama, form:form, data:data, teama_id:teama_id,
teamb_id:teamb_id, a_res:a_res, b_res:b_res});
}
add(teama,teamb,data,form,teama_id,teamb_id,a_res,b_res);
});
for(var n=0;n<car.length;n++){
var taba = [<?php echo json_encode($at1)?>];
var tchild = taba[0];
for(var u=0;u<tchild.length;u++){
if(car[n].teama_id == tchild[u].localteam_id
&& car[n].teamb_id == tchild[u].visitorteam_id){
html += "<tr><td><input type='hidden' name='aid"+n+"'
value='"+car[n].teama_id+"'>
<input type='hidden' name='bid"+n+"'
value='"+car[n].teamb_id+"'>"
+car[n].data
+"</td><td> "+car[n].teama + "</td><td>"+ car[n].a_res
+ "-"+ car[n].b_res + "</td><td> "
+ car[n].teamb + '</td><td> you predicted -
>'+tchild[u].localteam_score +' - '+tchild[u].visitorteam_score +
'</td></tr>';
}
}
}
$(".message").append(html);
I have to append data one by one by clicking button
$(document).ready(function() {
var i = 0;
$("#add_row").click(function() {
$('#addr' + i).html("<td>" + (i + 1) + "</td><td><select id='myselect" + i + "' name='job_id[]" + i + "' class='form-control'><option value=''>Select the Job</option><?php
$mysql = "select * from ca_job where job_status != 'Closed' and job_customer_name = '".$com_id.
"'"; $result1 = mysql_query($mysql) or die(mysql_error());
while ($roww = mysql_fetch_array($result1)) {
$sql = "select * from `ca_job_type` where `jtype_id`= '".$roww['job_type'].
"'";
$res = mysql_query($sql) or die(mysql_error());
$row1 = mysql_fetch_array($res);
echo '<option value='.$roww['job_id'].
' selected>'.$roww['job_id'].
'-'.$row1['job_type_name'].
'</option>';
} ? > < /select></td > < td > < input name = 'invoice_description[]"+i+"'
type = 'text'
placeholder = 'invoice_description'
class = 'form-control input-md'
id = 'invoice_description' / > < /td><td><input name='sac_hsc_code[]"+i+"' type='text' placeholder='sac_hsc_code' class='form-control input-md'id='sac_hsc_code' / > < /td><td><select id='employee' name='tax_id[]"+i+"' class='form-control'><option value=''>Please select</option > <?php
$sql = "select tax_id, tax_type, tax_comp, tax_Percent FROM ca_taxmaster where tax_comp = '0'";
$resultset = mysql_query($sql) or die(mysql_error());
while($rows = mysql_fetch_array($resultset)) { echo '<option value='.$rows['tax_id'].' selected>'.$rows['tax_type'].'</option>'; } ?> < /select></td > < td > < input name = 'amount[]"+i+"'
type = 'text'
placeholder = 'amount'
class = 'form-control input-md' / > < /td>"
);
Above source which I have posted was multiple input type up to that working but after selecting drop-down of id='myselect' for first list it was showing the values if press (+) button above value get cleared and showing last data alone but I need the values of first row and second row.
$(document).ready(function() {
$('#myselect' + i).change(function() {
var job_id = $(this).find(":selected").val();
var dataString = 'job_id=' + job_id;
$.ajax({
url: '<?=base_url(); ?>ajax/getjob.php',
dataType: "json",
data: dataString,
cache: false,
success: function(employeeData) {
$('.appendData').empty();
if (employeeData) {
$("#dvPassport").show();
$("#dvPassport1").hide();
var myselect = [employeeData];
employeeData.forEach(function(item) {
var data = '<tr>';
data += '<td>' + item.job_id + '</td>';
data += '<td>' + item.disburse_Date + '</td>';
data += '<td align="right">' + item.approved_amount + '</td>';
data += '</tr>';
$('.appendData').append(data);
});
} else {
$("#dvPassport").hide();
$("#dvPassport1").show();
} //else
}
});
});
});
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
});
$("#delete_row").click(function() {
if (i > 1) {
$("#addr" + (i - 1)).html('');
i--;
}
});
});
Please click here to get clear view
In the above picture if I have selected dropdown two values showing and I am pressing the + button and selecting second drop-down first values getting cleared and showing second value what I have selected in the last dropdown. but I need the values of the first drop-down and second drop down.Please help me if anyone faces this problem .Thanks in advance.
i am not quit sure what you are trying to achieve but you forgot some ticks in for the value in the dropdowns, which might solve your problem
change
echo '<option value='.$roww['job_id'].' selected>'.$roww['job_id'].
to
echo '<option value="'.$roww['job_id'].'" selected>'.$roww['job_id'].
and
echo '<option value='.$rows['tax_id'].' selected>'.$rows['tax_type'].'</option>';
to
echo '<option value="'.$rows['tax_id'].'" selected>'.$rows['tax_type'].'</option>';
beside that
you should really consider formating your code well, it is very hard to read and understand and therefore very hard to debug
try to divorce your source, try to not mix php, html and javascript. it is possible to use it that way, but it also is a huge error source and very hard to maintain
use the mysqli functions instead of mysql -> MySQL Improved Extension
I am having problems displaying the names of golf courses in my dropdown menu. I have a PHP script that when ran, returns the names of the courses in my database. The problem is that when I apply this to my index.html dropdown page and display it in the browser, the content is not displaying the dropdown.
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT name FROM courses";
$result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));;
$courses = array();
while ($row = mysqli_fetch_array($result))
{
array_push($courses, $row["name"]);
}
echo json_encode($courses);
?>
The above code successfully generates the data from the database
$(document).ready(function () {
$.getJSON("getCourseDD.php", success = function(data){
var options = "";
for(var i=0; i< data.length; i++){
options += '<option value ="' + data[i] + '">' + '</option>';
}
$("#selectCourse").append(options);
});
});
The above code is not populating the course names into the dropdown menu.
The id of my dropdown menu is selectCourse.
<form> <select id="selectCourse" </select> </form>
Thanks for any help in advance.
You need to put text in options as below :
var dummyData = ['English','Spanish','French','Mandarin'];
$(document).ready(function () {
var data = dummyData, //This data comes from the ajax callback
courseOptions = "";
for(var i=0; i< data.length; i++){
courseOptions += '<option value ="' + data[i] + '">'+data[i]+'</option>';
}
$("#selectCourse").append(courseOptions);
});
Working Demo : jsFiddle
Currently you are not setting text of option also, use
options += '<option value ="' + data[i] + '">' + data[i] + '</option>'
instead of
options += '<option value ="' + data[i] + '">' + '</option>';
As you're currently utilizing jQuery, you may want to go for this solution:
for(var i=0; i< data.length; i++)
{
$("#selectCourse").append(
$('<option>').text(data[i]).val(data[i])
);
}
Use .html(options); in place of .append(options); .
append() add data after tag but html() insert data between tag.
and you should also assign something between tag, like
options += '<option value ="' + data[i] + '">' + data[i] + '</option>'
First log your data like console.log(data) and check in browser firebug console whether it outputs json string or object. If it's string you need to convert it into object using JSON.parse().
I'm attempting to call a PHP file and have it return a result (a single record's 'pageLocation') from a database table ('page'). I then want to get that result into a variable, so I can use it while creating an image in html.
Currently, the image is being created but the source is not feeding into it, leaving a default empty image at the correct size.
Javascript:
// Loads a list of comics created by the user from the database.
function loadComic()
{
var xmlhttp = new XMLHttpRequest();
var getID = '<?php echo $_SESSION["userID"]; ?>';
var url = "loadCom.php?userID="+getID;
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
loadComicJSON(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
// JSON parsing for 'loadComic'.
function loadComicJSON(response)
{
var arr = JSON.parse(response);
var i;
var out = "";
document.getElementById("loadList").innerHTML="";
if (arr.length == 0)
{
//Non-relevant code affecting layout if no comics are found.
}
else
{
out+="<br>";
for(i = 0; i < arr.length; i++)
{
// Gets image source from database.
imgSrc = "";
tempID = arr[i].comicID;
$.post("getCover.php", {'comicID':tempID}, function(result)
{
imgSrc += ("" + result);
}
);
// Creates image item and associated radio button.
out += "<hr><br><img name = '" + ('com' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='" + imgSrc + "'><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br>";
}
}
}
</script>
PHP (getCover.php):
<?php
if (isset($_POST["comicID"]))
{
include_once('includes/conn.inc.php');
$checkID = $_POST["comicID"];
$query = ("SELECT FIRST (pageLocation) FROM page WHERE comicID = '$checkID' ORDER BY pageNum");
$result = mysqli_query($conn, $query);
$conn->close();
echo ($result);
}
else
{
$checkID = null;
echo "Error. No comic found.";
}
?>
Thanks for any help provided.
You need to get he data from the result, like:
$row = $result->fetch_assoc()
Also, yes, Jim G is right, you need to escape that POST variable.
Hi I'm trying to get the xml data from php to javascript using DOM document and it keeps giving me : XML or text declaration not at start of entity error.(on firebug)
I tried saving it to a real xml file and it outputs a well formatted xml.
I guess the reason for this is white space on top of the xml file. I tried using ob_start(); and ob_end_flush(); but couldn't get that working
BTW I'm new to Ajax!
JS script
var xh = createRequest();
var xhrObject = false;
if (window.XMLHttpRequest)
{
xHRObject = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xHRObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function getData()
{
if ((xh.readyState == 4) &&(xh.status == 200))
{
alert("hi");
var serverResponse = xh.responseXML;
var header = serverResponse.getElementsByTagName("good");
var spantag = document.getElementById("sp");
var x;
spantag.innerHTML = "";
x = "<table cellpadding='1' cellspacing='6' border='0'>";
x += "<tr><td>ID</td><td>price</td><td>quantity</td><td>Total</td><td>Remove</td></tr>";
for (i=0; i<header.length; i++)
{
var id = header[i].getElementsByTagName("ID")[0].childNodes[0].nodeValue;
var price = header[i].getElementsByTagName("price")[0].childNodes[0].nodeValue;
var qty = header[i].getElementsByTagName("quantity")[0].childNodes[0].nodeValue;
var total = header[i].getElementsByTagName("total")[0].childNodes[0].nodeValue;
if(qty=="0")
{
continue;
}
x += "<tr>"
+ "<td>" + id + "</td>"
+ "<td>" + price + "</td>"
+ "<td>" + qty + "</td>"
+ "<td>" + total + "</td>"
+ "<td>" + "<a href='#' onclick='AddRemoveItem(\"Remove\","+id+");'>Remove Item</a>" + "</td>"
+ "</tr>";
}
x += "</table>";
if (header.length != 0)
spantag.innerHTML = x;
}
}
PHP code
function toXml($shop_goods)
{
$doc = new DomDocument();
$goods = $doc->createElement('goods');
$goods = $doc->appendChild($goods);
foreach ($shop_goods as $Item => $ItemName)
{
$good = $doc->createElement('good');
$good = $goods->appendChild($good);
$title = $doc->createElement('ID');
$title = $good->appendChild($title);
$value = $doc->createTextNode($Item);
$value = $title->appendChild($value);
$price = $doc->createElement('price');
$price = $good->appendChild($price);
$value3 = $doc->createTextNode($ItemName["price"]);
$value3 = $price->appendChild($value3);
$quantity = $doc->createElement('quantity');
$quantity = $good->appendChild($quantity);
$value2 = $doc->createTextNode($ItemName["qty"]);
$value2 = $quantity->appendChild($value2);
$total = $doc->createElement('total');
$total = $good->appendChild($total);
$value3 = $doc->createTextNode($ItemName["total"]);
$value3 = $total->appendChild($value3);
}
$strXml = $doc->saveXML();
//echo("<br>----- DATA RECOREDED!!! ----");
return $strXml;
}
As others have noted, this could be an encoding issue.
Check your code for the Xml byte order mark.
Check the document is returning the correct mime type.
Not sure of your constraints but have you considered serializing your data to Json format. It's much easier to work with in the browser.
Finally consider using a library like JQuery to handle your ajax requests, much easier for cross browser compatibility.