Not Receiving $_GET Values from jQuery AJAX Call - php

I'm writing a small function to get the URL of an image and save to locally to server.
Here's the AJAX call (confirmed it's sending the correct URL to "getimdbpic.php" with firebug)
$.get("getimdbpic.php", { posterURL: data.Poster, movieTitle: data.Title },
function(picData){
alert("Data Loaded: " + picData);
});
The problem I'm having is with my PHP.
$url = $_GET['posterURL'];
$title = $_GET['movieTitle'];
file_put_contents($img, file_get_contents($url));
I simply can't get the values that are being passed. The file_put_contents throws an error stating that the "File name cannot be empty". (referring to $url being empty)
Edit: Fixed the casing, still not receiving values.

You seem to be mixing up the case between posterURL in the Javascript, and posterUrl in the PHP.

Make sure you're using the latest JQuery. I saw a very bizarre bug like regarding values not getting sent that was fixed by an upgrade.
EDIT: Might want to try a fallback to standard $.ajax() since $.get() is just a wrapper around it:
$.ajax({
url: "getimdbpic.php",
data: { posterURL: data.Poster, movieTitle: data.Title },
type: 'GET', // this is default, but just in case
success: function(picData){
alert("Data Loaded: " + picData);
}
});

Typo in the casing here:
$url = $_GET['posterURL'];

Related

Sending data using Ajax to local PHP script, receive response but if-condition in php file is never met

I have a draggable div-container and whenever I drop it, its location is to be send to a local php script.
$(function() {
$( "#fenster" ).draggable({
stack: "#fenster", stop: function(event, ui){
var pos_x = ui.offset.left;
var pos_y = ui.offset.top;
$.ajax({
type: "POST",
contentType: "application/json",
data: {'x': pos_x},
url: "index.php",
}).done(function(msg){
alert("data Saved: " + msg);
});
}
});
});
In the php file (index.php) I check whether $_POST['x'] is set. Unfortunately, no matter what I do, the condition is never met.
if((isset($_POST['x']))){
$_SESSION['xLoc'] = $_POST['x'];
echo "Test";
}
Upon dropping the window, I get a response (alert of the msg shows output) and according to FireBug, the request DOES contain x.
The PHP superglobal $_POST, is only available when you use these content types
application/x-www-form-urlencoded (standard content type for simple form-posts) or
multipart/form-data-encoded (mostly used for file uploads)
You are using application/json which means you need to get the stream with...
$rawData = file_get_contents("php://input");
$d = json_decode($rawData);
if((isset($d['x']))){
$_SESSION['xLoc'] = $d['x'];
echo "Test";
}
Or if you dont actually need to be submitting JSON, just remove the contentType from your jquery, and you should be able to retrieve the $_POST on the php side, using the code you already had.
$.ajax({
type: "POST",
data: {'x': pos_x},
url: "index.php",
}).done(function(msg){
alert("data Saved: " + msg);
});
Or change your php to the code above, to retrieve the raw stream, if you need to be sending json data to the server
I had two redirects that killed the POST request. After making adjustments to the if-conditions, this no longer happens and the data sent by the Ajax request is now also being successfully processed by PHP.
Thank you all that took the time to help me, it's greatly appreciated.

$.ajax not a function in yii

I have the below function that I used in two different pages and worked perfectly in both cases. Suddenly my pages stopped updating and I got the error $.ajax not a function.
function update_report(data) {
var request = $.ajax({
url: "report?poids="+data,
type: "GET",
dataType: "html"
});
request.done(function(msg) {
$("#yw2").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
req ="a";
}
I then changed the $ to jQuery. Then it started sending AJAX requests but it didnt get the relative URL. Like I was generating the request from a page like /index.php/link1 and my code was sending request to /index.php/report rather then /index.php/link1/report
So, then I changed my url: to "link1/report=?"+data then it started sending request to the right page but couldnt update the response as it didnt find the div #id. Got error
TypeError: $(...) is null
What can cause all this issue and how to fix this? And why $.ajax suddenly stopped working, though I didnt make any changes?
JQuery can be not available by $.ajax(). Check if jQuery.ajax() is available or you included jquery twice.
You should not require jquery manually. The best way to include jquery is using Yii::app()->clientScript->registerCoreScript('jquery'). Path for library is set in config/main.php.

No response from PHP Script

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

JQuery ajax error

Ok, so my Ajax call looks like this:
var poststring = "id_Client=" + id_client + "&id_File=" + id_file;
alert(poststring);
$.ajax({
type: "POST",
url: "addclpermission.php",
data: poststring,
error: function(xhr, textStatus, errorThrown){
alert("Error: " +textStatus)
}
});
Everything works fine until the $.ajax(). If I use alert(poststring) the output looks like this:
id_Client=7&id_File=32
Using firebug, I found out that the url "addclpermission.php" is actually requested, but then 'aborted'. The path is correct though, if I copy the url out of firebug and call it directly, no error is displayed.
The alert in the 'error' option returns "Error: error"
The file addclpermission.php:
<?php
require_once("../allgemein/includes/dbconnect.php");
$id_File = $_POST['id_File'];
$id_Client = $_POST['id_Client'];
$sql = "INSERT INTO permission (id_File,id_Client) VALUES (".$id_File.",".$id_Client.")";
mysql_query($sql);
?>
I'm pretty sure this code once worked and that I haven't changed that much.
Any ideas?
Thanks!
Edit: I don't think that the error is in the php script, I have multiple ajax calls to several php scripts, but all of them fail the same way.
Edit 2: Now it works! Well, at least half of it. The request is still aborted, but the data gets inserted in the database. But as I said, this isn't the only ajax call and the others still aren't working, and this one is aborted. So I'd really like to know what caused this error and how I can fix it for good. Thanks!
Does the data get inserted to mysql despite the error? If so, can you put echo on your addclpermission.php file to return 'success' and/or 'fail' for mysql_query()? How about stripping this php file to just echo "hello"???
First, I would try just requesting addclpermission.php in the browser and see what happens.
Then, if that works, what if you just make addclpermission.php contain some text, no PHP content at all. Then for each stage that works, gradually add content (so first the include, for example).
I think the error could be in dbonnect.php or addclpermission.php. Save this in addclpermission.php (make a backup of your current file) and browse to it directly:
<?php
require_once("../allgemein/includes/dbconnect.php");
$id_File = 1;
$id_Client = 1;
$sql = "INSERT INTO permission (id_File,id_Client) VALUES (".$id_File.",".$id_Client.")";
mysql_query($sql);
?>
Please let us know if it works or if you get an error.
When I do jQuery Ajax, I set the data as a Javascript object that jQuery then serializes. Do you have better luck if you provide data: property as an object like this:
data: {
id_Client: id_client,
id_File: id_file
}
I am pretty sure your problem is that you are not returning an expected dataType to the .ajax call, if you explicity set the datatype (json or text for example):
$.ajax({
type: "POST",
url: "addclpermission.php",
data: poststring,
dataType: "json",
error: function(xhr, textStatus, errorThrown){
alert("Error: " +textStatus)
}
});
Then just echo out the expected datatype, just so the server responds, then ajax will know the request was successful.
<?php
// if your dataType is json
echo json_encode(true);
// if your dataType is text
echo ' ';
// exit so the server can return the request
exit;
problem is a --> require_once
require_once("../allgemein/includes/dbconnect.php");
remove this line in a php and write all code here
but I don't know why ?

AJAX/JQUERY/PHP issue

I am trying to use an ajax 'POST' call through the jquery $.ajax function to send data to a php file. For some reason the callback is a success but the data is not getting to the php file. Here is an example of the code:
In JS file:
$.ajax({ type: "POST",
url: "setData.php",
data: "myPOSTvar=myData"
success: function(){ alert("Data Saved"); }
});
In php file:
$var = $_POST['myPOSTvar']
...
$var ends up with a default value instead of the data it is sent.
Any ideas?
Sorry about the syntax errors...at work right now and don't have my code in front of me...the syntax is all correct in the actual script, just typed to quick when posting here...
Try this and see if you get any info.
$.post("setData.php", { myPOSTvar: "myData" },
function(data){
alert("Data saved");
});
I doubt it's a success, the url should be a string : url: "setData.php" .
I really doubt that piece of JS code is working as it should. POST and setData.php should be enclosed with quotes. Right now you should get some errors because "POST" variable is not defined and then because you're accessing a "php" property on a non existent object "setData".

Categories