Actually i've used this script to get the profile picture of instagram user
<script src="http://codeorigin.jquery.com/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
var user_id = <? echo $page_id; ?>;
var url = "https://api.instagram.com/v1/users/"+user_id+"?client_id=775829274b6f48c1ac2bf218dda60e16&callback=?";
$.getJSON(url, function(data) {
$("body").append("<img src='"+data.data.profile_picture+"' />");
}
);
</script>
The Output of this script is 100% what i need.
All i need now is to take the image link to a PHP variable which is (+data.data.profile_picture+)
if tried to reload the same page with + ?link="+data.data.profile_picture+"
so i can grab it with $_GET['link']
Like this:
window.location.href = location.href + '?link="+data.data.profile_picture+";
but it doesn't .. What should i do to pass this javascript variable to a PHP variable.
Try This
window.location.href = location.href + '?link='+data.data.profile_picture;
You need to send your data to the PHP, and the simplest way would be using jQuery.ajax().
var picture = data.data.profile_picture;
$("body").append("<img src='"+picture+"' />");
$.ajax({
url: "http://example.com/webservices/getProfilePicture.php",
type: "POST",
data: {
'profile_picture': picture
},
success: function () {
console.log('Success!');
// Place eventual post-treatment here
},
error: function () {
console.log('Error..');
// Place eventual error-handling / debugging here
}
}
);
});
Then in PHP you can access it with this:
<?php $profile_picture = $_REQUEST['profile_picture']; ?>
Related
I want to develop a Wordpress plugin. So, I want to call Ajax function when I click on button in my php code.
This is my php code:
function unilang_translation_page() {
echo '<div class="wrap"><h1>Translations of strings</h1> </div>';
$unilang_table_strings = new Unilang_Table_Strings;
$unilang_table_strings->prepare_items();
$unilang_table_strings->display();
$_SESSION['store_table_strings'] = serialize( $unilang_table_strings );
echo "<a type='button' class=\"button button-primary\" onClick=\"Utility.saveStringTranslations();\">Submit Changes</a>";
}
And this is my javascript file:
var Utility = {
saveStringTranslations: function() {
$.ajax({
type: "POST",
url: "/unilang/php/unilang-save-string-translations.php",
success: function(data) {
alert(data);
},
error: function(error) {
alert(error);
}
})
}
}
When I click on the button the browser console returns this:
I tried to change path but it doesn't works.
How can I set my plugin path in the URL?
Try declaring a JavaScript variable in your plugin PHP file like below
<script> var plugin_url = '<?php echo plugins_url( '/unilang/php/unilang-save-string-translations.php', __FILE__ ) ?>'; </script>
and call the plugin_url variable in the AJAX URL path - url: plugin_url + "/unilang/php/unilang-save-string-translations.php".
Hope this helps and you can read more here - https://codex.wordpress.org/Function_Reference/plugins_url.
I am having trouble passing a Javascript array to a PHP array on the same page when the submit button is pressed. I have seen discussion of JSON.stringify and json_encode on other posts, but I am not sure how to use those functions with my code.
JS:
<script>
var kegs = [];
var textarea = document.getElementById("your_textarea");
$("#kegId").on('keyup', function (e) {
if (e.keyCode == 13) {
kegs.push($(this).val());
$("#kegId").val("");
textarea.value = kegs.join("\n");
};
});
</script>
PHP:
if (!isset($_POST['btn-addkegs'])) {
//I want to set the Javascript array 'kegs' to a php variable here
Using Ajax will do it for you! I wrote this code that sends an array to PHP on the same page. Once you get the array in PHP you can do whatever you want with it :).Just copy and paste this file and called it index.php to see the result. This will totally help you!
<?php
$data = array();
if(isset($_POST['myArray']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH'])){
$data = 'You array is: ' . $_POST['myArray'];
echo json_encode($data);
die();
}
?>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div id = "random"></div>
<script type = "text/javascript">
$(document).ready(function() {
var arr = [2,4,5,6,7];
var myArray = JSON.stringify(arr);
$.ajax({
url: "index.php",
method: "POST",
dataType: "json",
data: {myArray: myArray},
success: function (result) {
alert("result: " + result);
console.log(result);
$("#random").html(result);
}
});
});
</script>
</body>
</html>
This can be achieved by using ajax(), its syntax is:
$.ajax({
url: 'process.php', // file where data processing is done
type: 'POST',
data: {
var1 :val1,
var2 :val2
// parameter set
},
success: function(response){ // response from process.php
// do your stuff here
}
});
Read more about ajax
As you are using the jquery
var jsArray = makeJavascriptArrayhere //
$.ajax({
url: urlToPhpFile, // file where data processing is done
type: Method,
data:jsArray,
success: function(response){ // response from process.php
// do your stuff here
}
});
now in your php file
var_dump($_POST); //see on network liner tabs
I use this button in jason.
<button id="bid" type="button" class="button" onclick="connect()">Save</button>
It show altert when I use alert after document.getElementById. But it not works in ajax function. Here is my connect function
function connect()
{
var BID = document.getElementById('BID').value;
var REF = document.getElementById('ref_po').value;
var POU = document.getElementById('po_units').value;
//**alert(BID + REF + POU);**
var url ='<?php echo base_url()."index.php/main/transacIn/" ?>';
$.ajax({
type: "POST",
url: url,
data: 'BID='+BID +'&REF='+REF +'&POU='+POU,
success: function(data) {
//$("#bid").hide();
alert(BID);
}
});
}
alert(BID + REF + POU); this alert works but not works alert in success. And it don't sent any data into controller. Help me about it. Thanks in advance.
try this
function connect()
{
var BID = document.getElementById('BID').value;
var REF = document.getElementById('ref_po').value;
var POU = document.getElementById('po_units').value;
var site_url = document.getElementById('site_url').value;
var url = site_url+'main/transacIn';
$.ajax({
type: "POST",
url: url,
data: {
BID : BID ,
REF: REF,
POU:POU
},
success: function(data) {
//$("#bid").hide();
alert(BID);
},
error: function(err) {
console.log(err);
}
});
}
you should a hidden field in your corresponding page <input id="site_url" type="hidden" value="<?php echo site_url(); ?>"/>
You cannot inject the php syntax into javascript file. Either you define the script in codeigniter template file as
<script type="text/javascript">
// Your javascript function
</script>
...or you can define a javascript variable in the template file which actually get the path to your controller:
var url = <?php echo base_url()."index.php/main/transacIn/" ?>';
Then on your javascript file on ajax post you are pointing to the variable defined in the template file:
$.ajax({
type: "POST",
url: url,
data: 'BID='+BID +'&REF='+REF +'&POU='+POU,
success: function(data) {
//$("#bid").hide();
alert(BID);
}
});
Hope you got the idea.
Anyway you need to be careful defining global variables. It's a good practice to guard the variables by using namespaces.
Try this solution. It will work:
$.post(url , {BID: BID, REF: REF, POU:POU },
function(data){
alert(BID);
});
JavaScript
function calcPrimesLoop() {
var primes = document.getElementById('primes');
primes.appendChild(document.createTextNode('\n'+this.prime.nextPrime()));
$.ajax({
url: "/test.php",
type: "post",
data: {prime: this.prime.nextPrime()},
success: function(data) {
}
});
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
}
Php
<?php
$content = $_POST['prime'];
$fn = "content.txt";
$content = stripslashes('prime'"\n");
$fp = fopen($fn,"a+") or die ("Error opening file in write mode!");
fputs($fp,$content);
fclose($fp) or die ("Error closing file!");
?>
So this is all the relevant scripting I think. I have a script that can get prime numbers and it works perfectly. But now I want to record these numbers on a text file. This is how I am trying to do it but I am having no success at all. Thank you. The issue is the numbers aren't being recorded.
I added an alert the Ajax is working. But when I add a form to the php script and submit it that works. So the ajax and php scripts are not working together as such.
You should read up about AJAX and see how you can pass information to a serverside page using Javascript and retrieve the return value.
http://www.w3schools.com/ajax/default.asp
https://www.youtube.com/watch?v=qqRiDlm-SnY
With ajax and jQuery it is actually simple.
function calcPrimesLoop() {
var primes = document.getElementById('primes');
primes.appendChild(document.createTextNode('\n'+this.prime.nextPrime()));
$.ajax({
url: "myScript.php", // URL of your php script
type: "post",
data: {prime: this.prime.nextPrime()},
success: function(data) {
alert("success");
}
});
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
}
myScript.php :
<?php
$content = $_POST['prime'];
...
You should definately look for Asynchronous JavaScript and XML.
You can choose between using AJAX with a Javascript function, or simplify your life with jQuery
Here is a sample:
//STEP ONE: INCLUDE THE LAST VERSION OF JQUERY
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
//STEP TWO, GET YOUR FUNCTION TO WORK:
function sendVariableTo(variable,url) {
$.ajax({
url:url, //Or whatever.php
type: "GET", //OR POST
data: { myVar: variable}, //On php page, get it like $_REQUEST['myVar'];
success:function(result){
//If the request was ok, then...
alert(result) //Result variable is the php page
//output (If you echo "hello" this alert would give you hello..)
},
});
}
Hope this helped, bye !
I would like to send 'ID' to JS function then send the same ID again from JS function to php function.
Please tell me what is the wrong in my code!
<script type="text/javascript">
function deleteclient(ID){ //I receive the ID correctly until now!
var x = "<?php deleteclient11('ID');?>";
return false;
}
</script>
<?php
function deleteclient11($x)
{
echo "$x";
}
?>
You need to use AJAX, it's easy with jQuery or another library, so I'll demonstrate with jQuery.
javascript
var deleteClient = function(id) {
$.ajax({
url: 'path/to/php/file',
type: 'POST',
data: {id:id},
success: function(data) {
console.log(data); // Inspect this in your console
}
});
};
php file
<?php
if (isset($_POST['id'])) {
deleteClient11($_POST['id']);
function deleteClient11($x) {
// your business logic
}
}
?>
More info: jQuery.ajax()