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

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

Related

Pass GET variable from URL to .js, and from the .js to .php

Hi I currently have a JS file being called to populate my html page with dynamic data. My JS file calls a PHP file to fetch stuff from my sqldb and my PHP file echos json_encode the stuff it got from the sqldb, which in turn is used to populate the html page.
My problem is that depending on what's in the url ie ?user=Bob, I want my js file to call the php file to search for Bob. Right now it searches for current user if ?user=xxxx is not specified. It seems the $GET['user'] is always null, thus it's not being passed because I suspect the JS file working as a middleman. Here are my code snippets:
My URL:
www.website.com/index.php?user=Bob
My HTML Code
<script type="text/javascript" src="js/get-data.js"></script>
My JavaScript
$(document).ready(function(){
$.ajax({
type: 'GET',
url: 'php/retrieve-db.php',
dataType: 'json',
success: function(response){
var name = response[0];
var location = response[1];
$('#name').html(name);
$('#location').val(location);
}
});
});
My PHP Code
$id;
if (isset($_GET["user"]))
{
$id = $_GET["user"];
}
else
{
$id = $_SESSION['loggedInUser'];
}
$query = "SELECT * FROM Persons WHERE User = '$user'";
if($result = mysqli_query($sqlconnection,$query))
{
$row = mysqli_fetch_row($result);
echo json_encode($row);
}
You need to specify the data attribute in your ajax call.
$.ajax({
type: 'GET',
data: $("#myForm").serialize(), //for example. You can change this to something relevant.
/*rest of the code*/
});
What this will do is prepare a GET request with the proper data, for example, http://path/to/backend/?key1=value1&key2=value2
I believe you want to do something like this
$(document).ready(function(){
$.ajax({
type: 'GET',
url: 'php/retrieve-db.php',
data: <?php echo json_encode($_GET); ?>,
dataType: 'json',
....
EDIT:
Thanks #Brad and #Ashwin Musjija for pointing out. I was focusing on answer too quickly that I overlook the possible non persistent XSS attack.

Retrieve PHP Variable via jQuery

I know this questions has been asked in various forms, but I've been unable to find a response that squares with what I'm trying to accomplish. Total amateur, so any additional pointers are appreciated.
The Task:
Use a form on page1 to post data to PHP file, which then searches the MySQL table for rows corresponding to the $_POST[]. Then, the PHP file echoes the result as JSON_encode($variable). From there, the PHP file redirects the user back to page1, which (in theory) has a JQuery script that calls the $variable from the PHP file and create html with the data.
The Code:
PHP
<?php
ob_start();
session_start();
session_save_path('path');
mysql_connect("", "", "")or die(); mysql_select_db("db")or die();
$pname = $_POST['country'];
$result = mysql_query("SELECT * FROM project WHERE name = '$pname'");
$array = mysql_fetch_row($result);
echo json_encode($array);
header("page1.html");
?>
html/jquery/ajax
<script type="text/javascript">// <![CDATA[
$(document).ready( function() {
$.ajax({
type: 'POST',
url: 'page.php',
data: '',
dataType: 'json',
cache: false,
success: function(result) {
$('#content1').html(data);
},
});
});
// ]]></script>
<div id="content1"></div>
The php script works and echoes the JSON encoded variable, but nothing on #content1...
I have a feeling either my code is wrong, or the data is lost while posting to the PHP file and then redirecting.
You're trying to append the variable data to the content but the variable is called result. Try this:
<script type="text/javascript">// <![CDATA[
$(document).ready( function() {
$.ajax({
type: 'POST',
url: 'page.php',
data: '',
dataType: 'json',
cache: false,
success: function(result) {
$('#content1').html(result);//<- this used to be $('#content1').html(data);
},
});
});
// ]]></script>
<div id="content1"></div>
Additionally, as many have pointed out you are simply outputting the json at the moment - there is nothing in place to generate the table.
Change $('#content1').html(data) to $('#content1').html(result);

Passing a variable returned by an ajax callback as argument to a PHP method

I just want to pass my variable data.company_name from callback function:
<script>
function AjaxInsert() {
var company_name = $("#company_name").val();
dataToSend = {};
dataToSend.company_name = company_name;
$.ajax({
url: 'insert.php',
data: dataToSend,
dataType: "json",
success : function(data) {
console.log("my variable: "+data.company_name);
}
});//ajax*/
}
</script>
,below in the same script into a PHP (PHPExcel) method:
<?php
$var_needed = 'I need that data.company_name here';
$objWorksheet->setCellValueByColumnAndRow(0,$num_rows+1,$var_needed);
?>
How can be this achieved?
The "same script" has been executed already, so you won't be able to interact with it anymore after page load.
You either want to manipulate your spreadsheet client side with a JS library, or to drop ajax and reload the whole page [and ruin your user experience by the way].
<?php
$var_needed = $_REQUEST['company_name'];
$objWorksheet->setCellValueByColumnAndRow(0,$num_rows+1,$var_needed);
?>
$objWorksheet->setCellValueByColumnAndRow(0,$num_rows+1,$_POST['company_name']);

PHP file_get_contents to use variables

I am trying to send the contents of javascript file using file_get_contents. The problem i'm having is the javascript contains some PHP variables:
<script>
jQuery('document').ready(function($){
$('a.ajax_link').click(function(){
$.ajax({
type: 'DELETE',
url: '/groups/$org_ID/leave/$member_ID',
success: function(data){
var data = $('<div>').html(data);
var msg1 = data.find('#msg1');
$('#data_box1').html(msg1).hide().fadeIn(500).delay(2000).fadeOut(500);
setTimeout('window.location.href =\"/groups/\"',3000);
}
});
});
});
</script>
Specifically, the url: line. That just stays as plain text and so my script fails. I now understand this is the behavior of file_get_contents but how can I go about doing this?
thanks!
Use output buffering and require:
$org_ID = 5;
$member_ID = 10;
ob_start();
require '/path/to/javascript_file.php';
$js_code = ob_get_clean();
Inside javascript file you'll have to use php tags:
url: '<?php echo "/groups/$org_ID/leave/$member_ID"; ?>'

Using Ajax to Post PHP variables to another file

I want to post the PHP variables $uid and $submissionid to the file fblike.php. Is the Ajax below formatted correctly to do this?
<?php
ob_start();
session_start();
$uid = $_SESSION['loginid'];
$submissionid = mysql_real_escape_string($_GET['submissionid']);
$_SESSION['submissionid'] = $submissionid;
?>
<head>
<script type='text/javascript' src='jquery.pack.js'></script>
<script type='text/javascript'>
$(function(){
$("a.connect_widget_like_button").live(function(){
$.ajax({
type: "POST",
data: "action=vote_up&uid="+$(this).attr("uid")"&submissionid="+$(this).attr("submissionid"),
url: "fblike.php",
});
});
});
</script>
</head>
You dont really want to use expando attributes if you dont have to, especially since thise are links... i would jsut do:
Like
then you can do a simple:
$("a.connect_widget_like_button").live('click', function(e){
e.preventDefault();
$.post($(this).attr('href'));
});
Now on the php side you need to be aware of where the values will be. If you pass the values as i have done in my example they will be in $_GET (even if its a POST request). If you pass them like you did in your original post then they will be in $_POST.
You need to send the data as an array/object. Something like this should do the trick.
$(function(){
$("a.connect_widget_like_button").live(function(){
$.ajax({
type: "POST",
data: {
action: "vote_up",
uid: $(this).attr('uid'),
submissionid: $(this).attr('submissionid')
},
url: "fblike.php"
});
});
});

Categories