I'm quite a beginner in ajax technology. I have a php for execute a mysql_query and I would like to use the result on the client side.
My database.php:
$q=mysql_query("SELECT name FROM customers");
$res=mysql_fetch_array($q);
echo json_encode($res);
and my client.php
<div id="output">this element will be accessed by jquery and this text replaced </div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
$.ajax({
url: 'database.php', //the script to call to get data
data: "",
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var name = data[0];
$('#output').html("<b>id: </b>"+name);
}
});
});
</script>
This is from some tutorial I've found. And as I saw the database.php works. It prints right data, but in the client.php I can't get anything. What could be the problem?
---------EDITED---------
So, seems like on the web server runs php 4.4.7 and looks like json_encode() function does not wokrs because of that. I' ve found a "solution". I include upgrade.php, which implemets new methods for older versions of php, as far as i understands.
here is the webste of it http://include-once.org/p/upgradephp/
I can't upgrade php version so could this be a good solution? At the moment it does not works
First try to pring or alert your value.. if it is coming do according to your value u got..
<div id="output">this element will be accessed by jquery and this text replaced </div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
$.ajax({
url: 'database.php', //the script to call to get data
data: "",
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
alert(data); // check data value is coming or not..
var name = data[0];
$('#output').html("<b>id: </b>"+name);
}
});
});
</script>
check its printing value for you or not...
$.getJSON("database.php",function(data){
var entries = data;
$.each(entries,function(index,entry){
//do stuff with json entry here
});
});
$.ajax({
url: '/database.php', //Correct path.
//data: "",
type : 'Get',
dataType: 'json',
success: function(data)
{
alert(JSON.stringify(data));
var name = data[0];
$('#output').html("<b>id: </b>"+name);
}
});
Properly be so:
database.php
if (isset($_POST['getData'])) {
$q=mysql_query("SELECT name FROM customers");
$res=mysql_fetch_array($q);
echo json_encode($res);
die();
}
client.php
<div id="output">this element will be accessed by jquery and this text replaced </div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
$.ajax({
url: 'database.php', //the script to call to get data
type: "post",
data: { getData: true },
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var name = data[0];
$('#output').html("<b>id: </b>"+name);
}
});
});
</script>
Use this code in database.php
$q=mysql_query("SELECT name FROM customers");
while($res=mysql_fetch_array($q))
{
$a[]=$res['name'];
}
echo json_encode($a);
Related
I create the table and use ajax to pass data.
This is my ajax part, I put the parameter in URL, but php code doesn't read it.
$.ajax({
type:"POST",
url:"system_setting.php?p=add",
data:"username="+username+"&password="+password+"&nickname="+nickname+"&authority="+authority,
success:function(data){
viewData();
}
});
I use $page=isset($_GET['p'])?$_GET['p']:''; to judgment parameter, but it doesn't read. Please teach me how should I do, thank you.
Use POST instead and add p=add in data instead url
$.ajax({
type:"POST",
url:"system_setting.php",
data:"p=add&username="+username+"&password="+password+"&nickname="+nickname+"&authority="+authority,
success:function(data){
viewData();
}
});
And in php
$page=isset($_POST['p'])?$_POST['p']:'';
Give this a try:
var data = {};
data.username = username;
data.password = password;
data.nickname = nickname;
data.authority = authority;
data.p = “add”;
$.ajax({
type:"POST",
url:"system_setting.php",
data: data
}).done(function(data){
viewData();
});
Then when you need the data uses $_POST[] e.g. $_POST[‘p’]
Try this,ajax parameter "method" is used for POST and GET.
$.ajax({
method: "POST",
url: "system_setting.php",
data: { p:"add", username: "unsername", password: "password", nickname: "nickname", authority:"authority" },
success:function(data){
alert(data);
}
});
You have to use only POST or only GET.
Working example:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var username="username";
var password="password";
var nickname="nickname";
var authority="authority";
$.ajax({
type:"POST",
url:"system_setting.php",
data:"p=add&username="+username+"&password="+password+"&nickname="+nickname+"&authority="+authority,
success:function(data){
alert(data);
}
});
</script>
In system_setting.php
$page=isset($_POST['p'])?$_POST['p']:'';
echo $page;
I have a button within my HTML that, when you click it, I need to have it run a query in a PHP file which would then echo the results.
I've tried the following, however, when I click the button, it does nothing. What's wrong?
HTML/Ajax:
<?php
$reply_id = 15;
?>
<html>
<body>
<center><a class="btn show-more">Show more comments</a></center>
<div id="resultcomments"></div>
<script type="text/javascript">
var id = $reply_id;
$(document).ready(function() {
$(".show-more").click(function() {
$.ajax({
url: 'assets/misc/test.php',
type: "POST",
data: ({id_variable: id}),
function(data) {
$("#resultcomments").html(data);
}
});
});
});
</script>
</body>
</html>
PHP (located in assets/misc/test.php):
<?php
$replyid= $_POST['id_variable'];
echo $replyid;
// query would go here
?>
since $reply_id is PHP variable, for using it inside javascript you need to do like:
var id = <?php echo $reply_id; ?>;
....
and change:
data: ({id_variable: id})
to
data: {id_variable: id}
like:
$.ajax({
url: 'assets/misc/test.php',
type: "POST",
data: {id_variable: id},
success: function(data) {
$("#resultcomments").html(data);
}
});
You're not assigning your AJAX success function to a key, so I don't think it's ever firing. (You could try a console.log() or a debugger to check.) Try this instead:
$.ajax({
url: 'assets/misc/test.php',
type: "POST",
data: {id_variable: id}
}).done(function (data) {
$("#resultcomments").html(data);
});
Try this in javascript
var id = <?php echo $reply_id; ?>;
No brackets needed for data attribute in ajax,
data: {id_variable: id},
Try this for data attribute
Let's say .. I have the following script in my controller:
$result= array("Name"=>Charlie Sheen, "Age"=>30);
echo josn_encode($result);
And in my view file I have the following java script. Now could you please tell me what exactly to write in the success function of the script below in order to get the "Name" and "Age" displayed in two different divs inside body tag? I have found some tutorials on this but all those are very confusing to me. Could you please kindly help?
Thanks in Advance :)
<script type="text/javascript">
$(function(){ // added
$('a.read').click(function(){
var a_href = $(this).attr('href');
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>batch/get_info",
data: "id="+a_href,
success: function(server_response){
//What exactly to write here
}
}); //$.ajax ends here
return false
});//.click function ends here
}); // function ends here
</script>
Make sure you spell you json_encode function correctly.
Your html should look like this:
<head>
<script type="text/javascript">
$(function(){ // added
$('a.read').click(function(){
var a_href = $(this).attr('href');
$.ajax({
dataType : 'json', //You need to declare data type
type: "POST",
url: "<?php echo base_url(); ?>batch/get_info",
data: "id="+a_href,
success: function(server_response){
$( '#name' ).text( server_response.Name );
$( '#age' ).text( server_response.Age);
}
}); //$.ajax ends here
return false
});//.click function ends here
}); // function ends here
</script>
</head>
<body>
<div id='name'></div>
<div id='age'></div>
</body>
First of all, you should set the dataType. It should have the value 'json'. As for accessing it, you just access it as you would any other JavaScript object:
<script type="text/javascript">
$(function() {
$('a.read').click(function() {
var a_href = $(this).attr('href');
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>batch/get_info",
data: "id=" + a_href,
dataType: 'json',
success: function(result) {
alert(result.Name); // Charlie Sheen
}
});
return false;
});
});
</script>
I use old CMS and one of the modules that I want to insert a system of voting +1 or - 1.
The problem is that the module is written in PHP and does not work call the JS. Maybe I'm doing something wrong.
I tried to change the path - it is useless ... Direct call script "modules/Forum/down_vote.php" protected server.
Initialize jQuery and I need a function in PHP:
print ("<script type=\"text/javascript\" src=\"modules/Forum/jquery.js\"></script>
<script type=\"text/javascript\">
$(function() {
$('.vote').click(function() {
var id = $(this).attr(\"id\");
var name = $(this).attr(\"name\");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='down')
{
$(this).fadeIn(200).html('<img src=\"modules/Forum/dot.gif\" align=\"absmiddle\">');
$.ajax({type: \"POST\", url: \"modules/Forum/down_vote.php\", data: dataString, cache: false, success: function(html)
{ parent.html(html);}
});
}
else
{
$(this).fadeIn(200).html('<img src=\"modules/Forum/dot.gif\" align=\"absmiddle\">');
$.ajax({type: \"POST\", url: \"modules/Forum/up_vote.php\", data: dataString, cache: false, success: function(html)
{ parent.html(html);
} });
}
return false;
});
});
</script>");
Vote buttons:
echo "<div class=\"box1\"><div class=\"up\">".$up."</div>"
."<div class=\"down\">".$down."</div></div>\n";
1.- Seems that you really don't need print all that js code. This will work the same:
<?php
// php code
?>
<script type="text/javascript" src="modules/Forum/jquery.js"></script>
<script type="text/javascript">
$(function() {
// ...
});
</script>
<?php
// php code
?>
If you need satisfy some condition to write/run this code do it like this:
<?php
// php code
if ($condition) : // start js code
?>
<script type="text/javascript" src="modules/Forum/jquery.js"></script>
<script type="text/javascript">
$(function() {
// ...
});
</script>
<?php
endif; // end js code
// php code
?>
2.- Apparently your jquery code is right. Sure that your CMS provides a way to get the URL of your site. Something like site_url()in codeigniter or wordpress. I suggest you use it to determine $path_to_your_modules in your AJAX call.
$.ajax({
type: "POST",
url: "<?php echo $path_to_your_modules; ?>/modules/Forum/down_vote.php",
data: dataString,
cache: false,
dataType : "html", // add this to format as html
success: function(html){
parent.html(html);
}
});
index.html
<html>
<head>
</head>
<body>
<input type="text" id="inputtext"><input type="button" value="submit "id="submit">
<br>
<div id="response">
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="thescript.js"></script>
</body>
</html>
thescript.js
$(document).ready(function(){
$("#submit").click(function(){
var dataString = $("#inputtext").val();
$.ajax({
type: "POST",
url: "greet.php",
data: dataString,
success: function(){
$("#response").load("greet.php");
}
});
});
});
greet.php
<?PHP
print "hello " . $_POST['dataString'];
?>
The value that was entered in the textfield should show when the greet.php is loaded. not sure why it won't work
I think it can easier:
$("#submit").click(function()
{
var dataString = $("#inputtext").val();
$.ajax({
type: "POST",
url: "greet.php",
data: "dataString=" + dataString,
success: function(result){
$("#response").html(result);
}
});
});
And for php:
<?PHP
if(isset($_POST["dataString"]))
{
echo "hello " . $_POST['dataString'];
}
?>
I don't think you've got your jQuery .ajax call right. From the jQuery documentation:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
You want to be passing params as your data, in key/value format, rather than just the data, That way you can access it in your php as 'dataString' is to pass data: "dataString=" + dataString instead.
$.ajax returns the "hello" already. however while your page receives it, it queries "greet.php" again.
$.ajax({
type: "POST",
url: "greet.php",
data: dataString,
success: function (response) {
$("#response").append(response); // or .html(response)
}
});
or better: use .post();
$.post("greet.php", dataString, function (response) {
$("#response").append(response); // or .html(response)
});
finally, is your submit button is in a form, and you handle the click event, you shoudld prevent the form to submit on click if you want to stay on the page and not reload it.
$("#submit").click(function(event) {
event.preventDefault();
// stuff
return false;
});
$(document).ready(function(){
$("#submit").click(function(){
var dataString = $("#inputtext").val();
$("#response").load("greet.php"+ dataString );
});
});
Try this;
$("#response").load("greet.php", {dataString : dataString});