How can I load data from API to page on onload event? - javascript

Ajax call using JQuery Ajax call using JQuery

You can store the values in localStorage to retain them and append it to textbox as needed:
$(document).on('ready' ,function(){
var value=localStorage.getItem('symbols'); //get value from localStorage
if(value!="" && typeof value != undefined) //check if it has value or not
$("#inputSymbol").val(value) //set input text's value
$("form").submit(function(){
var valueEnteredByUser = $("#inputSymbol").val();
var valueToBeStored=localStorage.getItem('symbols') + ' ' + valueEnteredByUser;
//here I am storing values with space separate and you have to take care how you want to store it actually
localStorage.setItem('symbols',valueToBeStored); //Store it in same localStorage.
//var valueEnteredByUser = "GE";
if (valueEnteredByUser == null || valueEnteredByUser == ""){
alert("Please enter a valid symbol");
}
new Request.symbolExecution(valueEnteredByUser, function(data) {
$("#dataContainer").remove();
this.success(data);
});
return false;
});
});
Now at any point of time if you want to remove value just do as below:
localStorage.setItem('symbols','') //store empty value

I would make the AJAX call right away inside your $(document).ready() block and push it onto a table that has the style="visibility:hidden;" that way the API call can begin before rendering takes place. Next I would set the hidden table to show during the $(window).load() function (which occurs after 'ready').
It may looks something like this:
$(document).on('ready', function(){
//AJAX API Here
// On success push data to table (hidden style)
});
$(window).load(function(){
//$(.hiddenTable).show();
});
This should provide a good user experience since the data will begin retreival from the API before the page is even rendered.

Why not make the first call through php and then the rest of the keys through js, as you said you want the data that is available through "GE" key as the default, you could get that data by using CURL or get_file_contents().

Related

How to use the value of <div id =last_relay1></div> for create a loop condition in PHP?

I have a JS file that goes to my database and return the value,
The only values that can exist are 0 and 1.
After this I go to an PHP file I invoke this value however I want create a if condition loop to analyze the value of this div for display an image depending of the value.
For example:
if (<div id="last_relay1"></div> = 0) then display IMAGE A
else
if (<div id="last_relay1"></div> = 1) then display IMAGE B
My difficulty is to use the value of as a PHP variable.
//Script to load the value of the current relay
$(document).ready(function(){
setInterval(function(){
$("#last_relay1").load('last_update.php #RELAY1_STATUS_last_update')
}, 1000);
});
//little code to display the value of LAST_RELAY1 for database.
//the values returned possibles are 0 and 1
<div id="last_relay1"></div>
You can use a callback function with .load() to check the text of the DIV after it has been loaded. Use .text() to get the contents of the DIV.
$("#last_relay1").load('last_update.php #RELAY1_STATUS_last_update', function() {
if ($this).text().trim() == "0") {
$("#image").prop("src", "imageA.png");
} else {
$("#image").prop("src", "imageB.png");
}
});
I think what you are looking to do is to send data from the web page (generated by JavaScript) to PHP to decide which image to serve.
The way you framed the question won't help you find a solution (http://xyproblem.info/).
Instead, you will need to either:
preload both image A and image b, and display the one you want in javascript by unhiding it.
Dynamically load the image using PHP by making an XHR request that returns the correct image.
I solved it. I follow the tip provided by Barmar.
I used the following code...
var value = $("#last_relay1").load('last_update.php #RELAY1_STATUS_last_update', function() {
var value_to_test = value.text();
if(value_to_test == 1){
$("#last_relay1").empty();
$('<img src="img/ON.png">').appendTo("#last_relay1"); }
else {
$('<img src="img/OFF.png">').appendTo("#last_relay1");
}
});

How to access and use multiple data from json object? Do I need to make an array?

I am a beginner and using $.get to retrieve data from a rest API such as:
[{"id":"1","url":"http:\/\/123.456.78.910\/workforce\/images\/item1.jpg","price":"99","description":"Mobile Phone"},
{"id":"2","url":"http:\/\/123.456.78.910\/workforce\/images\/item2.jpg","price":"98","description":"Laptop"}
{"id":"3","url":"http:\/\/123.456.78.910\/workforce\/images\/item3.jpg","price":"92","description":"Console"}] }
$.get('http://xxxxxxxxxxx,
function (data) {
var obj = $.parseJSON(data);
So from what I understand I have retrieved the data from the REST API and parsed it so it is stored in a variable called obj.
My question is, how do I access and use each unique record in the obj variable?
Each record has it's own picture (item1.jpg, item2.jpg etc).
Whem my app loads I want it to show the item1.jpg image, and I want to be able to navigate to the other item pictures using buttons (previous / next).
I also want the description and price to be displayed underneath in some text input fields.
What I have figured so far is that I should:
Iterate through the obj variable, and store each record into an array.
Upon app initialisation I can set the default value for the image placeholder to array[index0].url, and set the description and price fields.
I can then set the previous and next buttons to array[currentIndex-1] or array[currentIndex+1].
Would this be the best way to do it?
Or can I just do this without using an array and manipulate the obj.data directly?
Thanks!!!
I may not be understanding what exactly what you want to do but I think I have the gist. If you just want to show the picture then the array of just images probably wouldn't be a bad idea. However, it looks like the Jason you're getting is already in an array. You can just use array index notation to get to what you want.
ie)
var arr = //your json response ;
var current = 0; //sets currently displayed object to the first in the array
var setCurrent = function () {
var image = arr[current]["url"];
}
You can then modify current however you want (on click on arrow iterate up/down, etc) then call the setCurrent function to set your image the the one you want. Hope that helps!
You can use the response you have from $.get() directly.
It is an array of objects.
You can use it like this:
console.log(data[2].description);
// outputs: "Console"
I've made a CodePen demo where it has a 4th object with a real image url to show you how to use the url info...
EDIT
Just in case you wouldn't know this:
You can use the response inside the scope of the $.get() callback...
You can not use it straith after the $.get() outside the callback since $.get() is asynchronous.
You can use it in some other handler wich will happen after the response is received.
var getResponse;
$.get('http://xxxxxxxxxxx', function (data) {
getResponse = data;
console.log(data[2].description);
// outputs: "Console"
console.log(getResponse[2].description);
// outputs: "Console"
});
console.log(getResponse[2].description);
// outputs: "Undefined"
// But since this handler will be triggered long after the response is obtained:
$("#somebutton").click(function(){
console.log(getResponse[2].description);
// outputs: "console"
});
In order for your page javascript to be able to access the data retrieved from your ajax request, you'll need to assign it to some variable which exists outside the callback function.
You will need to wait until the ajax request has been processed before you can read the array. So you might want to set the actual default image to be something that doesn't rely on the ajax request (a local image).
Here's a simple approach
// fake testing ajax func
function fakeget (url, callback) {
setTimeout(callback(JSON.stringify([
{"id":"1","url":"http:\/\/123.456.78.910\/workforce\/images\/item1.jpg","price":"99","description":"Mobile Phone"}, {"id":"2","url":"http:\/\/123.456.78.910\/workforce\/images\/item2.jpg","price":"98","description":"Laptop"},
{"id":"3","url":"http:\/\/123.456.78.910\/workforce\/images\/item3.jpg","price":"92","description":"Console"}
])), 1000);
}
// real code starts here
// global variables for ajax callback and setImg func to update
var imageData, currentImg;
// change this back to $.get for real
fakeget('http://xxxxxxxxxxx',
function (data) {
imageData = $.parseJSON(data);
setImg(0);
}
);
function setImg(index) {
// turns negative indices into expected "wraparound" index
currentImg = (index % imageData.length + imageData.length) % imageData.length;
var r = imageData[currentImg];
$("#theImg").attr('src', r.url);
$('#theDescription').text(r.price + " " + r.description);
}
$("#prev").click(function () {
setImg(currentImg - 1);
});
$("#next").click(function () {
setImg(currentImg + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img id='theImg' src='somedefault.jpg'>
<div id='theDescription'></div>
</div>
<button id='prev'>Prev</button>
<button id='next'>Next</button>
Few observations :
Your JSON Object is not a valid JSON.
No need to parse it again your data is already a JSON Object.
Working fiddle
var data = [{"id":"1","url":"http:\/\/123.456.78.910\/workforce\/images\/item1.jpg","price":"99","description":"Mobile Phone"},{"id":"2","url":"http:\/\/123.456.78.910\/workforce\/images\/item2.jpg","price":"98","description":"Laptop"}, {"id":"3","url":"http:\/\/123.456.78.910\/workforce\/images\/item3.jpg","price":"92","description":"Console"}];
for (var i in data) {
var imgUrl = data[i].url;
console.log(imgUrl);
}

jQuery and Ajax script

So i have a jQuery script that i should explain it line by line, i already do that and i want to make sure that is correct, so this is my script :
//Here we use the jQuery selector ($) to select the servers_id which is located into
//the delivers_id and we attaches a function to run when a change event occurs
$("#delivers #servers").change(function(){
//Here we look if the servers_id value was changed and the value is different of 0
if($(this).val() != '0') {
//Here we create a new variable sid and we stored the servers_id value in it
var sid = $("#delivers #servers").val();
//Here we use the Ajax $.get to get the sid value and send it by Ajax request then
//we set the data into the o_vmats_id html and empty the vmtas_id
$.get("/deliverability/get_vmtas/" + sid,
function(data) { $('#o_vmtas').html(data); $('#vmtas').html(''); });
}
//Here the else statement, we select the vmtas_id and set the html content like in the code (value=0)
//and empty the o_vmtas_id html content
else { $('#vmtas').html('<option value="0">All Classes</option>');
$('#o_vmtas').html(''); }
});
so please if someone has any remark i will be very appreciative
You're looking for the #servers element twice, no need for that. You can and should cache items that are going to be looked up more than once, so store that element in a var at the very beginning.
Other than that... there's not much to it, other than you wouldn't actually need much jQuery to do this :)

Jquery load content then refresh every 2 second

i am having trouble solving this, i'm trying to load a page which process a variable given by an input form then show the content based on the input, this worked fine, but i am also trying to refresh and update that input every 2 seconds
Below are my codes
<script>
$(document).ready(function(){
function getData(){
$("#dateslot").change(function(){
var inputField= $('#dateslot').val();
$("#timeslot").load('burgerorder_check.php?dateselect='+inputField);
});
setTimeout(getData,1000);
};
getData();
});
</script>
I'm trying to create a function that if someone else picked that, you won't be able to, which i successfully coded but not for the refresh part.
You have the methods and variables in the wrong order. You should probably set a variable outside the getData scope that can change at anytime, then just use that variable when fetching data.
Also, use setInterval if you want to repeat the function. setTimeout is simply a delay.
var val; // the select value is stored here
$("#dateslot").change(function(){
val = $(this).val(); // change the value
}
setInterval(getData,1000);
getData();
function getData(){
if ( val ) {
$("#timeslot").load('burgerorder_check.php?dateselect='+val);
}
}

Jquery delay to stop code like an alert box does

If I use an alert to stop the code running the ddl ‘Suburb1' is populated with the correct value if I use ‘delay’ the value is not set. I need some way of stopping the code running after ‘change’ so that $('#Suburb1').val(SuburbVC); is not fired straight away when the ddl Suburb1 is getting populated from the DB.
if ($(this).attr("checked") == true) {
var PostCode = $('#PostCode').val();
var SuburbVC = $('#SuburbVC').val();
$('#PostCode1').val(PostCode);
// Another function is called which populates Dropdown list from DB
// If I use delay Suburb1 is not populated
$('#PostCode1').change().delay(5000);
//If I use an alert Suburb1 is populated
// alert('delay');
$('#Suburb1').val(SuburbVC);
} else {
$('#PostCode1').val("");
}
Thanks
You are tackling this problem the wrong way; You should add a callback function to execute the rest of the code, after you populate the values from the DB.
How do you populate the values from the DB? AJAX? If so, add a function call with the code you want to execute after the data is ready, to the success handler.

Categories