Getting a PHP variable in jQuery - php

So I have this:
<?php
echo '
<script>
$(function(){
$("a#yeah").click(function(){
$.ajax({
url: "ajax.php?action=yeah&id='.$id.'",
success: function(html){
$("a#yeah").html("your cool")
}
})
})
})</script>';
?>
basically I am using the PHP variable $id which can be find in the document, how could I get this same variable but without echoing the jQuery(so I could keep my editor syntax highlight in the JavaScript part)?

never echo any client side code - just type it as is.
PHP especially good in this http://www.php.net/manual/en/language.basic-syntax.phpmode.php
<script>
$(function(){
$("a#yeah").click(function(){
$.ajax({
url: "ajax.php?action=yeah&id=<?php echo $id?>",
success: function(html){
$("a#yeah").html("your cool")
}
})
})
})</script>

You can add the php inline like:
<script> var yourVariable = '<?php echo $phpVar; ?>'; </script>

Just echo around the variable, as that appears to be the only piece requiring processing:
...stuff...
url: "ajax.php?action=yeah&id=<?=$id?>",
...more stuff...
If your server doesn't have short_open_tag enabled, then <?php echo $id; ?>

Related

How can I set an ajax variable equal to a php variable?

I'm looking for some guidance on how if I have an already existing php variable, that is not a web element, just a string, how can I pass that as a variable to ajax?
here is a santized snippet of what I'm doing.
I want to be able to pass $my_php_var to ajax.
<?php
$my_php_var = "foo";
?>
$(document).on('click', '#btn_add', function(){
var my_php_var = $my_php_var;
$.ajax({
url:"directory/script.php"),
method:"POST",
data:{my_php_var:my_php_var},
dataType:"text",
success:function(data);
{
alert(data);
}
})
What you can do is, print it there inside another PHP tag:
<?php
$my_php_var = "foo";
?>
$(document).on('click', '#btn_add', function(){
$.ajax({
url:"directory/script.php"),
method:"POST",
data:{my_php_var:<?=$my_php_var?>},
dataType:"text",
success:function(data);
{
alert(data);
}
})
Where <?=$var?> is short version of <?php echo $var; ?>.

Jquery Ajax is neither passing data to PHP nor returning anything on success()

I am trying to pass the jquery variable to PHP with Ajax but the receiving php file is returning error " Undefined index" Code is:
<div class="img">
<a href="ss.php">
<img id="theme_bg" src="images/themes/theme1.jpg">
</a></div>
$(document).ready(function($){
$('.img').on('click','img',function(){
var imgsrc = $(this).attr('src');
alert(imgsrc); //this is returning the img src correctly
$.ajax({
type: "POST",
url: 'ss.php',
dataType: 'json',
data: {imgpath:imgsrc },
success: function(response) {
content.html(response); // i tried alert here but it shows nothing
}
});
});});
receiving PHP file code is:
<?php
$imagepath = $_POST['imgpath'];
echo $imagepath;
?>
I tried it with GET also but same error.. I haven't used Ajax before this. I checked other responses here on similar questions but none of them was has anything majorly different from mine code. so dont know what's the error..
updated Screen shots of code both files
updated screen shots of output
You have dataType set to json
so PHP should php <?php echo json_encode([$imagepath])
The better solution would be dataType: text instead of JSON
Note that in $.ajax the dataType is for response not request
Check $.ajax manual http://api.jquery.com/jquery.ajax/
Why you wrote ss.php in anchor you dont need that that's why it redirecting ss.php on click and getting error undefined index.
Your html code should be like this:
<form id="myForm" method="post" action="ss.php">
<div class="img">
<img id="theme_bg" src="images/themes/theme1.jpg">
<input name="imgpath" id="imgpath" type="hidden"/>
</div>
</form>
Jquery code:
$(document).ready(function ($) {
$('.img').on('click', 'img', function () {
var imgsrc = $(this).attr('src');
$("#imgpath").val(imgsrc); //this is returning the img src correctly
$("#myForm").submit();
});
});
ss.php
<?php
$imagepath = $_POST['imgpath'];
echo $imagepath;
?>
Try this one. Add this one to document.ready function
$(".img").click(function() {
$.ajax({
type: "POST",
url: "ss.php",
data: {imgpath:imgsrc},
dataType: "text",
cache:false,
success:
function(data){
alert(data);
}
});// you have missed this bracket
return false;
});

PHP json_encode data to jQuery for AJAX call

I am having a problem in using json_encode function.I am putting a simplified version of the problem here.
Here is the file containing php and jquery code.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script>
<?php
$test = "xxxxxxx";
?>
<p onclick="testAjax()">Click here</p>
<script>
var sendbody;
function testAjax(){
sendbody = "<?php echo json_encode($test); ?>";
$.ajax({
type: 'POST',
cache:false,
url: 'testAjaxCall.php',
data: {sendbody:sendbody},
success:function(data){
alert("1");
},
error:function(data){
alert("0");
}
});
}
</script>
And the ajax file simply contains
<?php
echo "testAjax";
?>
When I use json_encode function, the jquery code written after using the json_encode function stops working and the ajax function shows neither the success message nor the error message.
However if I write it as
sendbody = "<?php echo $test; ?>";
In this case the jquery code below this line works and shows success message.
When using json_encode, you don't have to quote the result, it's already quoted.
So change
sendbody = "<?php echo json_encode($test); ?>";
to
sendbody = <?php echo json_encode($test); ?>;
Otherwise you got:
// this cause syntax error
sendbody = ""xxxxxxx"";
First of all whenever you are expecting JSON to be returned to your AJAX call you have to tell it that by setting dataType: 'json', if not it tries to process it as text and obviously fails (your call is a success but the processing of the response isn't). The next best thing to do is use console.log(data) to get a better understanding of the response.

Load php dynamically from a dynamic javascript

How can I load my php on my domain using my javascript that was loaded dynamically.
my sample code
sample.html(Client-side)
<div onClick = "getThis()"></div>
my.js(Client-side)
function getThis(){
var url = "http://www.sampledomain.com/test.js"
var script = document.createElement('script');
script.src = url;
document.head.appendChild(script);
}
test.js(Server-side)
$.get("index.php", function(data) {
alert(data);
});
index.php(Server-side)
<?php
$_SESSION['user'] = "rob098";
?>
<script>
var data = '<?php echo json_encode($_SESSION['user']) ?>';
</script>
but it doesn't alert any.
Use ajax and json:
sample.html
<div onClick = "getThis()"></div>
my.js (inside sample.html)
function getThis() {
$.ajax({
url: '/test.php',
dataType: 'json',
success: function(data){
alert(data.user); //should alert rob098
},
});
}
test.php
header('Content-type: application/json');
echo json_encode(array("user" => "rob098"));
you have to append your js file to this
$(document).ready(function(){
$.get("index.php", function(data) {
alert(data);
});
});
so when script file loaded it will execute code inside jQuery ready function
I think you are using jquery $.get() the wrong way. Well I've never seen used that way at least, so you need to change your index.php to this:
<?php
$_SESSION['user'] = "rob098";
echo json_encode($_SESSION['user']);
header('Content-type: application/json');
?>
Let me know if I helped.

How do I add a php variable to this jquery url setting?

I'm trying to make the URL in the following example contain a php variable like this:
http://api.crunchbase.com/v/1/company/$company.js
This is my jquery code:
$.ajax({
url: "http://api.crunchbase.com/v/1/company/airbnb.js",
dataType: 'jsonp',
success: function(results){
var number_of_employees = results.number_of_employees;
}
What do I need to do to achieve this?
Thanks!
You'll need to output the variable as JavaScript from PHP at some point in the script. This can be done quite easily using json_encode:
var company = <?php echo json_encode($company) ?>;
Note that this will have to be placed in a file that is actually executed by PHP, rather than an inert .js file. One way to achieve this is to put it in an inline <script> in the HTML in your PHP template; e.g.
<script type="text/javascript">
var company = <?php echo json_encode($company) ?>;
</script>
Try this:
<script type="text/javascript">
var company = <?php echo json_encode($company); ?>;
alert(company);
</script>
You're setting the company variable with the output of $company, you can then use this variable however you please in JavaScript.
$.ajax({
url: "http://api.crunchbase.com/v/1/company/" + company + ".js",
dataType: 'jsonp',
success: function(results){
var number_of_employees = results.number_of_employees;
}
Can you try this, assuming you have the company name in the php $company variable:
$.ajax({
url: "http://api.crunchbase.com/v/1/company/<?php echo $company ?>.js",
dataType: 'jsonp',
success: function(results){
var number_of_employees = results.number_of_employees;
}

Categories