I have a page that loads in "get-results.php" which loads the results into a div. This works great. However, I also need to grab a variable from the php file that is being loaded, so that I can re-include it in the .load() url, this way I can have the php file have the previous result for comparison.
$(".results").load("get-results.php" + "?userClicked=" + var1 + var2 + "&prevresult=" + theResults);
In the "get-results.php" file, I have set
var theResults = "<?php echo $result; ?>";
Is there a way for me to access "var theResults" from the page that is loading it (outer page, not inner)? How can I get the Var from the file and put it into a Var in the outer file? Any pointers would be great thanks.
var theresults;
$(".results").load("get-results.php" + "?userClicked=" + var1 + var2 + "&prevresult=" + theResults,function() {
theresults=$(".results").html();
}));
obviously you have to wait the load is complete to get the new value for theresults.
otherwise, you can use $.get which seems more appropriate here :
$.get("get-results.php" + "?userClicked=" + var1 + var2 + "&prevresult=" + theResults,function(data) {
theresults=data;
$(".results").html(data);
}))
edit : if you are indeed sending more than this php var, you should send back a json (with your variables to be sent in an array then you echo json_encode($arrayofvar) then in the js you'll retrieve a json object of your var in the getJSOn callback
No you can not, i.e if you are sending other things with the variable.
If you are sending only that variable ( which I think you are not), then use the above answer.
Else
try this one:
in php file:
var theResults = "<?php echo $result; ?>";
echo "<input type='hidden' value='".$theResults ."' id='theResults'/>";
in javascript file:
$(".results").load("get-results.php" + "?userClicked=" + var1 + var2 + "&prevresult=" + theResults,function() {
theresults=$("#theResults").val(); alert(theresults);
}));
Related
function submitID(){
// some codes working in here....
var text="A_1";
var name="test";
$.ajax({
url: 'callmethod.php',
type: 'post',
data: {'action':'methodname', 'text': text, 'name':name},
success: function(data, status) {
var results = JSON.parse(data);
for(var i = 0; i < results.length; i++){
var id= results[i]['ID'];
alert(id); --- I got the value of ID in here -- example output value : Hello
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
});
}
What I would like to do in here, I got the value of var id but I want to set as the PHP variable $valuephp= >>> id <<< how can I do for that? please help me to advice.
In short, its not possible, like that to set ajax response to php variable because
PHP runs - Server Side before page load and builds the page
JS (and thus AJAX) runs - Client Side AFTER the server gave your browser the page
So what you can do ?
You post data to your server with your ajax call, so in server side, you can set php variable.You can store this in a session variable if you need it later, or in the database.
You can store ajax result in php variable by embedding ajax result div into php tag.
Assign ajax response variable to js variable and then just assign it to your html div containing php variable as:
$('#result').text('test');
<?php
$result='<div id="result"></div>';
// Here you embed div in php tag and store in php varible
?>
In your ajax call, after success or error
<?php $variablephp = "<script>document.write(111)</script>" ?>
Now you can access that variable, make sure that variable actually used after ajax call
<?php echo $variablephp; ?>
I have a problem with jQuery to obtain each value from jSon string and modify a div or span or other id with value obtained from a jSon string.
At the start of each PHP file i have an SQL request generate an hidden input with a jSon string as value. This is for multilanguage for example in english the generated string is
<input type="hidden" id="page_json_language_home" value='{
"label_title":"My WebSite",
"label_settings":"Settings",
"label_subscription":"Subscription"
}' />
for french :
<input type="hidden" id="page_json_language_home" value='{
"label_title":"Mon site web",
"label_settings":"Parametres",
"label_subscription":"Abonnement"
}' />
this is work fine !
After that i have a javascript using jquery to match each label_xxx with value
i have many html code like this
<title id="label_title></title>
<div id="label_settings"></div>
or
<span id="label_subscription"></span>
This is my (partial) code in my javascript file i called to obtain the json string from hidden input :
var _getPageJsonLanguage = function(id) {
if (!id)
id = "page_json_language";
else
id = "page_json_language_" + id;
var json = $("#" + id).val();
var data = bsc.data.jsonParse(json);
return data;
};
This is work fine too !
The code in problem is :
data_language = bsc.page.getPageJsonLanguage("home");
var j = 0;
var language = [];
for (i in data_language) {
console.log("i in language = " + i);
language[j] = i;
console.log("language[j] = " + language[j]);
$("#" + i).html(language[j]);
j++;
}
The result can i obtain in browser 1) undefined for each label or 2) label_xxx for each label_xxx
I need help to access each value of each label_xxx .
I can't obtain the value, this is my last try....
I believe the problem is in your for in loop, you never actually grab the value, only the key:
for (i in data_language) {
console.log("i in language = " + i);
language[j] = data_language[i]; //changed this line to actually grab the value
console.log("language[j] = " + language[j]);
$("#" + i).html(language[j]);
j++;
}
If you are receiving undefined, it may be due to the JSON not being parsed correctly. Since your using jQuery, you can always run $.parseJSON(json) to be sure.
Fiddle accessing your JSON in a for in loop and logging: http://jsfiddle.net/tymeJV/CKBLc/1/
I hope this will work -
var data_language = JSON.parse($("#page_json_language_home").val());
var language = [];
var j = 0;
for (i in data_language) {
console.log("i in language = " + i);
language[j] = data_language[i];
console.log("language[j] = " + language[j]);
$("#" + i).html(language[j]);
j++;
}
Since I'm relativly new to the use of php and javascript I ran into this problem while trying to add multiple variables in a URL
I use the following script:
<script>
function refresh() {
var PCWDE = document.getElementById("PC");
var NMWDE = document.getElementById("naam");
var VNMWDE = document.getElementById("voornaam");
var ONDWDE = document.getElementById("onderneming");
var BTWWDE = document.getElementById("btwnummer");
var LNDWDE = document.getElementById("land");
this.document.location.href = "http://example.com/form.php?PCS=" + PCWDE.value "&nm=" + NMWDE.value "&vnm=" + VNMWDE.value "&ond=" + ONDWDE.value "&btw=" + BTWWDE.value "&lnd=" + LNDWDE.value;
}
</script>
That's beeing activated trough the following html code:
<?php
$pc = $_GET['PCS'];
echo '<input type="text" name="pc" id="PC" onblur="refresh()" value="'.$pc.'">'
?>
The main reason for the use of this html code was that I needed to execute a query without submitting the form, while still beeing able to hold the value of the text box even when the page would refresh. The above html code is used multiple times with the use of different ID's.
The problem I face while trying to do this is that my code only works when only adding 1 variable to the URL like so:
this.document.location.href = "http://example.com/form.php?PCS=" + PCWDE.value;
Otherwise it does not work. Either the 'onblur' event fails to work, or the script fails to run.
Is there a way to add the multiple variables to the URL in a similiar way to what i'm doing now?
You forgot plus signs. That's a syntax error and you should see the error message if you open the error console. (on firefox you press control-shift-j)
Shoule be:
this.document.location.href = "http://example.com/form.php?PCS=" + PCWDE.value + "&nm=" + NMWDE.value + "&vnm=" + VNMWDE.value + "&ond=" + ONDWDE.value + "&btw=" + BTWWDE.value + "&lnd=" + LNDWDE.value;
I have a php page which includes the following javascript:
<script>
$(document).ready(function(){
$('#search').hide();
});
$('#L1Locations').live('change',function(){
var htmlstring;
$selectedvalue = $('#L1Locations').val();
$.ajax({
url:"<?php echo site_url('switches/getbuildings/');?>" + "/" + $selectedvalue,
type:'GET',
dataType:'json',
success: function(returnDataFromController) {
alert('success');
var htmlstring;
htmlstring="<select name='L2Locations' id='L2Locations'>";
htmlstring = htmlstring + "<option value='all'>All</option>";
console.log(returnDataFromController);
var JSONdata=[returnDataFromController];
alert('string length is' + JSONdata.length);
if(JSONdata.length > 0)
{
for(var i=0;i<JSONdata.length;i++){
var obj = JSONdata[i];
for(var key in obj){
var locationkey = key;
var locationname = obj[key];
htmlstring = htmlstring + "<option value='" + locationkey + "'>" + locationname + "</option>";
}
}
$('#l2locations').html(htmlstring);
}
else
{
alert('i think undefined');
$('#l2locations').html('');
}
}
});
$('#search').show();
});
</script>
what i'm trying to accomplish is dynamically show a combo box if the variable "returnDataFromController" has any items.
But I think I have a bug with the line that checks JSONdata.length.
Regardless of whether or not the ajax call returns a populated array or an empty one, the length always shows a being 1. I think I'm confused as to what is counted when you ask for the length. Or maybe my dataType property is incorrect? I'm not sure.
In case it helps you, the "console.log(returnDataFromController)" line gives the following results when i do get data back from the ajax call (and hence when the combo should be created)
[16:28:09.904] ({'2.5':"Admin1", '2.10':"Admin2"}) # http://myserver/myapp/index.php/mycontroller/getbranches:98
In this scenario the combo box is displayed with the correct contents.
But in scenario where I'm returning an empty array, the combo box is also created. Here's what the console.log call dumps out:
[16:26:23.422] [] # http://myserver/myapp/index.php/mycontroller/getbranches:98
Can you tell me where I'm going wrong?
EDIT:
I realize that I'm treating my return data as an object - I think that's what I want because i'm getting back an array.
I guess I need to know how to properly check the length of an array in javascript. I thought it was just .length.
Thanks.
EDIT 2 :
Maybe I should just chagne the results my controller sends? Instead of returning an empty array, should I return false or NULL?
if (isset($buildingforbranch))
{
echo json_encode($buildingforbranch);
}
else
{
echo json_encode(false);
}
EDIT 3:
Based on the post found at Parse JSON in JavaScript?, I've changed the code in the "success" section of the ajax call to look like:
success: function(returnDataFromController) {
var htmlstring;
htmlstring="<select name='L2Locations' id='L2Locations'>";
htmlstring = htmlstring + "<option value='all'>All</option>";
console.log(returnDataFromController);
var JSONdata=returnDataFromController,
obj = JSON && JSON.parse(JSONdata) || $.parseJSON(JSONdata);
alert(obj);
}
But i'm getting an error message on
[18:34:52.826] SyntaxError: JSON.parse: unexpected character # http://myserver/myapp/index.php/controller/getbranches:102
Line 102 is:
obj = JSON && JSON.parse(JSONdata) || $.parseJSON(JSONdata);
The problem was that the data from the controller is malformed JSON.
Note the part of my post where I show the return data:
({'2.5':"Admin1", '2.10':"Admin2"})
The 2.5 should be in double quotes not single quotes.
I don't understand how / why this is happening but I will create another post to deal with that question. Thanks everyone.
I'm fetching a row of data from a mysql-server using php, then encode it to a json array. I then pull the information using the following PHP. The strange part is that if I send "vname" to it's own div, I get "NaN" as a result. If I display it in the first div, everything turns out fine. Any idea why? Btw, is it right of me to use .html to send to the div? I've tried .appendTo and .text with the same result.
<h3>Output: </h3>
<div id="output">Content1</div>
<div id="username">content2</div>
<script id="source" language="javascript" type="text/javascript">
$(function() {
$.ajax({
url: 'api.php',
dataType: 'json',
success: function(data) {
var id = data[0];
var vname = data[1];
var message = data[2];
var timestamp = data[3];
$('#output').html(+id + timestamp + message);
$('#username').html(+vname);
}
});
});
</script>
I;m going to guess its because of the first +. Javascript is trying to add nothing to all of the other stuff, which would output a NaN
$('#output').html(id +timestamp +message );
$('#username').html( vname );
In this case text() might be a better to use because there aren't any html elements in your strings, but it really doesn't matter.
+variable is shorthand for casting a variable to a number: Unary plus/minus (MDN)
var x = "5";
+x; //Gives you 5 as a number
x = "Hello";
+x; //Gives you NaN
You can use regular append.
$('#output').append(id + timestamp + message);
$('#username').append(vname);
$('#output').html(+id + timestamp + message);
$('#username').html(+vname);
These are probably your problem. The plus sign in front of the variables would throw an error. If you are trying to concatenate (add together) the existing the value and your response from the ajax change it to some thing like this:
$('#output').html($('#output').html() + id + timestamp + message);
$('#username').html($('#username').html + vname);