Insert and call JS in PHP code - php

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);
}
});

Related

How to echo an ajax variable in PHP file

I am trying to send a variable from one PHP file to another PHP file and echo it:
<script>
$.ajax({
type: "POST",
url: 'AjaxCallTest.php',
data: ({Imgname:"13"}),
success: function() {
alert('form was submitted');
}
});
<script>
And then in the receiving PHP file (AjaxCallTest.php):
<?php
$temp = $_POST['Imgname'];
echo $temp;
?>
but AjaxCallTest file doesn't echo anything? I need to get this variable and echo it. Note that I've included jQuery library in my code but I didn't include it in AjaxCallTest.php.
replace this line data: ({Imgname:"13"}), with data: {"Imgname":"13"}
I tried this and it worked! Notice the closing <script> tag
I also added the return result to check the echo in 'AjaxCallTest.php'
<script>
$.ajax({
type: "POST",
url: 'AjaxCallTest.php',
data: ({Imgname:"13"}),
success: function(result) {
alert(result + ' form was submitted');
}
});
</script>
Your code worked fine for me. One error I could find is that you didnt closed the script tag correctly. close the script tag.
<script>
$.ajax({
type: "POST",
url: 'AjaxCallTest.php',
data: ({Imgname:"13"}),
success: function() {
alert('form was submitted');
}
});
<script>

Send values to PHP

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

Ajax - Can't get json data

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);

How to get json data and display in div using jquery

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>

jquery .load not loading immediately after loading data

I was wondering if this was making an asynchronous request...write now Im using:
<script type='text/javascript'>
$(document).ready(function() {
var ktitle = $('.hiddentwo').text();
$('div#tab2').load('morefour.php?title=' + encodeURIComponent(ktitle));
});
</script>
what Im doing though is adding text in the first, into the database, on the current php file (addtext.php). Im passing the Id of the current document to the morefour.php and that is loading the added text on the second tab...the thing is, Im having to refresh to see the content again. Im running on localhost btw.
For more clarity, Im running another jquery script that on clicks, retrieves this data to send it to a php file to enter into a database
$(".button").click(function() {
var content = $(this).siblings().outerHTML();
$.ajax({
async: false,
type: "POST",
url: "tosqltwo.php",
data: {
content: content
}
});
});
$(function(){ //shorthand of $(document).ready
$('div#tab2').html($.ajax({
type: "GET", //if you are doin $_GET['title'] in morefour.php
url: "morefour.php",
data : {title:ktitle},
dataType: 'html', //i am not sure about this part
async: false
}).responseText)
});
or you can try
$(function(){
$.ajax({
url : 'morefour.php',
data : {title:ktitle},
type:'GET',
dataType:'html',
success: function(data) {
$('div#tab2').html(data);
}
});
});
you can use $.ajax function with async to false.
$.ajax({
async: false,
url : 'morefour.php',
data : 'title=' + encodeURIComponent(ktitle),
success: function(data) {
$('div#tab2').html(data);
}
});

Categories