Inconsistent Loading JSON and binding to form fields - php

So I have a datagrid where when a row is clicked a form is loaded, then JSON data is pulled and propagates form fields using JQuery. It works great...sometimes. It is very inconsistent, and I can't figure out why it doesn't work every time. I can click on a row, it loads, then (without refreshing) the next few times it might not, and then (still without refreshing) the next few random number of times it does.
Any help would be appreciated. The first thing the script does is load the corresponding form into the div #dlg, then pull the JSON data, and then parse and populate the fields.
function fw_getFormData(r_id, t_name, r_key){
$('#dlg').dialog('refresh', 'dg_process/dg_edit_form.php?table='+t_name),
jsonURL = 'form_data/dg_forms_data.php?table='+t_name+'&pkey='+r_key+'&id='+r_id;
var jqxhr = $.getJSON( jsonURL, function() {})
//JSON load is complete. Propagate form fields.
.done(function(data) {
$.each(data, function(index, obj) {
$.each(obj, function(key, value) {
//$('#'+key).attr("value", value);
$("#dlg").parents("div").find('input[name='+key.toLowerCase()+']').val(value);
}); //End inner parse of JSON
}); //End outer Parse
}) // End .done
//JSON Did not load
.fail(function() {
alert( "JSON could not load" );
}) // End .fail
});
The JSON it is parsing looks like this:
[{"staffID":"1","fname":"Bill","lname":"Smith","email_address":"bsmith#fakeemail.net","password":"testpw"}]
As a final note, the alert for .fail never fires when it doesn't work.

Related

How can I get information from MySQL with Ajax?

So i am trying to learn Ajax with jQuery, to retrieve some information. At the moment, I have problem to get the information. My code is very simple at the moment, just because I want to learn how it works. This is my HTML code.
<h2>Hello world</h2>
<p id="response"></p>
My jQuery code:
$(function(){
$('h2').on('click', function() {
$.ajax({
url: "ajax.php",
type: "get",
datatype: "json",
success: function(data){
$.each(data, function(i, key){
$("#response").html(key['name'])
});
},
error: function(data){
console.log("tjohejsan");
}
})
});
});
So when I click on h2 it should retrieve data. What I want is to make a call from my database to get information about the users.
So my php code looks like this:
$sql = "SELECT * FROM moment2";
$result = mysqli_query($db,$sql) or die("Fel vid SQL-fråga");
$array = array();
while($row = $result->fetch_assoc())
{
$array[] = $row;
}
echo json_encode($array);
At this point, this is where it fails. I don't know really where the problem is. Because I want an associative array.
I would appreciate it if you could assist me, because as I mentioned, I don't really know how to solve it from here.
Thanks in advance!
EDIT: I realised I had a typo while writing this. changing data['name'] to key['name']
You have issue in the jquery each function. Replace the success function as
success: function(data){
$.each(data, function(i, key){
$("#response").html(key['name'])
});
},
It is because jquery each function has key and value as argument, so only replace "data" by "key" in your this line: $("#response").html(data['name'])
There are a couple places that you are going to run into trouble with this. Here is a JSFiddle for you to reference with my tips below:
https://jsfiddle.net/MrProvolone/zgw9ymv3/2/
There are a few things to consider...
1). Your returned data needs to be converted using parseJSON(), which is a built in jQuery function. This will convert your JSON string into a JavaScript object.
2). When you are looping through your object, you need to include the number (i) that you are trying to access
3). Because we are making a new object variable, we don't need the "key" designator in your $.each() function call... so it becomes $.each(data, function(i){}); instead of $.each(data, function(i, key){});
3). When you are trying to write out your html, you must grab what is already in the container, then add your new html to it, and finally write it all back out to the container.
Here is a step by step:
Instead of:
success: function(data){
$.each(data, function(i, key){
$("#response").html(key['name'])
});
}
We need to add the parsing (and remove the "key" variable per #3 above) so it becomes this:
success: function(data){
var parsed = jQuery.parseJSON(data);
$.each(data, function(i){
$("#response").html(key['name']);
});
}
Now we have a new variable to work off of (parsed) so we need to change both the $.each line, and the .html() line to make sure it uses that new variable....
So this:
$.each(data, function(i, key){
$("#response").html(key['name']);
});
Becomes this:
$.each(parsed, function(i){
$("#response").html(parsed['name']);
});
But that still won't work. We are looping through the object, so when we try to access a value, we have to specify which element in the object we are trying to get to. So anywhere in your loop that looks like this:
parsed['keyname']
becomes this:
parsed[i]['keyname']
So now we have:
$.each(parsed, function(i){
$("#response").html(parsed[i]['name']);
});
At this point you should be getting some html in your container. However, you will notice that you are only getting the value of the last row of your data. That is because you are overwriting ALL of your html in the container in each loop, instead of adding to what is already there. We need to make a new variable to fix this. So this:
$.each(parsed, function(i){
$("#response").html(parsed[i]['name']);
});
Becomes this:
$.each(parsed, function(i){
var oldhtml = $("#response").html();
$("#response").html(oldhtml + '<br>' + parsed[i]['name']);
});
Now you will see each result, with a html line break between each one.
Hope this helps!
In your js, on the success callback, you are using the wrong data, and not appending the data retrieved to the html Tag
Here is an essai
success: function(data){
if(typeof data != "object"){
data = JSON.parse(data);
}
$.each(data, function(i, key){
$("#response").append(key['name'])
});
}

Auto update comment count inside ajax prepended div

What I'm trying to do is auto update a comment count on any prepended div that has been constructed by ajax. So basically replacing the ajaxed response div commentprint
success: function(data) {
$.each(data.posts, function(i, response) {
$("#homestatusid").prepend("<div id='commentprint"+response['streamitem_id']+"'>Comments "+response['num']+"</div>")[
}
});
I have a page called ajaxcommentcount.php. This is where the response would come from and replace commentprint. I just don't have any clue how to do it.
Okay I was able to send the data needed and retrived and updated the ajaxed div.
I added the following to the success
timer = setInterval(function() {
refreshCurrentTab(streamitem_id);
}, 5000); refreshCurrentTab(streamitem_id);
And then called the function in .load() passing the post id over to return and replace the div.
function refreshCurrentTab(streamitem_id)
{
$('#commentprint'+streamitem_id).load('ajaxcommentcount.php?var='+streamitem_id+'');
}

Update DOM with jQuery ajax array results

I have search results generated by a 3rd party script that I would like to add data to. I have parsed the results to get an array of id's, and queried the database for additional fields. The ajax success method receives the formatted array back, but now I'm stuck on how to get those results into the right place in the DOM.
The HTML:
<div class="ihf-results-property-info">
<div class="ihf-results-price">LIST: $2,150,000</div>
<div class="ihf-results-links"> 24 Photos
</div>
<div class="ihf-results-extra-info">
<div class="ihf-results-listingnum hidden-xs">Listing # 727938</div>
</div>
Repeat...
The last div I included in the example has the unique ID I'm using for the query. I'd like to use that to associate the ajax return with proper placement in the DOM. Here is my javascript:
jQuery(document).ready(function($) {
// grab the listings numbers so we can query the db for extra data
var listings = $('.ihf-results-listingnum').map(function() {
// grab just the digits
var listingNum = $(this).text().replace(/[^0-9]/g, '');
// add the listing number to the parent so we can target it later
$( this ).parents('.ihf-results-extra-info').parent().addClass('marketing-details-' + listingNum);
return listingNum;
// use .get to create an array of the listing numbers
}).get();
$.ajax({
type: "GET",
url: "custom/07-idx-queries.php",
data: 'mlsNums=' + listings, // looks like ?mlsNums=735383,727468,699876...
success: function(result) {
// this logic came from here: http://stackoverflow.com/questions/15311320/how-to-work-with-jquery-ajax-and-php-array-return
resultJson = $.parseJSON(result);
if (typeof resultJson == 'object') {
jsObject = eval(resultJson);
jsArray = [];
for(elem in jsObject){
jsArray.push(jsObject[elem]);
}
console.log(jsArray);
// this works as expected, except keys are 0 based
// This is where it all falls apart. I want to extract each object and stick it in the DOM in the correct place
jQuery.each(jsArray, function(key, value) {
$( this ).appendTo('.marketing-details-' + key);
});
}
else {
console.log("error occurred");
}
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
})
});
And the php I'm using produces the desired results from the db, with the exception that it is a numerical array. I think an associative array would work better when trying to put the results into the DOM, tha way I could use the ID's as the key and match them to the classes I added. Here is the relevant code from custom/07-idx-queries.php:
$mls_nums = explode(",",$_GET['mlsNums']);
// removed all of the conditionals to keep the question clean
$html = array();
foreach ($mls_nums as $mls_num) {
// just retreiving a single object from each row for now
$remarks = $mysqli->query("SELECT mr FROM listings WHERE ln = '$mls_num'")->fetch_object()->mr;
// format the data
$my_html = "<p class='marketing-remarks mlsnum-".$mls_num."'>$remarks</p>";
// build an array of the results - necessary?
array_push($html,$my_html);
}
// send the data back in a JSON string
echo json_encode($html);
So my goal is to query the db for up to 10 rows, and insert the results into an equal number of new divs that are children to a div with the same id number in its class. I greatly appreciate any help.
In your PHP do this:
$html[$mls_num] = $my_html;
// this isn't needed
// array_push($html,$my_html);
Now your returned data has a way to tie into the target div.
Not clear if you have control over the HTML in the first part of your example, but this would be one approach.
<div class="ihf-results-listingnum hidden-xs">Listing # 727938</div>
<div class="remarks" id="remarks_<?= $listingid; ?>"></div>
Then in the JavaScript $("#remarks_" + key).html(value);
Otherwise, you need to use jQuery to locate the div with the listing id using the :contains selector:
$("div:contains('# " + key + "')").appendTo(value);
'# " + key + "' would equate to # 1234 or whatever it is. This won't work if the same listing is on the page twice though!
Okay, here is the working success method. Thanks to LG_PDX for the cleaned up php. I eliminated the unnecessary processing as .each() appears to iterate just fine over the JSON response:
success: function(result) {
resultJson = $.parseJSON(result);
if (typeof resultJson == 'object') {
$.each(resultJson, function(key, value) {
$('.marketing-details-' + key).append( value );
});
}
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}

JQuery .html() not returning result of get() from PHP

I've got a page with four divs on it that I'm trying to load using jquery. The user shows and hides the divs by clicking on links. Currently, the contents of the divs are populated with PHP include statements, but that leads to ~30-second load times for the page.
I'm trying to replace those include statements with JQuery in order to load the proper contents of each div when the user clicks the link to show or hide it. My problem is that when I click one of the links to switch divs, the div appears but without anything in it. I've used Fiddler to ensure the request is going off (which it is) but the response is coming back as a 404.
However, when I examine the response in Fiddler, the expected HTML is there, just not getting passed into my element properly. I've tried using .load() as well as $.get(), but got the same results. I've also ensured my element names are correct as well. Code is as follows:
$(document).ready(function()
{
$('#allvideos').click(function () {
$.get("/wp-content/themes/Danceamatic/templates/all_videos.php", function(data) {
var $resp = data;
$( "#carrusel_all_videos" ).html($resp);
alert("Load was performed.");
});
$('#current_showcase').hide();
$('#carrusel_new_videos').hide();
$('#carrusel_featured').hide();
$('#carrusel_all_videos').show();
$('#i_mentors').hide();
return false;
});
$('#featuredvideos').click(function () {
$.get("/wp-content/themes/Danceamatic/templates/view_featured.php", function(data) {
var $resp = data;
$( "#carrusel_featured" ).html($resp);
alert("Load was performed.");
});
$('#current_showcase').hide();
$('#carrusel_all_videos').hide();
$('#carrusel_new_videos').hide();
$('#carrusel_featured').show();
$('#i_mentors').hide();
return false;
});
$('#newvideos').click(function () {
$.get( "/wp-content/themes/Danceamatic/templates/new_videos.php", function( data ) {
$( "#carrusel_new_videos" ).html( $.parseHTML(data) );
alert( "Load was performed." );
});
$('#current_showcase').hide();
$('#carrusel_all_videos').hide();
$('#carrusel_featured').hide();
$('#carrusel_new_videos').show();
$('#i_mentors').hide();
return false;
});
$('#currentshowcase').click(function () {
$('#carrusel_all_videos').hide();
$('#carrusel_new_videos').hide();
$('#carrusel_featured').hide();
$('#current_showcase').show();
$('#i_mentors').show();
});
});
I've set breakpoints on the "var $resp = $data" line and have not hit it at all.
Any help is appreciated. Thanks!
The url "/wp-content/themes/Danceamatic/templates/all_videos.php" is not correct. Double check the location of the javascript file that makes this request and also check the location of the php file.
If the location seems correct then maybe it's the structure of the url -- try:
"wp-content/themes/Danceamatic/templates/all_videos.php" or
"./wp-content/themes/Danceamatic/templates/all_videos.php" or
"../wp-content/themes/Danceamatic/templates/all_videos.php".

jquery each json variable bug

I have a strange bug. When I try to run my code:
var firstJson;
$.getJSON(site_url+"/more/sector_by_city/"+id+"?"+Math.random(), function( json ) {
$.each(json, function(key, value) {
firstJson = 9;
});
});
alert(firstJson);
The alert I get is: "undefined".
Why did I get this instead of getting 9?
What am I missing here?
(the each loop runs without issue and there are values in the JSON)
At the end, 9 changes to some other value.
Thanks
Async functions my friend. Your alert is being called before your .getJSON request has been finished. You'll need to use a callback function to get the correct alert.
Because when you call alert(firstJson) the asynchronous $.getJSON call has not yet completed, so firstJson has no value associated with it. If you move your alert into the $.each function or after the $.each, and at the end of $.getJSON, it will have a value.
The variable doesnt have a value when alert is called. You'll have to wait getJSON is over, using done().
var firstJson;
$.getJSON(site_url+"/more/sector_by_city/"+id+"?"+Math.random(), function( json ) {
$.each(json, function(key, value) {
firstJson = 9;
});
}).done(function() {
alert(firstJson);
});
References:
done()
$.getJSON

Categories