How To Use Ajax To Get Data From Db And Display On Page
Solution 1:
First, you will find it helpful to review these simple examples about AJAX. Do not just read them, copy them to your server and make them work. Change a few names or values -- see how they work.
AJAX request callback using jQuery
Next, here is a post that gives an overview to how PHP / web page / AJAX all work together. Take a few minutes and read it carefully. See if you can follow the logic. I bet the lightbulb will come on for you.
PHP - Secure member-only pages with a login system
Make your code as standard as possible. Don't take any shortcuts. Use the full $.ajax()
structure, not the shortcuts of $.post()
or $.get()
(these are both shortcut forms of $.ajax()
. Don't skip anything. As you get better, you can start to take some shortcuts. But for now, make sure your AJAX code block looks like this:
var var_value = $('#someElement').val();
$.ajax({
type: 'post',
url: 'your_ajax_processor.php',
data: 'post_var_name=' +var_value,
success: function(dataz){
if (dataz.length) alert(dataz);
$('body').append(dataz);
}
});
In your PHP, you will receive the value you posted in the $_POST
array variable. If, in AJAX, you named your variable post_var_name
(as we did in the example above), then that is how you access the contents:
$myVar = $_POST['post_var_name'];
When you are having trouble, a great idea is to put in some tests. (1) On the PHP side, comment out everything and at the top put in an echo command, like:
<?phpecho'I got here';
die();
Back on the web page, in the AJAX success function, just alert what you get:
success: function(d){
alert(d);
}
At that point, you know two things:
Your AJAX -to- PHP communications are working, and
You see what value got passed over to PHP.
Then, you might do something like this
js/jQuery:
var var_value = $('#someElement').val();
$.ajax({
type: 'post',
url: 'your_ajax_processor.php',
data: 'post_var_name=' +var_value,
success: function(dataz){
if (dataz.length) alert(dataz);
$('body').append(dataz);
}
});
PHP:
<?php$myVar = $_POST['post_var_name'];
//Now you can do something with variable `$myVar`, such as:$out = '
<div class="red-background"> '.$myVar.' </div>
';
//This content is received in the AJAX code block using the variable name you specified: "dataz"echo$out;
Solution 2:
is this in french? lol, luckily it's still all code. try this:
inside of your success(datos1) function replace datos1 with datos1.data. Ajax gives you the whole response, you just want the data from the response generally.
success:function(datos1){
console.log(datos1);
console.log(datos1.data);
for(x = 0;x<=datos1.data.length;x++){
//$("#PAIS").append("<option value='"+datos.data[x].id_pais+"'>"+datos.data[x].pais+"</option>");
$("#REGION").append(new Option( datos.data[x].region, datos.data[x].id_region));
}
Post a Comment for "How To Use Ajax To Get Data From Db And Display On Page"