returing data after the call success, ajax? - javascript

'function makeRequest()
{
var G_REL_URL="'||owa_util.get_cgi_env('SCRIPT_NAME')||'"
var v_data_sales ={ pvCurrCd:"'||CURRDEF||'"
};
$.ajax({
url:G_REL_URL+ "/contr_entry_pkg.SELECT_SALES_CENTERS",
data:v_data_sales,
async:false,
success: function(vRetVal){
//var jsonObj = eval("("+vRetVal+")");
function processresponse(v_data_sales,vRetVal)
}
});
} '||CHR(10)||
'function processresponse (v_data_sales,vRetVal){
retJson=eval("("+vRetVal+")");
} ';
i want to return a data to a dropdown after there is a onchange='makeRequest"
im not sure if im doing it the right way but is not giving me any errors
and is not working
maybe my logic is wrong but after its success if calls the function
processresponse so it will return pvcurrcd
but its not doing it.
any help or tips ,thanks
here below is where it make the onchange call which i dont think it matter here
HTP.P('<td class="reqlabel1">Sales Center:</td>');
HTP.P('<td class="tablelabel">');
HTP.P(Get_Sc_Dd(PVNAME=>'pnSalesCenterID', PVORAID=> VUSERNAME,
PVDEFVAL => NSALESCENTERID, PVEVENT=>'class="reqinput1" onChange="makeRequest();" style="width:260px"'));
it will change the currency dropdown here
HTP.P('<td class="reqlabel1">Currency:</td>');
HTP.P('<td class="tablelabel">');
HTP.P(Get_Currency_Dd(PVNAME=>'pvCurrCd', PVDEFVAL => NULL,
PVEVENT=>'class="reqinput1" id="pvCurrDd" onblur="makeRequest();" style="width:200px"'));

your code is missing some correct syntax... try this
'function makeRequest(){
var G_REL_URL="'||owa_util.get_cgi_env('SCRIPT_NAME')||'";
var v_data_sales ={ pvCurrCd:"'||CURRDEF||'" };
$.ajax({
url:G_REL_URL+ "/contr_entry_pkg.SELECT_SALES_CENTERS",
data:v_data_sales,
async:false,
success: function(vRetVal){
//var jsonObj = eval("("+vRetVal+")");
/*
fire up the Javascript console in
chrome/firefox/safari
and look at the result of:
*/
console.log(vRetVal);
// or better:
console.dir(vRetVal);
processresponse(v_data_sales,vRetVal);
}
});
function processresponse(v_data_sales,vRetVal){
retJson=eval("("+vRetVal+")");
}
}';

Related

How to restore Jesson's value and put it into outside variable

I have a problem with this code
I manage to take the values from the json and put them into variables but I can not use them outside the function
what am i doing wrong ?
var sensor_name1;
var lat1;
var lng1;
var sensor_name2;
var lat2;
var lng2;
var sensor_name3;
var lat3;
var lng3;
$(function (){
var $sensors = $('#sensors');
$.ajax({
type:'GET',
url:'http://127.0.0.1:5000/',
success: function(sensors){
$.each(sensors, function(i, sensor) {
if (i==0){
$sensors.append(sensor_name1=sensor.name, lat1=sensor.lat, lng1=sensor.lng);
}
if(i==1){
$sensors.append(sensor_name2=sensor.name, lat2=sensor.lat, lng2=sensor.lng);
}
if (i==2){
$sensors.append(sensor_name3=sensor.name, lat3=sensor.lat, lng3=sensor.lng);
}
});
console.log('sensor one : ',sensor_name1, lat1, lng1);
console.log('sensor tow : ',sensor_name2, lat2, lng2);
console.log('sensor three : ',sensor_name3, lat3, lng3);
}
});
});
Hi and welcome on Stack Overflow :)
JavaScript Ajax is asynchronous and you execute console.log() before these variables receive a value.
But in your case you pass to append() which accepts a htmlString, Element, Text, Array or jQuery parameter a assignment of value expression. You don't append a child, but you declared it using append()
You must have to wait for response from server and after use that.
$(function () {
var $sensors = $('#sensors');
$.ajax({
type: 'GET',
url: 'http://127.0.0.1:5000/',
success: function (sensors) {
$.each(sensors, function (i, sensor) {
let sensorInfo = 'sensor #'+i+': '+sensor.name+' '+sensor.lat+' '+sensor.lng;
console.log(sensorInfo);
$sensors.append('<p>'+sensorInfo+'</p>')
});
}
});
});
Greetings, plum!
Sources:
Asynchronous on MDN: https://developer.mozilla.org/en-US/docs/Glossary/Asynchronous
jQuery Docs: https://api.jquery.com/jQuery.get/#jQuery-get-url-data-success-dataType

jQuery blur based checking and print result to a view in codeigniter

Possibly someone asked question like as my question. But, I can't find any solution.
ProfileEditor.php (controller)
method 1:
public function modify_personal_information() {
$this->data['userinfo'] = $this->personal_information_of_mine($userid);
$this->load->view('layouts/header', $this->data);
$this->load->view('profile/personalinformation', $this->data);
$this->load->view('layouts/footer', $this->data);
}
method 2:
public function check_url_if_exists() {
$newportalurl = $this->uri->segment(2);
$this->results = $this->profile_model->checknewportalurl($newportalurl);
if ($this->results == 1) {
$this->status['status'] = 1;
$this->status['msg'] = 'This name is available. Thanks.';
} else {
$this->status['status'] = 0;
$this->status['msg'] = 'This name is not available. See suggestions.';
}
$this->load->view('profile/layouts/availiability', $this->status);
//or echo json_encode($this->status);
}
profile/personalinformation.php (views)
a form with <div id="urlsuggestions"></div>
profile/layouts/availiability.php (views)
where i am printing the message which i am getting from the check_url() function
ajax.js (ajax)
$('#newportalurl').blur(function() {
var fval = $(this).val();
var ifexists = fval.toLowerCase().replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '');
$.ajax(baseurl + "check/"+ifexists, function(data) {
//i tried following things
//alert(window.location);
//$('#msgbox').html(data.msg).show().addClass('alert-success').delay(2000).fadeOut();
//$('#urlsuggestions').load(window.location + 'modifypersonalinformation #urlsuggestions');
});
});
Now, I am trying to load the message to personalinformation view. What I am doing wrong or what will be the procedure to do it? I actually want to know the process how codeigniter handle them.
Please try like this, im not able to get response from your metod.
$.ajax({
url: "<?= base_url("check/") ?>"+ifexists,
success: function (data) {
$("#urlsuggestions").html(data);// if you want to replace the data in div, use .html()
or if you want to append the data user .append()
}
});

Submiting a form via json/ajax/jquery

Here is my code
function generate_clicked()
{
var txt_text_color = $('#txt_text_color').val();
var url='process.php?';
url+='txt_text_color='+encodeURIComponent(txt_text_color);
$.ajax({
url: url,
beforeSend: function ( xhr ) {
xhr.overrideMimeType("application/json; charset=x-user-defined");
}
}).done(function ( data ) {
try{
$('#preview').val(data.css);
$('#my_iframe').srcdoc = data1;
}
catch(err)
{
console.log(err);
}
document.getElementById("my_iframe").src = data.live_preview_html_page;
});
}
This works for my purposes but if I added another form element I would tediousily have to add var example =$('....').val();
and
url+='example'+endcodeU.....
Which I will be having over 100 elements, then I would retreview them on process with
$txt_text_color = $_REQUEST['txt_text_color'];
My question is, how can I serialize this (I think that's what I need to do) so that I don't have to write those two varibles names each time I make a new form object.
I need to save get/post those varibles in process.php to use them.
Sorry if this doesn't make sense, I'm still learning.
Try form.serialize()
http://api.jquery.com/serialize/
Your code would look something like this:
function generate_clicked()
{
var formData = $('#form').serialize();
var url='process.php?';
url+=formData;
$.ajax({
url: url,
beforeSend: function ( xhr ) {
xhr.overrideMimeType("application/json; charset=x-user-defined");
}
}).done(function ( data ) {
try{
$('#preview').val(data.css);
$('#my_iframe').srcdoc = data1;
}
catch(err)
{
console.log(err);
}
document.getElementById("my_iframe").src = data.live_preview_html_page;
});
}

read a div from an html file to a javascript var

I want to read the colTwo div from the file members.html (in the same folder) into a variable, then set innerHTML to that variable. The result is 'undefined'. How can I fix this?
var fredpagevar;
$.get("members.html", function(data){
fredpagevar = $(data).find('#colTwo').html();
});
function fredpage(){
document.getElementById('boldStuff').innerHTML = fredpagevar;}
based on your markup : <li><a href="#" onclick='fredpage()'>Fred</a></li>
Try this -
function fredpage(){
$.get("members.html", function(data){
$('#boldStuff').html($(data).find('#colTwo').html());
});
}
You can simply do this:
$.get("members.html", function (data) {
$('#boldStuff').html($(data).find('#colTwo').html());
});
This should work:
var fredpagevar;
$.get("members.html", function(data){
fredpagevar = $(data).find('#colTwo').html();
}).done(function (){
document.getElementById('boldStuff').innerHTML = fredpagevar;
});
Your function probably fired before get method receive data from file.
Or second usage (in case when you use your function in other place):
var fredpagevar;
$.get("members.html", function(data){
fredpagevar = $(data).find('#colTwo').html();
}).done(fredpage());
function fredpage(){
document.getElementById('boldStuff').innerHTML = fredpagevar;
}

Advice requested - passing variables between functions using json/jquery & ajax

I've looked over a lot of 'similar' q&a threads on SO but to be honest, as I don't have too much of a grip on js programming, I'm finding it difficult to make sense of a lot of the answers (as far as they may apply to my own situation).
The context is this, I have two php scripts one returning a list of customer_ids (json encoded) for a set period and the other returning their preferences for news feeds (json encoded).
I wrote the following, having googled a bit to get a basic understanding of how to setup an ajax function in jQuery:
$('document').ready(function() {
$.ajax({
type:'GET', url: 'cust_selection.php', data: '',
succes:function(cstmrid) {
var clistlen = cstmrid.length;
var i=0;
var cstmr;
for( ;cstmr=cstmrid[i++]; ) {
$('#adminPanel>ul>li').append("<a href='' onclick='alert("+cstmr+")' class='lst_admin basic'>"+cstmr+"</a>"); //alert to be replaced with a function call which passes customerid to the function below.
}
},
dataType:'json'
});
var cstmrid = "483972258"; //hardcoded for testing purposes
$.ajax({
type:'GET', url:'newsfpref.php?', data:'cref='+cstmrid,
success:function(npfdata) {
var item;
var n=0;
for( ;item=npfdata[n++]; ) {
var news = npfdata[n].nsource;
$('#adminMain>table>tbody').append("<tr><td>"+item+"</td></tr>");
}
},
dataType:'json'
});
});
Now from the first ajax function, I get a list of links which I want to be able to click to launch the second ajax function and pass it the customer id so that it can grab a list of the news sources that they've configured for their pages.
The alert and the hard-coded customer id both suggest that the functions are 'working', but when I try and adjust the first function so that:
...
$('#adminPanel>ul>li').append("<a href='' onclick='getCustomerNP("+cstmr+")' class='lst_admin basic'>"+cstmr+"</a>");
... is calling a modified version of the second function, as below:
...
function getCustomerNP(cstmrid) {
$.ajax({
type:'GET', url:'newsfpref.php?', data:'cref='+cstmrid,
success:function(nprfdata) {
var item;
var n=0;
for( ;item=npfdata[n++]; ) {
var news = npfdata[n].nsource;
$('#adminMain>table>tbody').append("<tr><td>"+item+"</td></tr>");
}
},
dataType:'json'
});
}
Everything seems to just fail at this point. The second function doesn't seem to 'receive' the variable and I'm not sure if it's something elementary that I've overlooked (like some muddled up " and ' placements) or if what I am trying to accomplish is actually not the way jQuery ajax functions interact with each other.
As you can see, I've cannibalised bits of code and ideas from many SO q&a threads, but copying without much of an understanding makes for a frustratingly dependent life.
I would appreciate as much - expansive - comment as you can provide, as well as a solution or two (naturally).
EDIT: Not to confuse anyone further, I've been modifying the above and correcting my (many) errors and typos along the way. At present, the code looks like below:
$('document').ready(function () {
$.ajax({
type: 'GET', url: 'cust_selection.php', data: '',
succes: function (cstmrid) {
var clistlen = cstmrid.length;
var i = 0;
var cstmr;
for (; cstmr = cstmrid[i++]; ) {
var a = $("<a href='' class='lst_admin basic'>" + cstmr + "</a>").click(function () {
getCustomerNP(cstmr)
})
$('#adminPanel>ul>li').append(a); //alert to be replaced with a function call which passes customerid to the function below.
}
},
dataType: 'json'
});
function getCustomerNP(cstmr) {
alert(cstmr);
}
});
You've got a typo in the $.ajax() success function within getCustomerNP(). The function declaration:
success:function(nprfdata) {
... has a parameter nprfdata, but then within the function you use npfdata (missing the r).
Also this code:
var item;
var n=0;
for( ;item=npfdata[n++]; ) {
var news = npfdata[n].nsource;
$('#adminMain>table>tbody').append("<tr><td>"+item+"</td></tr>");
}
...declares and sets variable news that you never use. And it doesn't seem right to increment n in the for test expression but then use n within the loop. You never set item to anything but you use it in your .append().
(Note also that JS doesn't have block scope, only function scope, so declaring variables inside an if or for loop doesn't limit them to that if or for block.)
I would not create inline onclick handlers like that. I'd probably do something more like this:
$('#adminPanel>ul>li').append("<a href='' data-cstmr='"+cstmr+"' class='lst_admin basic'>"+cstmr+"</a>");
...and then within the document ready setup a delegated event handler to catch the clicks on those anchors:
$('#adminPanel>ul>li').on('click', 'a.lst_admin', function() {
$.ajax({
type:'GET', url:'newsfpref.php?', data:'cref='+ $(this).attr('data-cstmr'),
success:function(npfdata) {
var item,
n=0,
// cache the jQuery object rather than reselecting on every iteration
$table = $('#adminMain>table>tbody');
// increment n only after the current iteration of the loop
for( ;item=npfdata[n]; n++) {
// change to use item
$table.append("<tr><td>"+item.nsource+"</td></tr>");
}
},
dataType:'json'
});
});
As you append your like with <a href='' onclick='getCustomerNP("+cstmr+")', Make sure you can access the function getCustomerNP.
Try to define getCustomerNP as
window.getCustomerNP = function(cstmrid) {
...
If you defined it in the $(document).ready(function(){ ... }) block, try this
$('document').ready(function () {
$.ajax({
type: 'GET', url: 'cust_selection.php', data: '',
succes: function (cstmrid) {
var clistlen = cstmrid.length;
var i = 0;
var cstmr;
for (; cstmr = cstmrid[i++]; ) {
var a = $("<a href='' class='lst_admin basic'>" + cstmr + "</a>").click(function () {
getCustomerNP(cstmr)
})
$('#adminPanel>ul>li').append(a); //alert to be replaced with a function call which passes customerid to the function below.
}
},
dataType: 'json'
});
function getCustomerNP(cstmrid) {
$.ajax({
type: 'GET', url: 'newsfpref.php?', data: 'cref=' + cstmrid,
success: function (nprfdata) {
var item;
var n = 0;
for (; item = npfdata[n++]; ) {
var news = npfdata[n].nsource;
$('#adminMain>table>tbody').append("<tr><td>" + item + "</td></tr>");
}
},
dataType: 'json'
});
}
});

Categories

Resources