No response from PHP Script - php

Absolutely new to PHP and so far it isn't pretty.
Anyway, I'm trying to pass a variable over to a PHP script, do a couple things with it, and pass it back to my Javascipt code.
Here's where I pass it off to PHP:
var src=encodeURIComponent("http://www.someonlinesite.com/file.swf");
$.ajax({
url:'test.php?src='+src,
dataType:'json',
success:function(response){
alert(response)
}
});
and here's the script:
<?php
$src=isset($_GET['src'])?$_GET['src']:'';
$size=getimagesize($src);
echo json_encode(array('size'=>$size));
?>
I'm trying to pass the URL of a .SWF video file over to a small PHP script that will use getImagesize() to figure it's dimensions and pass them back.... but I'm not seeing anything in the response and the alert isn't firing.
What's going wrong?
UPDATE:
I've updated the code with the most recent - according to the advice from some nice SO members. When I hardcode the $src variable and navigate directly to the test.php it echoes everything perfectly. So, it looks like the PHP is working. However, it appears like either the callback is never firing or the PHP file isn't returning the data. In the console there still isn't anything in the response.

You need to concatenate your url string parameter in get():
$.get('test.php?src=' + src, function(data){
alert(data);
});
And also, your src variable begins with a double quote and is closed with a single quote. That will cause issues.
var src="http://www.someonelinesite.com/file.swf";
Also, it's probably a bad idea to do this via $_GET since you are passing a URL. $_POST would be better or encode the URL before you pass it. The current url you are passing right now would look like this in a browser:
http://www.mysite.com/test.php?src=http://www.someonelinesite.com/file.swf
That's not pretty. Using encodeURIComponent(), your whole URL will end up looking like this:
http://www.mysite.com/test.php?src=http%3A%2F%2Fwww.someonelinesite.com%2Ffile.swf
Edit to $.ajax
$.get above would work just fine, but going with the implementation of $.ajax works too:
$.ajax({
url:'test.php',
type: 'GET', //Add the type
dataType:'json',
data: {'src': src}, //Add the data, leave it out the url
success:function(data){
alert(data)
}
});

Try this :
In Jquery :
var src="http://www.someonelinesite.com/file.swf";
$.ajax({
url:'test.php?src='+src,
dataType:'json',
success:function(response){
alert(response.size);
}
});
In php
$src=isset($_GET['src'])?$_GET['src']:'';
$size=getimagesize($src);
echo json_encode(array('size'=>$size));
?>

Related

How can I pass a variable from JSON to PHP?

I'm using JSON to produce some data on Wordpress which I need to store in a PHP session variable. Here's the current setup that I'm messing around with but having no luck:
jQuery(document).ready(function($) {
$.ajax({
url: 'url',
type: 'POST',
dataType:'json',
data: {foo: 145},
success: function(data){
console.log(data);
alert(data);
}
});
});
and the PHP:
session_start();
$_SESSION['bar'] = $_POST['foo'];
I can see the data in the console but nothing will display when I echo my sesh var. Using vardump returns an empty array. Where am I going wrong here?
(I realize there are plenty of other questions just like this, but believe me, I've tried them all - nada.)
Answer: You can't use javascript to store server side variables.
You must save the $_SESSION var in the PHP script that this AJAX calls. Which you have put URL?? In WordPress you can use JQuery to call a special hook which can be caught he functions.php that handles all AJAX.
There's info about this everywhere, see solution to this answer:
Using AJAX in a WordPress plugin
You would have to set a global variable for both languages and then transfer them via javascript you could do this on every page using php includes.

Moving array from jQuery to PHP

Im trying to transfer an array from jQuery to PHP but for some reason after hours of searching nothing will work. Below is what I have and what others seem to be using online but for some reason I only get the error alert. Anyone know what it is I'm doing wrong? It seems to be something to do with my jQuery code but I can put in anything there and get the same results so it is useless for telling me what I am supposed to fix. Also Im not sure if it is important but the array Im using is 2d.
FINAL WORKING CODE:
jQuery:
$.ajax({
type: "POST",
url: "phpfile.php",
data: {"myData" : myArray},
success: function(data){
alert("Success");
//appends code to end of my webpage, just for testing purposes
$('#button').after(data);
},
error: function(e){
alert("Error")
}
});
PHP:
$data = $_POST['myData'];
//creates xml file
var_dump($data);
The following is copied from the comment so this question can be marked as answered:
It seems like it should be working so I would try a simple, very basic ajax test and make sure at least that is working correctly. I would try to:
1) Get rid of the dataType json line.
2) Take the "/" out of the url.
3) Change the data to {"myData" : "testing"} or even get rid of the data line altogether.
4) Change the PHP to only be: echo "test".
Then see if you alert Success. This will hopefully tell you that your ajax is working. If so, you can start putting your code back in and see where it fails.
The mistake might be:
data: {"myData" : myjsonString}
Try this, assumming that jsonString is a string
data: "myData="+ jsonString

ajax call on CodeIgniter page returns result "an empty string"

I've got an AJAX script in my index.php of my CI application. I am just trying to return a simple string at this point for my testing. I'm using the following code for this:
<script>
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'index.php/loader/opc_client',
dataType: 'json',
cache: false,
success: function(data) {
console.log(data);
$('#opc-results').html(data.test);
}
});
});
</script>
The url in this call is a standalone file with it's own controller. When I access this file directly in the browser it's loaded normally and returns expected results. Following is my PHP code:
<?php echo json_encode("test"); ?>
I can see the post results in Firebug after the function is fired but the Firebug window just displays "an empty string" under the POST in console view.
Any clues? I'm not understand this...
UPDATE: If I console.log('success') in the success parameter of the AJAX call, it logs it properly so for some reason data is empty
you shouldn't just json_encode a string although technically php can deal with a string as an array but I guess in this case things get weird. Just wrap it in an array, and when youre done testing you'll probably be better off using key value pairs as it makes thing on the client side easier to deal with, ie obj.property.
try echo json_encode(arrray('test'));

Getting a value from a variable , send to php to process and add that value to mysql database?

i am new to php and mysql.
How can i extract a VALUE from a JAVASCRIPT VARIABLE(i set) then send it to a PHP page that can read it and process it , the PHP will then insert the value into a table in MySQL database.
var A = "somevalue"
I have been researching but none of it give me a simple and direct answer . I saw some people uses JSON(which i am unfamiliar with) to do this.
Hopes someone can give me an example of the javascript/jquery , php code to this. Thanks!
You've asked for... a lot. But, this tutorial looks like it could help you.
(FYI -- I swapped out the original tutorial for one on ibm.com. It's better but far more wordy. The original tutorial can be found here)
I'm not pretty sure if it works but just try this. Your jQuery script shoul be like this:
$(function(){
var hello = "HELLO";
$.post(
"posthere.php",
{varhello: hello},
function(response){ alert(response); }
)
});
and "posthere.php" is like this:
$varhello = $_POST['varhello'];
echo $varhello . ' is posted!';
you should then get an alert box saying "HELLO is posted!"
What you need is Ajax. This is an example jQuery to use:
function sendData(data) {
$.ajax({
type: 'POST',
data: data,
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
This will send post data to that url, in which you can use PHP to handle post data. Just like in forms.
If you have a form:
<form id="theformid">
<input type="text">
</form>
Then you can use jQuery to send the form submit data to that sendData function which then forwards it to the other page to handle. The return false stops the real form from submitting:
$("#theformid").submit(function(){
sendData($(this).serializeArray());
return false;
});
If you though want to send just a variable, you need to do it like this:
function sendData(data) {
$.ajax({
type: 'POST',
data: {somekey: data},
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
Then when you are reading $_POST variable in PHP, you can read that data from $_POST['somekey'].
Inside the success callback function you can do something with the data that the page returns. The whole data that the page returns is in the data variable for you to use. You can use this for example to check whether the ajax call was valid or not or if you need to something specific with that return data then you can do that aswell.

Use Javascript variable in PHP

I have seen some answers to this question in previous posts, but no one has given a real working example, just psuedo code. Has anyone ever done this before?
Basically, what i have is a variable in javascript (jquery), and i want to use this variable to drive a query (for an overlay window) i am going to run in php.
From what i have read you can do this using an ajax call to the same page so it doesnt refresh itself, but i must be missing something because i can't get it working...
Any examples out there?
Thanks.
UPDATE 6/21/2010:
Ok, i tried to work through but still having some problems...here is what i have. The page I am working on in edit_1.php. Based on Firebug console, the page (edit_1.php) is receiving the correct 'editadid'.
When i try to echo it out though, i get an 'Undefined variable' error though...anything y'all can see i missed here?
Here is the javascript:
var jsVariable1 = $(this).parent().attr('id');
var dataString = 'editadid=' + jsVariable1;
$.ajax({
url: 'edit_1.php',
type: 'get',
data: dataString,
beforeSend: function() {
},
success: function (response) {
}
});
Here is my php:
if(isset($_GET['editadid']))
{
$editadid = (int)$_GET['editadid'];
}
echo $editadid;
It's hard to help without seeing the code you're currently using.
In jQuery:
var jsVariable1 = "Fish";
var jsVariable2 = "Boat";
jQuery.ajax({
url: '/yourFile.php',
type: 'get',
data: {
var1: jsVariable1,
var2: jsVariable2
},
success: function (response) {
$('#foo').html(response);
}
});
Then your PHP:
<?php
$jsVariable1 = $_GET['var1'];
$jsVariable2 = $_GET['var2'];
// do whatever you need to do;
?>
<h1><?php echo $jsVariable1; ?></h1>
<p><?php echo $jsVariable2; ?></p>
It's fairly generic... but it'll do stuff.
An important thing to note, and a very common mistake, is that any additions you make to the DOM as a result of an AJAX request (i.e in this example I've added a h1 and a p tag to the DOM), will not have any event handlers bound to them that you bound in your $(document).ready(...);, unless you use jQuery's live and delegate methods.
I would say instead of looking for an example you must understand how ajax works. How can you hit a URL via ajax and pass query parameters along with them (these can be the javascript variables you are looking for) How server side response is captured back in javascript and used into manipulate existing page dom. Or Much better you can post what you have tried and somebody can correct it for you.

Categories