Strange behaviour when trying to send data with ajax (jQuery) - php

I'm coding an website which must have same functionality as SO. My server use Litespeed, which increase the speed of runing php files.
When I'm trying to send php code in regular form, everything seems to be ok, data being sent to the action file without interpreting the code inside the variable. But when I'm trying to send the same data in comments textareas, with jQuery $.post method, I'm getting Forbidden 403 error. Data is blocked on the road by Litespeed server. I don't know why is happening this, why is $_POST data auto-evaluated when using ajax?
This situation doesn't appear everytime, but just in some cases, for example:
this is a new message which presents this php code: <?php mysql_query("SELECT * FROM my_table"); ?>
Note that if I remove <?php and ?> from my message, it is ok. I've already tried to use encodeURI() method but this don't change anything.
Is there any setting which must be applied in .htaccess for not auto-evaluate $_POST data?
or I should replace the open and close tags, before sending the comment?
Later edit
This is how I managed to resolve this right now, but I'm still waiting for a suggestion with .htaccess:
$but.prev('textarea').val().replace(/(<\?php)/gi,'-?php ').replace(/(<\?)/gi,'-? ').replace(/\?>/gi,' ?-');
and on the server side
str_replace(array('-?php','?-','-?'), array('`<?php','?>`','`<?'), $_POST['comment']);

Related

Nothing happens when clicking submit

I'm using WordPress with Custom Content Types plugin. I have the code in a PHP file which creates a contact form.
The website is http://schools.raci.org.au/competition/ancq/
It was working fine before I migrated it to a new host. I didn't write the original code, so I don't really know how it works.
Here are the relevant files:
Here is the code for the main page: pastebin.com/piaTSVgc
and the code for the form: pastebin.com/xeqsmc5g
here is admin-ajax.php: pastebin.com/eFx2JFJu
here is the function where register_interest_form lives: pastebin.com/knrChkSP
here is functions.php: pastebin.com/hru5LkQR
Thanks in advance!
Its working from.
When we submit form. there is ajax request is been processing and getting 0 in response.
The default response from admin-ajax.php is,
die( '0' );
...by adding your own exit() or die() after returning your desired content prevents the default response from admin-ajax.php being returned as well.
The solution is to add die() to the end of your own ajax function, so you die the script before die('0')
It also generally means that your ajax call has succeeded.
Ultimately, to answer your question, it's meant to work this way. What you are doing by exiting after returning your content is the right thing to do.
details from.
https://wordpress.stackexchange.com/questions/116759/why-does-wordpress-add-0-zero-to-an-ajax-response

PHP, can't set variable via $_POST

I have a slightly frustrating problem...
I'm sending a form value to PHP via AJAX and that seem to work fine.
When I do var_dump in PHP I see my values I can also set a variable and echo it correctly.
However, the line
$prod_id=$_POST['product'];
causes an uncaught type error in the browser.
If I just set the variable with text in PHP everything works fine.
To conclude, this piece of code works fine:
$prod_id=("Slab Skate");
$selected_customers = mysqli_query($link,"SELECT * FROM customers
INNER JOIN cust_products on cust_products.cust_id=id
INNER JOIN products on products.prod_id=cust_products.product_id
WHERE products.prod_name='$prod_id'");
This code causes uncaught typerror:
$prod_id=$_POST['product']
Same SQL statement as above.
If I do
var_dump ($prod_id);
after setting it with $_POST I get:
string(10) "Slab Skate"
My form data in network headers tab of Chrome developer tools say:
product:Slab Skate
I don't get it...
Thanks in advance for any tips.
Update and some clarifications.
The error I get is this: "Uncaught TypeError: Cannot read property 'documentElement' of null" which is a Javascript error coming from a function later in the code. However, since the whole thing works if I "hardcode" the variable instead of setting it from $_POST my assumption was that the error must reside in PHP.
But maybe that's not the case...
What I'm doing is the following: posting a form value to PHP -> use value to select from my_sql and prepare an XML output. So far so good, (I can see the xml output in Chrome dev tools) but then I go back to a javascript to fetch the xml output from my PHP file and then it fails.
When thinking about it, it's rather obvious why it works with a "hardoded" variable and not with the $_POST set one.
So, I see two solutions either set the PHP variable in my_sql or using javascript more intelligently.
Do anyone have a smart solution? I could post all the code, but it's quite long.
Second update:
I solved the issue by writing an xml file to the server instead of trying to download it from the php file. Then my java function can process the xml correctly.
It does work, but I'm not sure how well it scales? It must be better to process the xml output from PHP directly rather then saving it to file first and then process. But, I have no insight on how big the difference is...
/Tim
I wouldn't use SELECT * FROM when using Inner Join if i were you. that would cause all sort of problems , simply give the names of columns.

Get all content from a file, including PHP code

I'm making a small CMS for practice. I am using CKEDITOR and is trying to make it avaliable to write something like %contactform% in the text, and then my PHP function will replace it with a contactform.
I've accomplished to replace the text with a form. But now I need the PHP code for the form to send a mail. I'm using file_get_contents(); but it's stripping the php-code.
I've used include(); to get the php-code from another file then and that works for now. I would like to do it with one file tho.
So - can I get all content from a file INCLUDING the php-code?
*UPDATE *
I'll try to explain in another way.
I can create a page in my CMS where I can write a header and some content. In the content I am able to write %contactform%.
When I get the content from the database I am replacing %contactform% with the content from /inserts/contactform.php, using file_get_contents(); where I have the form in HTML and my php code:
if(isset($_POST['submit'])) {
echo 'Now my form is submitted!';
}
<form method="post">
<input type="text" name="email">
<input type="submit" name="submit">
</form>
Now I was expecting to retrieve the form AND the php code active. But If I press my submit button in the form it's not firing the php code.
I do not wan't to show the php code I want to be able to use it.
I still have to guess, but from your update, I think you ultimatly end up with a variable, which contains the content from the database with %contactform% replaced by file_get_contents('/inserts/contactform.php').
Something like:
$contentToOutput = str_replace(
'%contactform%',
file_get_contents('/inserts/contactform.php'),
$contentFromDatabase
);
If you echo out that variable, it will just send it's content as is. No php will get executed.
Though it's risky in many cases, if you know what you're doing you can use eval to parse the php code. With mixed code like this, you maybe want to do it like the following.
ob_start();
eval('; ?>' . $contentToOutput);
$parsedContent = ob_get_clean();
$parsedContent should now contain the results after executing the code. You can now send it to the user or handle it whatever way you want to.
Of course you'll have to make sure that whatever is in $contentToOutput is valid php code (or a valid mixture of php with php-tags and text).
Here is a link to the symfony Templating/PhpEngine class. Have a look at the evaluate method to see the above example in real code.
yes...
$content = file_get_contents( 'path to your file' );
for printing try
echo htmlspecialchars( $content );
From reading the revised question, I think the answer is "You can't get there from here." Let me try to explain what I think you will encounter.
First, consider the nature of HTTP and the client/server model. Clients make requests and servers make responses. Each request is atomic, complete and stateless, and each response is complete and usually instantaneous. And that is the end of it. The server disconnects and goes back to "sleep" until the client makes a new request.
Let's say I make a request for a web page. A PHP script runs and it prepares a response document (HTML, probably) and the server sends the document to my browser. If the document contains an HTML form, I can submit the form to the URL of the action= script. But when I submit the form, I am making a new request that goes back to the server.
As I understand your design, the plan is to put both the HTML form and the PHP action script into the textarea of the CKeditor at the location of the %contactform% string. This would be presented to the client who would submit the form back to your server, where it would run the PHP script. I just don't think that will work, and if you find a way to make it work, you're basically saying, "I will accept external input and run it in PHP." That would represent an unacceptable security exposure for me.
If you can step back from the technical details and just tell us in plain language what you're trying to achieve, we may be able to offer a suggestion about the design pattern.

Ajax issues, Invalid JSON

I'am building simple Ajax application (via jquery). I have strange issue. I found where the problem is, but I don't know how to solve it.
This is simple server-side php code:
<?php
require('some.php');
$return['pageContent'] = 'test';
echo(json_encode($return));
?>
On the client side, the error "Invalid JSON" is thrown.
I have discovered that if I delete require function, everything work fine.
Just for information, the "some.php" is an empty php file. There is no error when I open direct php files.
So, conclusion: I cant use require or include function if I want to use ajax?
Use Firebug to see what you're actually getting back during the AJAX call. My guess is that there's a PHP error somewhere, so you're getting more than just JSON back from the call (Firebug will show you that). As for your conclusion: using include/require by itself has absolutely no effect on the AJAX call (assuming there are no errors).
Try changing:
<?php
require('some.php');
$return['pageContent'] = 'test';
echo(json_encode($return));
?>
To:
<?php
$return = array(
'pageContent' => 'test'
);
echo json_encode($return);
?>
The problem might have to do with $return not being declared as an array prior to use.
Edit: Alright, so that might not be the problem at all. But! What might be happening is you might be echoing out something in the response. For example, if you have an error echoing out prior to the JSON, you'd be unable to parse it on the client.
if the "some.php" is an empty php file, why do you require it at all?!
require function throws a fatal error if it could't require the file. try using include function instead and see what happens, if it works then you probably have a problem with require 'some.php';
A require call won't have any effect. You need to check your returned output in Firebug. If using Chrome there is a plugin called Simple REST Client. https://chrome.google.com/extensions/detail/fhjcajmcbmldlhcimfajhfbgofnpcjmb through which you can quickly query for stuff.
Also, it's always good to send back proper HTTP headers with your response showing the response type.
It's most likely the BOM as has been discussed above. I had the same problem multiple times and used Fiddler to check the file in hex and noticed an extra 3 bytes that didn't exist in a prior backup and in new files I created. Somehow my original files were getting modified by Textpad (both in Windows). Although when I created them in Notepad++ I was fine.
So make sure that you have your encoding and codepages set up properly when you create, edit, and save your files in addition to keeping that consistent across OSes if you're developing on windows let's say and publishing to a linux environment at your hosting provider.

Can't send content-type: text/xml header from PHP at the same time getting the data from MYSQL

i hope you can cast some light on my problem. I need to do an AJAX / PHP / MYSQL application to display posts and stuff on the page i'm writing.
I only discovered how to do some simple stuff in PHP after taking some mushrooms but that was years ago and now i don't have mushrooms and i'm just stuck!
So here's the problem:
i think i need to send a proper "xml" file through php so the ajax part can take it but: when i try to put the header on top of the php it displays this error:
" Extra content at the end of the document "
When i looked at some tutorials people were using the "header" fearlesly to do such stuff as i want to do and no comments suggested that it didn't work. so why it doesn't work on my local server?
I'm running:
WAMP
Apache 2.2.11
PHP 5.3.0
It also doesn't work on a remote server (PHP 5.3.0) :/
I read all the stuff i could find till 5am and decided to ask you for help for the first time :)
Thank you!
header('content-type: application/xhtml+xml; charset=utf-8');
require_once("allyouneed.php");
require_once("bazingablob.php");
$category=$_GET["category"];
$post_tags=$_GET["post_tags"];
$language=$_GET["language"];
$author=$_GET["author"];
$posts_per_page=$_GET["posts_per_page"];
$current_page=$_GET["current_page"];
$order=$_GET["order"];
$hard_limit=$_GET["hard_limit"];
$show_hidden=$_GET["show_hidden"];*/
$wypluj="";
$wypluj="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
$bazinga_blob = new bazingablob;
if (!$bazinga_blob->connect_to_database())
{
$wypluj.="<IsOK>0</IsOK>";
echo $wypluj;
exit;
}
else
{
$wypluj.="<IsOK>jedziem</IsOK>";
}
$bb_result=$bazinga_blob->get_all_posts($category,$post_tags,$language,$author,$posts_per_page,$current_page,$order,$hard_limit,$show_hidden);
if ($bb_result) //udalo sie cos znalezc w bazie wedlug kryteriow
{
$wypluj.="<Pagination>";
$wypluj.="<CurrentPage>";
$wypluj.=$bazinga_blob->posts_pagination["current_page"];
$wypluj.="</CurrentPage>";
$wypluj.="<LastPage>";
$wypluj.=$bazinga_blob->posts_pagination["last_page"];
$wypluj.="</LastPage>";
$wypluj.="<PostsCount>";
$wypluj.=$bazinga_blob->posts_pagination["posts_count"];
$wypluj.="</PostsCount>";
$wypluj.="</Pagination>";
$wypluj.="<Posts>";
foreach ($bb_result as $item)
{
$wypluj.="<Post>";
$wypluj.="<PostId>".$item->post_id."</PostId>";
$wypluj.="<PostAuthor>".$item->post_author."</PostAuthor>";
$wypluj.="<PostLangId>".$item->post_langid."</PostLangId>";
$wypluj.="<PostSlug>".$item->post_slug."</PostSlug>";
$wypluj.="<PostTitle>".$item->post_title."</PostTitle>";
$wypluj.="<PostGreetingPicture>".$item->post_greeting_picture."</PostGreetingPicture>";
$wypluj.="<PostGreetingVideo>".$item->post_greeting_video."</PostGreetingVideo>";
$wypluj.="<PostGreetingSound>".$item->post_greeting_sound."</PostGreetingSound>";
$wypluj.="<PostShort>".$item->post_short."</PostShort>";
$wypluj.="<PostBody>".$item->post_body."</PostBody>";
$wypluj.="<PostDate>".$item->post_date."</PostDate>";
$wypluj.="<PostPublished>".$item->post_published."</PostPublished>";
$wypluj.="<PostSticky>".$item->post_sticky."</PostSticky>";
$wypluj.="<PostComments>".$item->post_comments."</PostComments>";
$wypluj.="<PostProtected>".$item->post_protected."</PostProtected>";
$wypluj.="</Post>";
}
$wypluj.="</Posts>";
}
echo $wypluj;
The error comes from your browser and indicates that your XML is malformed.
Setting the application/xhtml+xml header tells the browser to process the document as serious XML. XML needs to be "well-formed", i.e. it must not contain any syntax errors. Apparently you do have a syntax error on line 1 at column 73, which makes the browser abort the attempt to process the document.
For this reason it's a pain to hand-code XML, you should really look into a library that takes care of the well-formedness for you, like PHP's own XMLWriter.
Have you validated your XML?
http://friendsofed.infopop.net/4/OpenTopic?a=tpc&s=989094322&f=5283032876&m=4521066061
I'm honestly not sure what you're trying to do with the header, it's not any Ajax method I've ever been taught. The header method you're doing looks just a few lines short of outputting the XML to a download prompt.
Here's my favorite way to do AJAX. Simple, understandable, and quick.
Include Jquery.
Setup your data--whether by form with a Serialize (gets form data into a Javascript Variable) or by just setting some variables as it seems you're doing above.
Send via Jquery Ajax to a separate processing page. The page will receive the data you setup as a $_REQUEST variable, with the method depending on whether you defined it as a POST or not (defaults to a GET)
The processing page --does-- stuff with the REQUEST data and may or may not respond back to the page. This is where you can do stuff like update divs, alert that it worked, etc.
Here's a great tutorial. Focus on the code under "Hello Ajax, Meet Jquery"
If you get yourself any more of those mushrooms, a PHP familiar way to do AJAX is with XAJAX. It allows you to do asynchronous calls to PHP functions. Be aware, though, that the forums are not the most english-friendly and documentation is a bit cryptic.

Categories