Reputation: 738
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);
?>
Upvotes: 0
Views: 6126
Reputation: 116
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);
Upvotes: 1
Reputation: 738
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);
Upvotes: 0
Reputation: 1635
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
Upvotes: 0
Reputation: 11431
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).
Upvotes: 0
Reputation: 10864
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
Upvotes: 1
Reputation: 24276
Your returning data is in the response
parameter. You have to echo
your data in PHP to get the results
Upvotes: 2