Pass PHP value to javascript using Ajax - php

I have a php code that provides the database values. I need those values in the javascript variable.
Javascript Code
<script src="http://code.jquery.com/jquery-1.8.0.js"></script>
<script type="text/javascript">
function text() {
var textVal=$("#busqueda_de_producto").val();
$.ajax(
{
type:"POST",
url:"index.php", //here goes your php script file where you want to pass value
data: textVal,
success:function(response)
{
// JAVSCRIPT VARIABLE = varable from PHP file.
}
});
return false;
}
</script>
PHP FILE CODE:
<?php
$q11 = "select * from sp_documentocompra_detalle where dcd_codigo".$_GET['codigo'];
$res11 = mysql_query($q11);
$row11 = mysql_fetch_array($res11);
?>

Your returning data is in the response parameter. You have to echo your data in PHP to get the results

Using JSON format is convenient
because of its key-value nature.
Use json_encode to convert PHP array to JSON.
echo the json_encoded variable
you will be able to receive that JSON response data through $.ajax

JavaScipt/HTML:
<script src="http://code.jquery.com/jquery-1.8.0.js"></script>
<script type="text/javascript">
function text()
{
var textVal=$("#busqueda_de_producto").val();
$.post('index.php', { codigo:textVal }, function(response) {
$('#output').html(response.FIELDNAME);
}, 'json');
return false;
}
</script>
<span id="output"></span>
PHP:
$q11 = "select * from sp_documentocompra_detalle where dcd_codigo='".mysql_escape_string($_POST['codigo'])."'";
$res11 = mysql_query($q11);
$row11 = mysql_fetch_array($res11);
echo json_encode($row11);

You aren't echoing anything in your PHP script.
Try altering your PHP to this:
<?php
$q11 = "select * from sp_documentocompra_detalle where dcd_codigo".$_GET['codigo'];
$res11 = mysql_query($q11);
$row11 = mysql_fetch_array($res11);
echo $row11; //This sends the array to the Ajax call. Make sure to only send what you want.
?>
Then in your Ajax call you can alert this by writing alert(response) in your success handler.
Tips
Send your data to the server as a URL serialised string : request=foo&bar=4. You can also try JSON if you fancy it.
Don't use mysql_* PHP functions as they are being deprecated. Try a search for PHP Data Objects (PDO).

i see lots of things that needs to be corrected
the data in your ajax do it this way data: {'codigo':textVal}, since you are using $_GET['codigo'], which leads to the second correction, you used type:"POST" so you must also access the $_POST variable and not the $_GET variable and lastly the target of your ajax does not display / return anything you either echo it or echo json_encode() it

The best solution is to use
echo json_encode("YOUR ARRAY/VALUE TO BE USED");
and then parse JSON in the javascript code as
obj = JSON.parse(response);

Related

set session from jquery to session in php

i have a page in php to execute query. when i need the parameter from another page with session using jquery. so, how to set session in php from session in jquery. please check my code and give me solution. thanks...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://code.ciphertrick.com/demo/jquerysession/js/jquerysession.js?d56ac9"></script>
<script>
$(document).ready(function(){
var sDecode = $.session.get("sesDecode");
alert(sDecode);
});
</script>
<?php
include('connection.php');
$content= ==> how to get " sDecode " ???
$upd = mysql_query("UPDATE t_modules set content='$content' where id_t_modules='3'") or die(mysql_error());
?>
You can use ajax to send parameter to a php file like this
$.ajax({
url: "connection.php",
data: "Session="+$.session.get("sesDecode"),
type: "POST",
dataType: 'json',
success: function (e) {
console.log(JSON.stringify(e));
},
error:function(e){
console.log(JSON.stringify(e));
}
});
Note that both solutions needs you to check the input since the user could potentially modify it.
Using Ajax
The best way to get sDecode is probably to send it via jQuery.post() (AJAX) to a PHP page that will register the session value (after doing the appropriate checks to it).
$.post('session.php', { d: sDecode }, function (response) {
alert(response);
});
and you get it in PHP via :
$sDecode = $_POST["d"]; // Please test the input here!
You might have to use .serialize() and then unserialize it in PHP depending on the content and how you treat it.
Using Redirection
You can simply redirect to a page and transmit it directly as a GET value:
window.location.href=”session.php?d="+sDecode;
Then on the session.php page you would read it using this code :
$sDecode = $_GET["d"]; // Please test the input here!
You can have PHP fill in the Javascript variable from the session variable.
<?php session_start(); ?>
<html>
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
var sDecode = <?php echo json_encode($_SESSION['sDecode']); ?>;
alert(sDecode);
</script>
PHP execute before Jquery so use ajax after get the parameter from session to do your query

How to make JQuery alert only one string from PHP?

I have a JQuery that creates an Ajax call to a PHP script. My PHP script echos 2 strings: check_1 and check_2. The alert() is displaying both the strings in the output. How to get only one string in the output?
PHP:
<?php
echo "check_1";
echo "check_2";
?>
JQuery:
$.get("check_ajax.php", function(data) {
alert(data);
});
send the server response as json ... and get it...
try this
jquery
$.get("check_ajax.php", function(data) {
alert(data.check_1); //alert the first object "check_1"
alert(data.check_2); //alert the second object "check_2"
},'JSON');
php
<?php
echo json_encode(array("check_1"=>"check_1","check_2"=>"check_2"));
?>
there is couple of ways to do this. one way is string manipulation and removing the text after the new line char of the first string. The other method is actually send your data from php to javascript using json. So in your php file you would create a data structure like an array.
<?php
$string = array("check_1", "check_2");
echo json_encode($string);
?>
in the javascript side then you can retrieve the first element from that json array.
$.get("check_ajax.php", function(data) {
alert(data[0]);
});
You can use like this : -
<?php
$html = "check_1";
$html1 = "check_2";
echo $html.'~~~'.$html1;
?>
JQuery:
$.get("check_ajax.php", function(data) {
var res = data.split('~~~');
alert(res[0]);
});
We have the same problem before, but what I do as an alternative solution was to have a conditional statement to separate multiple values returned by php
if(your condition here) {
echo "check_ 1";
} else {
echo "check_ 1";
}
Hope it helps :)
PHP:
<?php
$text = array("check_1", "check_2");
die(json_encode($text));
?>
jQuery:
$.get("check_ajax.php", function(data) {
var response = JSON.parse(data);
alert(response[0]); // for "check_1"
alert(response[1]); // for "check_2"
});

How can I pass a variable from PHP to javascript

I have a php page with
<?php echo $_SERVER['DOCUMENT_ROOT']?>
Then my javascript is
var data = "Not Set";
$.get("test.php",function(returnData,requestStatus,requestObject){
data = returnData;
alert(data);
});
If I navigate directly to the php page on the site, it displays the data that I need.
I just can't seem to get the data into my javascript.
Am I on the right track and if so where am I going wrong?
Or is there an easier way to get the full filepath when working with a server?
Currently if I run document.location.href in my javascript it returns .
http ://127.0.0.1/etc
The code below will work on ".php" file. NOT ON ".html" file.
You can use the php variable with echo in javascript. For example
alert('<?=$phpvariable?>');
or
alert('<?php echo $phpvariable ?>');
It seems you are overthinking this. There is hardly any need to use ajax, but of course you can and just append() the data from the ajax call to your $('body') and jquery will automatically execute things inside a <script> tag.
var serverRoot = '<?php echo $_SERVER['DOCUMENT_ROOT']?>';
Try following
Instead of GET send $.post request and file don't return any thing just write
$.post("Requestedfile.php",
{
data :data
},
function(data) {
if(data == false)
{
//do something
}
else
{
//do somthing
}
}
);

Passing php array as variables to javascript load url and back to php array?

I saw many examples related but I'm still confused. I'm using ajax (which I don't know much about) to get the results of a file updated every xxx seconds. It's working perfectly if I pass just one variable, but what is the best way if I need to pass an array from php through it?
Structure is simples:
show_results.php
<?php
include_once('modWhosonlineCustom.inc.php');
$document->addScript("http://code.jquery.com/jquery-latest.js");
$document->addScript("ajax.js");
$array_name = modWhosonlineCustom::getOnlineUserNames();//the array I need to pass to javascript variable
?>
<script>
var whosonline = '<?php echo "$array_name"; ?>';
</script>
<div id="results"></div>
Ajax code than would have more than one param to build in the url load:
ajax.js
$(document).ready(function() {
$("#results").load("response.php?array_name[param1]&array_name[param2]");
var refreshId = setInterval(function() {
$("#results").load("response.php?array_name[param1]&array_name[param2]&randval="+ Math.random());
}, 10000);
$.ajaxSetup({ cache: false });
});
And back to PHP response page, how could I use again the array params passed through url?
response.php
<?php
$names = $_GET['array_name'];
foreach ($names as $name) {
//do something
Any suggestions is really appreciated, thanks!
EDIT
Thanks guys, I think I'm the right way now, but ramains the problem to pass this array through a url in the javascript. Or maybe I'm not getting it in the right way in the php end callback file. I'll show you what a modifyed:
show_results.php
...
<?php
$names = modWhosonlineCustom::getOnlineUserNames();
?>
<script>
var whosonline = '<?php echo "json_encode($names)"; ?>';
</script>
ajax.js
$(document).ready(function() {
$("#atendentes").load("response.php?names=" + whosonline);
var refreshId = setInterval(function() {
$("#atendentes").load("response.php?names=" + whosonline + "&randval="+ Math.random());
}, 10000);
$.ajaxSetup({ cache: false });
});
response.php
$users = $_GET['names'];
$users = json_decode($users);
echo "user: $users";
$names = $users;
foreach ($names as $name) {
...
Here in the other side I'm getting: Warning: Invalid argument supplied for foreach() in response.php on line 33, and the echo is empty
What is missing?
To pass arrays/objects from PHP to JavaScript you may use the json_encode()/json_decode() functions.
Your code wouldn't work. If you have
$arr = array('a', 'b', 'c');
echo $arr;
you actually get
Array
as the output. Not the contents of the array. To "output" an array from PHP to JS, you have to convert it to native Javascript, which is where json_encode comes in:
<?php
$arr = array('a', 'b', 'c');
?>
var js_array = <?php echo json_encode($arr) ?>;
which will produce
var js_array = ["a","b","c"];
As a general rule, anytime you are using PHP to generate javascript code and are filling in Javascript variables with PHP values, you should use json_encode to ensure that you're generating valid Javascript. Any syntax errors and the whole Javascript code block is dead in the water once the client starts trying to execute it.

Pass JSON from php to javascript

I want to localize my webapp. Since localization through javascript only is not recommended I thought using php would be an alternative.
So with php I read a messages.json file that stores all localization data.
$json = file_get_contents("_locales/en/messages.json");
In the header of my webapp I generate some javascript with php according to the user's browser language.
echo "var localeObj = " . $json . ";";
So this is just a var that holds all data from the messages.json file that looks like that
{
"extTitle": {
"message": "Test1"
},
"extName":{
"message": "Test2"
}
}
Now I want to be able to access each item from the json like
var title = getItem("extTitle");
and it returns Test1. Any idea how to do that?
I am not very familar with json but if I just alert the localeObj it gives me just [object Object].
var getItem = function(item) {
return localObj[item].message;
};
You could always encapsulate your i18n strings too...
(function() {
var localObj = { ... };
window.getItem = function(item) {
return localObj[item].message;
};
})();
This way, no other variables can possibly clobber your localObj.
You use array syntax [], or dot syntax ., to access javascript object properties.
Example:
localeObj["extTitle"];
localeObj.extTitle;
I would recommend reading something like this to get more familier with JSON.
You can initialize javascript variable like this.
var json = eval(<? echo $json ?>);
alert(json.extTitle.message+ ' '+json.extName.message);
Inside messages.php:
<?php
header('Content-type:application/javascript');
$messages = array(
"yes"=>"hai",
"no"=>"iie"
);
$messages = json_encode($messages);
echo "window.messages = $messages";
?>
Inside index.html:
<html>
<body>
<script type="text/javascript" src="messages.php"></script>
<script type="text/javascript">
console.log(window.messages)
</script>
</body>
</html>
As long as you tell the browser to interpret the php file as a javascript file, you can echo anything you want.

Categories