issue when using window.location in loop to insert data (GET method) - javascript

I'm using sailsjs to insert data from GET parameter of the URL (mydomain.com/prod_master/addsupp).
The page is /prod_master/addsupp which is accepting GET parameters to insert in database.
In javascript I need to do loop and insert more than one record
following is the javascript code i'm using:
<script>
for(var i=2;i<(rCount);i++)
{
supplier=tbl.rows[i].cells[3].children[0].value;
del_lead_time=tbl.rows[i].cells[4].children[0].value;
min_qty=tbl.rows[i].cells[5].children[0].value;
window.location="/prod_master/addsupp?supplier="+supplier+"&del_lead_time="+del_lead_time+"&min_qua="+min_qty;
}
</script>
However I can confirm that using my url mydomain.com/prod_master/addsupp?supplier=val&del_lead_time=val2&min_qua=val3 its adding records to database perfectly
but in loop if i use window.location=url then its not working.
Any solution?
Note: if is there any jQuery solution then also let me know.

In loop you can't use window.location=url to call any url and do some task. Because javascript execution will be faster than you think. Once it has replaced URL in window.location, in next loop it will replace same and it will conflict with previous call.
Better approach would be calling that URL using ajax call.
I'm giving you psudo code using jQuery to do GET request.
<script>
for(var i=2;i<(rCount);i++)
{
supplier=tbl.rows[i].cells[3].children[0].value;
del_lead_time=tbl.rows[i].cells[4].children[0].value;
min_qty=tbl.rows[i].cells[5].children[0].value;
urlToCall="/prod_master/addsupp?supplier="+supplier+"&del_lead_time="+del_lead_time+"&min_qua="+min_qty;
$.get(urlToCall, function(response){
console.log(response); //you might want to see returned response
});
}
</script>

Related

Can't work with data obtained with $.Ajax()

I am writing a JS where I want to make some Ajax calls to get a JSON file from my DB in CouchDB. My code is based on examples I found online, but my lack of experience and knowledge is making it difficult to fix it completely.
My code:
function myFunction(){
var request = $.ajax({
url:'http://admin:pass#localhost:5984/db/_design/view/_view/view',
type:'get',
dataType:'json'
});
request.done (function (data)){
var result;
for (var i in data){
if( data[i] == key){
result.push(data[i]);
}
}
console.log(result);
};}
Problem: It seems like it is not even doing the requested call since when I try to print my array it isn`t doing anything.
The way see it, in the first part where I defined request it should get the JSON file from CouchDB. And, if correct, in the second part where the request is done request.done I give the function how I want the JSON file to be taken care of. To make it clear, my idea is to iterate through the data and to save the values of the "key" in every row in my result-array.

Using GET method to get href attribute of an object

What i'm trying to do is what i thought would be quite easy, but it doesnt seem to be working. I want to get the href of an object and all the function is returning is undefined.
This is the page that i'm requesting and what i'm trying to retrieve is the href held in the element of the first seller (who's ClassName is ui-link-inherit)
var buy = $.get(
"http://m.roblox.com/items/24826737/privatesales/",
function (data){
alert($(data).find(".ui-link-inherit:eq(0)").attr('href'));
}
);
I thought it was a permissions issue at first but it still wont work even if you run that on the page.
Did you tried to just alert the data you get?
If there is no .ui-link-inherit ofc it wont work and since .ui-link-inherit seems to be a class of jqueryUI which adds the classes after the page is loaded via javascript, you wont get this class via GET
//EDIT: I dont get all this "you cant access the data cause ajax is asynchronus". He is using the get-fukction completely right. He can access data since data IS the returned stuff from the server. Did I miss something that you all get this that way?
You cannot return a value from that function, it is executed asynchronously. Instead just wait for the AJAX to finish and then do something with the result
// don't do this
// var buy = $.get(... etc...);
// the variable buy will never have any value
// do this instead
function getHREF(){
$.get(
"http://m.roblox.com/items/24826737/privatesales/",
function (data){
var buy = $(data).find(".ui-link-inherit:eq(0)").attr('href');
doSomething(buy);
}
);
)};
function doSomething(buy) {
// in here do whatever you want with the ajax data
}
$(document).ready(function () {
getHREF();
});
The site does not allow Cross-site HTTP requests. Read here: HTTP access control

Passing a Javascript variable back to php, when no submit button functionality is used

I have a fairly complex PHP script in place, and I need to embed a very small JavaScript prompt inside of this code.
This is my criteria / requirement:
I want this JavaScript code to execute when a certain set of criteria is met.
I do NOT want to execute this code with any kind of submit button.
I currently have the PHP code calling the JavaScript prompt correctly.
The JavaScript comment / variable is being initialized, and stored properly, within the JavaScript code itself.
The parent PHP code is waiting for the JavaScript input, and does not continue until the prompt text has been entered.
But, I have not been able to figure out how to pass the JavaScript variable back to the parent PHP code.
What I have so far is very simple, but it is working exactly as I intended:
function getReprNotes() {
?>
<script>
var REPRNOTES = prompt('Please enter any appropriate reprocessing request notes');
alert(REPRNOTES);
</script>
<?php
}
getReprNotes()
Note that I want to pass the REPRNOTES text / variable back to the parent script.
Can anyone tell me how I need to do this, using the above code?
Keep in mind javascript is client side scripting, and php is server side. The only way for you to send information to PHP is by making a call to the server, the best way to do this from the client using javascript without submitting a form is by is using AJAX.
Take a look at these tutorials: 5 Ways to make AJAX calls with jquery and 24 best practices for AJAX implementations.
This is what AJAX calls are for. Split your PHP into two and have the javascript issue an ajax call which triggers the second. If you can use jQuery then you want to make a $.ajax() call: https://api.jquery.com/jQuery.ajax/
If you can't or don't want to use jQuery you can still make ajax calls through XMLHttpRequest objects: http://www.w3schools.com/Ajax/default.asp
$.ajax({
url: '/to-some-url',
data: 'data=' + value,
type: 'POST',
success: function (response, textStatus, jqXHR) {
if (jqXHR.status > 0) {
// do something here
}
}
});
You can use jquery ajax method to pass javascript variable value to php by post(or get). But I don't understand what you really want to achieve

Ajax Call Confusion

before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>

How do I assign a JSON response from this API I'm using to elements on my page?

I'm trying to use the API from https://developer.forecast.io and I'm getting a JSON response, this is the first time I'm using an API and all I really need to know is, how do I assign the JSON response I get back from their API to elements on my page. Thanks!
This is done with a script-tag in my header:
script(src='https://api.forecast.io/forecast/APIKEY/LAT,LON')
http://api.jquery.com/jQuery.ajax/ you need to add a success callback, at the bottom of that page are examples you can look at.
EDIT
ok i saw that you are using a script tag with the request, since the api is outside your current domain you need to make a JSONP request
$(document).ready(function(){
$.ajax({
url: 'https://api.forecast.io/forecast/APIKEY/LAT,LON',
dataType: 'jsonp',
success: function(data){
//do whatever you want with the data here
$("body").append(JSON.stringify(data));
}
});
});
off course you need to make some tweaks to that piece of block but you get the idea
What you're looking for is DOM manipulation. DOM is the HTML Document Object Model, an object representation of the HTML comprising a document. There are a lot of ways to go about this, but one of the more popular Javascript libraries for performing this task is jQuery. See their help documentation category on manipulation for more information.
OK, based on your clarification, you're not yet using AJAX. I say "not yet", because you're going to need to. Again, I'll recommend jQuery for that, and their own documentation as the best resource. For a simple "get", your easiest option is the getJSON method.
So, at a very simple level you might do something like:
$(function(){
$.getJSON('url_to_api', function(data) {
$("#SummaryBox").append("<div>" + data.hourly.summary + "</div>");
}
});

Categories

Resources