AJAX success not render properly since second request - javascript

I use ajax to render output to below HTML element.
<p class="result-box" id="result-box">The result is : <br><strong id="result"></strong></p>
Everything works fine when rendering result for the 1st input request.
When I update my input, the console changes and prints desired data but the webpage including the text does not change.
I get Cannot read property 'setAttribute' of null at canvas_and_ploton the 2nd+ time refresh below, If I remove setAttribute, I get Cannot read property 'getAttribute' of null at canvas_and_plot.
$(document).on('submit','#cat_select',function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'/cat_select',
data:{
l2:$('#l2').val(),
l3:$('#l3').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
},
success: function server_response(response) {
const r = JSON.parse(response);
console.log(r); //updated
var cat_result = r.cat_result;
console.log(cat_result[0]) //updated
var text=$('<i></i>');
$.each(cat_result, function(idx, value) {
text.append('<id="result'+idx+'">' + cat_result[idx][0]+ '<br>'); //even the text output are not updated
text.append('<canvas id="canv_'+idx+'" width="200" height="200"></canvas><br>');
});
$('#result').replaceWith(text);
$.each(cat_result, function(idx, value) {
canvas_and_plot(idx,cat_result[idx][9],cat_result[idx][10],cat_result[idx][11])});
}
function canvas_and_plot(idx,a,b,c) {
var canv = document.getElementById('canv_'+idx);
canv.setAttribute('id', 'canv_'+idx);
var C = document.getElementById(canv.getAttribute('id'));
//plot...
}
I tried adding cache: false and adding random number to the url but neither of them works.
Why only error after the first request? How can I fix this? Thanks

The reason for it not changing is that you are replacing your block #result with received data.
$('#result').replaceWith(text);
After which you'll a dom tree that looks something like this:
<p class="result-box" id="result-box">
The result is : <br>
<i>
<id="result123">...<br>
<canvas id="canv123" width="200" height="200"></canvas><br>
<id="result321">...<br>
<canvas id="canv321" width="200" height="200"></canvas><br>
</i>
</p>
So the second time you click there is no element with #result id.
I suggest (as a rough and quick solution):
On every request remove all children of your #result element and fill it again with new data. So add this line before making the request - $('#result').empty(); and replace $('#result').replaceWith(text); with $('#result').append(text);
The main idea is to keep the place you put and add your server data. Hope this helps!

Related

How can I grab a div in PHP that's in a loop within a javascript function

Below is the code.
under the function there is a resultContainer.innerHTML that populates a list of QR codes scanned. How can $_POST the values in PHP so that I can send it in an email format? I tried adding a name within the div (<div **name="qrOutput"**>[${countResults}] - ${qrCodeMessage}</div>) but PHP does not pick it up. Only returns an empty string.
I also tried giving the <div id="qr-reader-results"></div> element a name but because the output is within another div inside this div I also got an empty result.
Thanks a lot for any help.
<!-- start -->
<div id="qr-reader" style="width:500px"></div>
<div id="qr-reader-results"></div>
<div id="root"></div>
<script>
function docReady(fn) {
// see if DOM is already available
if (document.readyState === "complete" ||
document.readyState === "interactive") {
// call on next available tick
setTimeout(fn, 1);
} else {
document.addEventListener("DOMContentLoaded", fn);
}
}
docReady(function() {
var resultContainer = document.getElementById('qr-reader-results');
var lastResult, countResults = 0;
function onScanSuccess(qrCodeMessage) {
if (qrCodeMessage !== lastResult) {
++countResults;
lastResult = qrCodeMessage;
resultContainer.innerHTML += ***`<div">[${countResults}] - ${qrCodeMessage}</div>`;***
}
}
var html5QrcodeScanner = new Html5QrcodeScanner(
"qr-reader", {
fps: 10,
qrbox: 250
});
html5QrcodeScanner.render(onScanSuccess);
});
</script>
<p id="QRout"></p>
You can store your results in an other variable when you add it to the DOM.
Declare a variable to store your results
var myResults = [];
When you add the result to the DOM add also the results in array variable
// ...
resultContainer.innerHTML += `<div>[${countResults}] - ${qrCodeMessage}</div>`;
myResults.push({count: countResults, message: qrCodeMessage})
Then you can use myResult var on a POST request
myCustomPostFunction('/yourUrl/', myResult);
The "myCustomPostFunction" will depend on the way you want to send the data
Check this codepen: https://codepen.io/zecka/pen/VwKNpze
Post request like a form submit
If you want to send the data to the current page like a form post, you can find an example here: https://stackoverflow.com/a/133997/2838586
Post request to a rest api
Fetch: POST json data

Code snippet not loading properly

I'm trying to add a review snippet to a webpage after retrieving the corresponding data-id from the database. Unfortunatly the snippet doesn't work properly if I add the snippet like shown below. The snippet works fine if it is hardcoded in html but not if I add it in javascript or if I put the snippet without a data-id and then try to append the data-id attribute with the correct id.
I've tried loading my ajax call to the database in a script next to the div's location to then simply use document.write() but without success. The snippet in use is a review snippet from Mobials.
Help is greatly appreciated.
<div id="mobials"> </div>
<script type="text/javascript" src="//api.mobials.com/assets/js/api/v1.js"></script>
<script type="text/javascript" src="https://mobials.com/assets/js/api/review.min.js"></script>
function Submit() {
if (validateInputs()) {
$.ajax({
type: "GET",
url: "#ViewBag.urlApi" +"LocationDetails?zipcode=" + $("#ZipCodeLoc").val() + "&format=JSON&authoriazation={"+"#ViewBag.ApiKey"+"}",
dataType: "jsonp",
traditional: true,
success: function (data) {
$("#events").empty();
$("#logos").empty();
$("#openingHours").empty();
locationDetails = JSON.parse(data);
//Customer Reviews
var isMobial = false;
$.each(locationDetails.Reviews, function (key, value) {
if(key == "Type" && value == 1){
isMobial = true;
$("#consumerAffairs").hide();
}
if(key == "ReviewCode" && isMobial){
var mob = document.getElementById("mobials");
mob.innerHTML += '<div class="mobials-root" data-id="'+value.reviewcode+'" data-language="en" data-type="badge" data-size="200"></div>';
}
});
}};
}
}
EDIT: This line in my .html:
<div class="mobials-root" data-id="someId" data-language="en" data-type="badge" data-size="200"></div>
Looks like this when loaded:
<div class="mobials-root" data-id="someId" data-language="en" data-type="badge" data-size="200" data-tracker="1" id="mobial-root-1"><img src="https://s3.amazonaws.com/mobials.com/api/badges/read_reviews/en/174_174_4.7_70.png"></div>
You can't use document.write() with ajax calls.
document.write() will work "as expected" only as long as the document is open. As soon as the browser recognizes that the document is loaded completely, the document is closed.
Subsequent calls to document.write() will replace the document rather than append to it.
Edit: but looking at your code, I don't see document.write() at all.

Javascript JSON object acess error

I've recently been working on a phonegap application using JSONP to create a dynamic feel. I have however recently hit a bit of a brick wall...
The following function is used to parse some delivery data (irrelevant) into jquery mobile:
function parseProdData(results) {
var html = '';
for (day in results.deliveries) {
var today = results.deliveries[day].delivery;
var today_date_arr = today.date.split('-');
var today_date = today_date_arr[2]+'/'+today_date_arr[1]+'/'+today_date_arr[0];
html += '<li><a href="#">';
html += today.delivery_day+', '+today_date;
html += '</a></li>';
console.log(html);
}
$('#JSON-list').append(html);
$('#JSON-list').trigger('create');
$('#JSON-list').listview('refresh');
}
Now all this looks like its working fine as when I check the console log I get:
<li>Thursday, 27/02/2014</li><li>Friday, 28/02/2014</li><li>Monday, 03/03/2014</li><li>Tuesday, 04/03/2014</li><li>Wednesday, 05/03/2014</li><li>Thursday, 06/03/2014</li><li>Friday, 07/03/2014</li>
Thus showing that it is accessing both the date and time attributes correctly. However, straight after this I get an uncaught type error:
Uncaught TypeError: Cannot read property 'date' of undefined
From my understanding of JS this should only happen when the relevant attribute is unset. As we can see from the html output in console, this is not the case as it is being accessed correctly.
Finally, I get exactly the same error (with delivery_day as the 'undefined' attribute) if I restrict the code to just the delivery day.
For those who would like it, below is a sample of the JSON code used:
{
"deliveries":[
{
"delivery":{
"delivery_day":"Thursday",
"date":"2014-02-27"
}
},
{
"delivery":{
"delivery_day":"Friday",
"date":"2014-02-28"
}
}
]
}
Does anyone have any idea why this error is popping up?
*EDIT*
Just to say, I'm fairly confident that the error is in the top part rather than the JQuery mobile elements as if I comment out the block $('#JSON-list').append(html); with $('#JSON-list').append(<li>Thursday, 27/02/2014</li><li>Friday, 28/02/2014</li>); then it works fine, but thats obviously not a solution.
*EDIT 2*
The issue was just that there was an empty element at the end of the 'deliveries' block, this was causing the uncaught error. I didn't notice it because the element was empty. Credit to #eithedog for pointing me in the right direction
I saved json data in result.json file then used this
$.getJSON('result.json', function(result, status){
var today = result.deliveries;
var html = "";
$.each(today, function(key, value){
$.each(value, function(key, value){
var today_date_arr = value.date.split('-');
var today_date = today_date_arr[2]+'/'+today_date_arr[1]+'/'+today_date_arr[0];
html += '<li>'+value.delivery_day+', '+today_date+'</li>';
})
})
$('#JSON-list').append(html);
$('#JSON-list').trigger('create');
$('#JSON-list').listview('refresh');
})
.success(function(result) {})
.fail(function(jqXHR, textStatus, errorThrown) {
})
.complete(function() { });
The issue was just that there was an empty element at the end of the 'deliveries' block, this was causing the uncaught error. I didn't notice it because the element was empty.
Credit to #eithedog for pointing me in the right direction.

How to get text field value from another page javascript

Here My script code
page 1 / index.php
$(document).ready(function(){
$("#list").load("load_list.php");
function reloadlist(){
var total_list = $("#total").val();
$.get('load_list.php', function(data){
var values = $("input[name='total']", data).val();
alert(values);
});
} setInterval(reloadlist, 3000);
})
<body>
<div id="list"></div>
</body>
page 2 / load_list.php
[My query for get the total data]
<input type="hidden" name="total" id="total" value="<?=$total?>">
When i load that index page, and alert value will be undefined. how to get text field value from load_list.php
save the value in a cookie and retrive it in next page
The element is at root level, and the contex selector uses find() internally, and that only works on descendants.
You can avoid any and all issues with elements being descendants or at root level by appending the content to another element, and then using find(), or you could use filter() directly
$.get('load_list.php', function(data){
var values = $('<div />', {html: data}).find("input[name='total']").val();
alert(values);
});
Also, the element has an ID, and it would be more efficient to use that in the selector.
You're in kind of a bad situation since you're just reloading the list after 3 seconds even if the call failed. You should try to clean up the whole idea a bit.
function reloadList = setTimeout(function(){
$.get('load_list.php', function(result){
var value = $(data).filter('#total').val();
alert(value);
reloadList();
});
}, 3000);
reloadList();

jQuery get href initial value once before it changes

In my application I have an ajax call, and on success it appends some data to an existing links href.
This works great. The issue is, If I want to run the ajax call again and on success, append some different data, it is taking the href value + the new value from the previous ajax call, and than adding the new data after that.
I want it to add the data to the inital href value, before it was appended.
Below is my code:
(I have the sample sample value being appended each time for testing purposes)
//get next page link value, so we can add filter to url
var next_link = $("a.next").attr("href");
$.ajax({
type: "POST",
url: "ajax_calls.php",
data: "instrument="+selected.val()+"&filter=true",
success: function(listing){$("#listings").html(listing);
$("a.next").attr("href", next_link + '&field=x');
},
error: function(){alert(3);$("#error").text("Could not retrieve posts").fadeIn(300).delay(900).fadeOut(300)}
});
Any help on this would be appreciated.
Thank you
How about using jQuery's .data method?
$('#change').click(function(){
var newData = Math.random() * 1000; // fake new data
$('a').each(function(i,e){
var oldHref = $(this).data('oldHref');
if (!oldHref){
var oldHref = $(this).attr('href');
$(this).data('oldHref',oldHref);
}
$(this).attr('href',oldHref + '#' + newData);
});
});
Hello, world!<br />
<input type="button" id="change" value="Change HREF" />
example
Store the old value in a data element, then reference before each new change.

Categories