$_REQUEST works, but $_POST doesn't - - php

Thank you for sharing in my headache - here is the short speil:
Recently inherited a poorly coded WordPress site - which leveraged a WP Contact Form 7 -
I stripped all the WP-CF code out (due to the fact that the WordPress had been stripped out before it was handed over to me) -- just to make a simple patch script and get on with real work.
I replaced the WPCF scripts with this one: (to make things as easy as possible for me):
jQuery(document).ready(function() {
$ = jQuery;
console.log("Ready");
$("#quack-button").click(function(e) {
console.log("Quack");
e.preventDefault();
e.stopPropagation();
POSTDATA = $.param($("#quack-form").serializeArray());
$.ajax({
method : "POST",
url : "http://www.domain.com/contact.php",
data : POSTDATA,
success : function(response) {
console.log(response);
alert("Thank you ! We'll get in touch as soon as we can -! ");
}
});
});
});
but, after trying many different forms/combinations of $.param and serialize -
The server side script continued to return a blank array....
print_r($_POST);
However, when I changed it to print_r($_REQUEST) - it all worked, fine....
Now, what possible ways could this even happen? What blindspots am I missing that could create this sort of scenario...?
This is the most baffling I've dealt with in some time... I appreciate any understanding anyone can throw at this...

If you want to send it as $_POST, change this line:
method: 'POST'
to this:
type: 'POST'
According to docs, thats the way of setting it.
type (default: 'GET')
Type: String
The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

Related

simple jsonp not working with php server

I tried following some basic examples, and it is not working. I am not sure I completely understand jsonp, but I followed the basic tutorials and on an intuitive level, I can't see anything wrong. (Of course, I am missing something, hence the question).
JavaScript code:
postData = $(this).serialize();
console.log(postData);
$.ajax({
data: postData,
url: 'externaldomain.php',
dataType: 'jsonp',
success: function(data){
console.log(data);
alert('Your comment was successfully added');
},
error: function(){
console.log(data);
alert('There was an error adding your comment');
}
});
PHP code:
$tag = mysql_real_escape_string($_GET["callback"]);
The annoying part is that it is not even showing me an error to Google for.
Can anyone help out figuring the problem please?
Since you haven't posted your full or relevant PHP code I'm going to assume it looks like this
$tag = mysql_real_escape_string($_GET["callback"]);
echo $tag."(";
// print json here
echo ")"
I'm not really sure how jquery handles jsonp requests but what I used to do is add a new script tag to the DOM that looks like this
<script> function cb(json) { alert(json); } </script> // (I)
<script src="{url}?callback=cb"></script> // (II)
When (II) is loaded, and because we have a callback then the script that we are including in the DOM looks like this
cb({
// json goes here
})
which pretty much is like a function call to some function called cb that we are using. It is therefore natural to have an implementation of cb (which is in (I)). That implementation is similar to the success(data) function in jQuery's ajax. It is used to use and manipulate the json requested
However I noticed that you are doing a POST request along the ajax call with jsonp. Unfortuantely (according to this question How to make a jsonp POST request that specifies contentType with jQuery?) doing POST with JSONP is not feasable due to implementation pursposes.
You can't POST using JSONP... it simply doesn't work that way...
So you can usually only perform GET requests. You can NOT perform POST requests.
For details about how jsonp work look at this nice article. jsonp-how-does-it-work
For more clearification :
See Other SO question Link1 Link 2
But there is work around for that with some limitations look at this Using PUT/POST/DELETE with JSONP and jQuery. (for me nothing works at all)

Empty php variable after ajax post

I have the following code in my script file:
$.ajax({
url: "server.php?saveEvent",
data: "myEvent=" + JSON.stringify(myEvent),
dataType: "json",
type: "post",
success: function (data) {
if (data) {
$("#log").append("<br />Evenement saved.");
}
}
});
In server.php I retrieve the variable using:
if (isset($_GET['saveEvent'])) {
if (isset($_POST['myEvent'])) {
$firephp->log(gettype($_POST['myEvent']));
$myEvent = json_decode($_POST['myEvent'], true);
}
}
When I tested this on my localhost, everything went fine. Unfortunately, after deployment,
$myEvent
was empty.
Using firephp, I tested what was in the variable, and I looked at the headers being sent. The object was sent to the server, but still somehow php see's it as being an empty variable.
Any ideas on how this is possible? Is it a php version or json issue?
EDIT: PHP ver= 5.2.17 / json enabled
EDIT2: Changing te url to ?saveEvent=1 didnt change anything
Edit3: I realize making a get and post is a bit strange, I'll try changing that, but get/post shouldn't be a problem I think
Your uri contains a GET parameter, saveEvent. You're checking for POST data only
try checking this: $_GET['saveEvent']
Even so, that parameter hasn't got a value assigned to it, perhaps change the url to ?saveEvent=1.There's also no reason for you to use 2 if statements:
if (isset($_GET['saveEvent'] && isset($_POST['myEvent']))
{
//do stuff
}
Since it seems there's more going on than just the GET vs. POST issue, you might want to add an ampersand (&) at the end of your url: look at your console, the XHR request just pastes the POST parameters at the end of your url, so the uri will look like either one of the following urls:
server.php?saveEvent=truemyEvent=foo
server.php?saveEvent=1myEvent=foo
server.php?saveEventmyEvent=foo
//or
server.php?saveEvent=1?myEvent=foo
Whereas, what you need is:
server.php?saveEvent=1&myEvent=foo&something=else
Basically, stick to 1 method, either POST or GET, and make sure that the various parameters are separated as they're supposed to be separated.I'm not sure if this is the issue, but try var_dump-ing the $_REQUEST super-global, along with $_GET, $_POST and what have you...
Try using an object instead of a string in your data
data: {myEvent:myEvent},
Is the behavior of using just server.php?saveEvent well defined by your server? The behavior of doing that may vary between servers or versions of PHP. What would the PHP variable be set with? It isn't exactly clear using that shorthand, so I would be nervous using isset() like you are. I would use something more ordinary like server.php?saveEvent=true so that you're sure saveEvent is going to be set.

Is there a way to call php with an event other than $.get?

EDIT : Found the solution to my problem below. See it here -> IE must close for event with jQuery to work
I've been asking around, trying to figure this one out. If there are any other way to do a mySql query in PHP by an event .. other than $.get.
I've previously posted this one other problem just in case somebody could help out ->
$.get not working in IE
Now I'm trying to find a way around the problem I previously posted cause if $.get is not going to happen in IE for me then there has to be another way with this. Maybe not with jQuery
Perhaps you could try the longhand syntax (as $.get is a shorthand alias of $.ajax)
function getbillinfo(tbl) {
$.ajax({
type: "POST",
url: "getbillno.php",
data: "tbl=" + tbl,
success: function(bill){
$("#billno").val(bill); });
}
});
}
See http://api.jquery.com/jQuery.ajax/
Edit: with regard to your problems with IE, there could be a couple of reasons
Possibility One
IE caches the results of Ajax calls to the same resource even if you
tell it not to in your HTTP headers. So if you make a request to
getbillinof.php?tbl=table over and over again, IE will make the
request once and then stop making it in the future and simply return
the result of the first request. To circumvent this you can call getbillinof.php?tbl=table&random_string_here
It may also be worth setting cache: false in the ajax() options and having a look into the isModified option.
Possibility Two
A Race Condition is causing the IE render action to run before
any data was returned. This however is unlikely as the success()
function is only supposed to run once the data has been received. A
race condition becomes far more likely if you're doing something like
function getbillinfo(tbl) {
$.ajax({
type: "POST",
url: "getbillno.php",
data: "tbl=" + tbl,
success: function(bill){
var mydata = bill;
}
});
$("#billno").val(mydata);
}

jQuery/Ajax call - It Doesn't work on IE7

i make a Jquery function that (for the moment) call a function dinamically and print it with an alert. with firefox, chrome : it works! when i try on IE7 (the first time), it fails. If i reload the page (F5) and retry , it works! o_O
I FINALLY understand why that's happen. In my old website i used the jquery-1.3.2.min.js library. On this i use the jquery-1.4.2.js and in fact it doesnt work. So what's up? A bug in this new version?
cheers
EDIT
actual functions (with Bryan Waters suggestions):
// html page
prova
// javascript page
function pmNew(mexid) {
var time = new Date;
$.ajax({
type: 'POST',
cache: false,
url: './asynch/asynchf.php' + '?dummy=' + time.getTime(),
data: 'mexid='+escape(mexid)+'&id=pmnew',
success: function(msg) {
alert(msg);
}
});
return false;
}
// ajax.php
if($_POST['id']=="pmnew") {
echo "please, i will just print this";
}
Fiddler result : if i use http://localhost/website fiddler doesnt capture the stream. if i use http://ipv4.fiddler/website it capture the stream, but at the ajax request doesnt appair. if i refresh the page, yes it works. mah...i really don't know how resolve this problem...
Best way to debug is to download Fiddler and see what the HTML traffic is going on and if the browser is even making the ajax request and what the result is 200 or 404 or whatever.
I've had problems with IE cacheing even on posts. And not even sending out the requests. I usually create a date object in javascript and add a dummy timestamp just to make the url unique so it won't be cached.
ok, I'm not exactly sure what the issue is here but I think you could probably fix this by simply letting jquery handle the click instead of the inline attribute on the tag.
first change your link like this to get rid of the inline event
<a class="lblueb" href="./asynch/asynchf.php?mexid=<?$value?>"><?=value?></a>
then in your javascript in the head of your page add a document.ready event function like this if you don't already have one:
$(function(){
});
then bind a click event to your link inside the ready function using the class and have it pull the mexid from the href attribute, then call your pmNew function like so:
$(".lblueb").click(function(e){
e.preventDefault();
//your query string will be in parts[1];
parts = $(this).attr("href").split("?");
//your mexid will be in mexid[1]
mexid = $parts[1].split("=");
//call your function with mexid[1] as the parameter
pmNew(mexid[1]);
});
Your final code should look like this:
<script type="text/javascript">
function pmNew(mexid) {
$.ajax({
type: "POST",
url: "./asynch/asynchf.php",
data: "mexid="+mexid+"&id=pmnew",
success: function(msg){
$("#pmuser").html('<a class="bmenu" href="./index.php?status=usermain">PANEL ('+msg+')</a>');
}
});
}
//document.ready function
$(function(){
$(".lblueb").click(function(e){
//prefent the default action from occuring
e.preventDefault();
//your query string will be in parts[1];
parts = $(this).attr("href").split("?");
//your mexid will be in mexid[1]
mexid = $parts[1].split("=");
//call your function with mexid[1] as the parameter
pmNew(mexid[1]);
});
});
</script>
I believe you have an error in your SQL code. Is userd supposed to be userid?
Gaby is absolutely right that your SQL code is wide open for injection. Please consider learning PDO, which will reduce the likelihood of SQL injection significantly, particularly when using placeholders. This way you will have query($sql) and execute($sql), rather than the code going directly into your DB.
As a matter of habit you should deal with your request variables early in your script, and sanitize them to death -- then assign the cleaned results to new variables and be strict in only using them throughout the rest of the script. As such you should have alarm bells ringing whenever you have a request variable in or near an sql query.
For example at the very least you should be stripping any html tags out of anything that will get printed back to the page.
That is in addition to escaping the quotes as part of the sql string when inserting into the database.
I'm all for coding things up quickly -- sure, neaten up your code later... but get security of request vars right before doing anything. You can't tack on security later.
Anyway sorry for harping on.... as for your actual problem, have you tried what Gaby suggested: change your html to:
<a class="lblueb" href="#" onclick="return pmNew('<?php echo $value; ?>')"><?php echo $value; ?></a>
And then update your JS function to:
function pmNew(mexid) {
$.ajax({
type: 'POST',
cache: false,
url: './asynch/asynchf.php',
data: 'mexid=' + escape(mexid) + '&id=pmnew',
success: function(msg) {
$('#pmuser').html('<a class="bmenu" href="./index.php?status=usermain">PANEL (' + msg + ')</a>');
}
});
return false;
}
Also, with IE -- check the obvious. Clear the browser cache/history
I didn't understood the "fail", but here's another example..
function pmNew(mexid) {
$.post("./asynch/asynchf.php", {mexid: mexid, id: "pmnew"},
function(msg) {
$("#pmuser").html('<a class="bmenu" href="./index.php?status=usermain">PANEL ('+msg+')</a>');
}
});
}
It appears that this issue is faced by several people.
One of them had luck with clean installation of browser:
http://www.geekstogo.com/forum/topic/22695-errorpermission-denied-code0/
Check to make sure the content returned to the DOM is valid for the DOCTYPE specified.
I've had a similiar problem with Chrome, FF and Safari all working just fine, but finding the ajax result broken in IE. Check to make sure you don't have any extra divs or spans in the ajax result breaking your markup.

Is this a jQuery bug, or am I missing something?

I am using jquery-1.3.2 in an AJAX web application. I use the jQuery ajax $.post() method to submit requests to the server.
On the server I am using php to build an array and then json_encode the answer. Then on the client I use the callback function of the AJAX post method to process the response.
All works well until I use the $.post() method to send variables to the server. If I send variables to the server, the response I get back is [object Object] and therefore I am unable to parse it. I have a work around at the moment that when posting variables I request a HTML response and then I parse that.
So the code involved taken from my site is:
The Jax call:
$.post("inc/sendfeedback.php", {NAME: name,TYPE: type,EMAIL: email,COMMENT: comment}, function(data) {PostData(data);}, "json");
So the PostData code looks like this:
function ProcessData(data)
{
//alert(data);
var jo = eval("(" + data + ")");
if(jo.result == "true")
{
if(jo.data != "" && jo.element != "")
{
$(jo.element).html(jo.data);
}
}
SMessage(jo.error);
}
If I uncomment the above code the alert with have in it [object Object].
if I remove the Post variables from the call it works fine.
The server code look like this:
$arr = array ("result" => $result,"data" => $data,"error" => $error,"element" => $element);
echo(json_encode($arr));
Is this a bug with the jQuery library, I tried it with the 1.2 version however its was still present there? I also search the jQuery site and can not find anyone having this issue.
So I assume I am missing something. But what?
$.ajax({
url: "script.php",
global: false,
type: "POST",
data: {NAME: name,TYPE: type,EMAIL: email,COMMENT: comment},
dataType: "json",
contentType: "application/json",
success: function(data){
alert(data.result);
}
}
No need to eval, jQuery evals/parses it before calling the success callback.
eval = pure evil
http://docs.jquery.com/Ajax/jQuery.ajax#options
Because you are using an associative PHP array, json_encode will return a string representation of a Javascript Object and not a Javascript Array. However, you should still be able to process it in a similar fashion to an array:
for (var key in data)
{
var item = data[key];
}
I would strongly recommend you download Firefox+Firebug addon and use the console API for debugging/dumping what is being returned by the server.
I have since registered and now can't post comments into this thread without reputation and can not see any easy method to claim this question as mine.
Deviant, your suggestion of using the $.ajax() method worked. Reason it didnt work for me the first time was I submitted the post data as a JSON object when the server code was expecting POST data.
So I fixed my javascript to call the server script correctly and everything works exactly as it should.
So the conclusion is, the $.post() method has a bug in it. I have not tracked it down but line 3633 is were the post method makes the call. I started digging however have not yet found the issue.
I qualify this by the fact the $.ajax() to the same server script and the same javascript processes the response and it all works, use the $.post method and my script fails with the return even through the return object appears to be a valid JSON object.
Thanks for the help guys. Now to go and remove all my $.post calls for $.ajax calls.
The result of all this can be seen at www.pygames.net
Cheers
Shane
a.k.a FrogSkin

Categories