jQuery POST to PHP appears in browser, but not the PHP file - javascript

I've been pulling my hair out over this problem and I must have searched through over fifty other questions on here, to no avail. I'm trying to code a website using PHP, MariaDB, jQuery, and other web development technologies, however I've encountered issues trying to post variables from the client-side (with jQuery) to the server-side (PHP). I created a very simple file just to isolate the problem that I'm having:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
<script type="text/javascript" src="jquery.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
type: "POST",
url: "index.php",
data: {'name': "name1"},
});
});
</script>
<body>
<?php
if(isset($_POST["name"])){
$i=$_POST["name"];
echo "num: ".$i;
}
else{
echo "No information supplied";
}
?>
</body>
</html>
I refresh the page, and I constantly get the failure message "No information supplied". I know the POST is getting sent to the browser, because I can see it in Firebug, and its status code is 200 OK, so I know that I must be doing something correctly. Is my PHP syntax messed up? I know that this will work just fine when I'm pulling data from forms embedded in the regular HTML.
Thank you for your assistance, and I apologize in advance if this is a really simple problem. I'm trying to learn web development as well as possible. I feel like I've tried everything, down to using the longer .ajax way of sending a POST variable, rather than using .post().

Here is your answer, you will be testing to see if there is an ajax request, if so process it, if not spit out your original page. As for the ajax call we are adding a success callback that will then update your body tags with your returned. data
<?php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
if(isset($_POST["name"])){
$i=$_POST["name"];
echo "num: ".$i;
}
else{
echo "No information supplied";
}
die;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
<script type="text/javascript" src="jquery.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
type: "POST",
url: "index.php",
data: {'name': "name1"},
success: function(data){
$('body').html(data);
}
});
});
</script>
<body>
this is the original body content
</body>
</html>

Your PHP code runs before you trigger the ajax request, because the server interprets and runs PHP before you get to see the resulting HTML in the browser
What you need is add a success callback in the ajax request object which will get the result of ajax request and do something useful with it, such as place it into a <div> element. The example below simply displays it
$.ajax({
type: "POST",
url: "index.php",
data: {'name': "name1"},
success: function(serverReponse){ alert(serverResponse) }
});

Related

Get a javascript derived dom-tree element

My aim is to get an element <div id="calender"> and all what is in the element shown in a browser. The point is that normal get-html-source won't do the thing. The element what I am looking for does not exists in the html output of php-function file_get_contents.
I have tried to get the source by php with xpath byt the help of http://us3.php.net/manual/en/class.domxpath.php which inludes a nice tool to get what is in any tag in the html page. But the problem here might be that the element (a calender) is formed to the loaded page by javascript and cannot be caught by server side php. So, is there a way I can catch such element (div) by javascript instead.
There are script examples of javascript for this kind of problem (if I have understood them correctly) but currently I cannot get a simple javascript to work. An example below shows how I have tried to built up a code. $ajax thing here is just one path I have tried to solve the problem but don't know how to use it. More here I cannot figure out why the simple javascript functions do not work (just test purposes).
<!doctype html>
<html lang="fi">
<head>
<meta charset="utf-8">
<title>load demo</title>
<style>
body {
font-size: 12px;
font-family: Arial;
}
</style>
<script type="text/javascript">
function ok {
alert "OK";
}
function get_html (my_html){
alert "OK";
var l = document.getElementById('my_link').value;
alert l;
alert my_html;
var url = my_html;
$.ajax({
url: url,
dataType: 'html'
success: function(data){
//do something with data, which is the page 1.html
var f = fs.open("testi_kalenteri.html", "w");
f.write(data);
f.close();
alert "data saved";
}
});
}
</script>
</head>
<body>
<p id ='my_link' onclick='get_html("lomarengas.fi/en/cottages/kuusamo-rukasaukko-9192")'>html-link</p>
<p id ='ok' onclick='ok()'>show ok</p>
</body>
</html>
Briefly, I have a link to a web page, which shows up a (booking) calendar in it but this calendar is missing in the "normal" source code, by file_get_contents (php). If I browse the html source with Chromes tools (F12) I can find the calendar there. T want that information get by javascript or by php or such.
If you read the source code of the page you point to (http://www.yllaksenonkalot.fi/booking/varaukset_akas.php), you notice that the calendar is loaded via an iframe.
And that iframe points to that location :
http://www.nettimokki.com/bookingCalendar.php?id_cottage=3629&utm_source=widget&utm_medium=widget&utm_campaign=widget
Which is in fact the real source of the calendar...
EDIT following your comment on this answer
Considering the real link : http://www.lomarengas.fi/en/cottages/kuusamo-rukasaukko-9192
If the calendar is not part of the generated html, it is surely asynchronously generated (in javascript, client side).
From this asumption, I inspected the source code (again).
In the developper tools of my browser, in the Network section, where you can monitor what files are loaded, I looked for
calls to server (everything but calls to resources : images, stylesheets...).
I then noticed calls to several urls with json file extensions like http://www.lomarengas.fi/api-ib/search/availability_data.json?serviceNumber=9192&currentMonthFirstDate=&duration=7.
I felt I was on the right track (asynchronous javscript calls to generate html with json datas), I looked for javascript code or files that was not the usual libraries files (jquery, bootstrap and such).
I stumbled upon that file : http://www.lomarengas.fi/resources_responsive/js/destination.js.
It contains the code that generates asynchronously the calendar.
tl;dr
The calendar is indeed generated asynchronously.
You can't get the full html with a curl or file_get_content in PHP and
you can't access it with ajax code (due to Same-origin policy).
By the way, you should contact the site to see if you can access their api via PHP with their consent.
Hope it helped you understand the whole thing...
To get <div id="calender"> you can use next code (jquery):
<div id="calender"></div>
<script>
$("#calendar").click(function(){
alert('calendar was clicked');
});
</script>
If I understand you correctly. I think you need appropriate php respond with some correct code inside php file:
// json_handler.php
<?php
if (is_ajax()) {
$return = $_POST;
$return["ok"]="ok";
$return["json"] = json_encode($return);
echo json_encode($return);
}
function is_ajax()
{
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
and this is script wich is inside html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<a id="click">click</a>
<script>
$("document").ready(function(){
$("#click").click(function(){
var data = {
"request": "request"
};
data=$.param(data);
// alert(data);
$.ajax({
type: "POST",
dataType: "json",
url: "json_handler.php",
data: data,
success: function(data) {
// here you will see echo respond from your php json_handler.php
// also you can add here more javascript (jquery code) to change your page after respond
alert();
}
});
return false;
});
});
</script>
<body>
<html>
http://www.w3schools.com/jquery/jquery_ajax_intro.asp

PHP file_get_contents and CURL failure to fetch the content of a javascript based page

I have tried both file_get_contents and CURL to fetch the content of a specific page. I setup the CURL to follow redirects and changed User-Agent, however, it did not work. I have no problem when loading page in browser. I get a page with below code whenever I try to fetch it with file_get_contents or CURL:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Loading ...</title> <script
src="/jquery.js" type="text/javascript"></script> </head> <html> <noscript>Enable java!</noscript> <div id="status"></div> <script type="text/javascript">
function check(){ $.ajax({
type: "POST",
url: "/index.php",
data: "allowed=5b91b80a061537ae6a23835aba38279e",
success: function(html){if(html == "allowed"){location.reload();}},
beforeSend:function(){
$("#status").html("Loading ...")
}
});
}
$(document).ready(function(){
check();
});
</script> </html>
Is there anyway to bypass such restriction without using Javascript based Web Scrapers like PhantomJs, CasperJs or ZombieJs? Simply using a plain PHP?

jQuery AJAX function returning strange output

I'm playing around with AJAX requests to a php file via jQuery, and I'm getting some strange output.
main.php:
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="/stylesheets/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<?php
include('main.html');
?>
<script type='text/javascript'>
$('#startButton').click(function() {
$.ajax({
method: "POST",
url: "test.php",
}).done(function(data) {
alert(data);
});
});
</script>
</body>
test.php:
<?php
echo 'Hello';
?>
Instead of alerting 'Hello' on button click, my program alerts the html of main.php. Any idea what's going on?
Figured it out - I'm using GoogleAppEngine and my app.yami file was not configured to direct requests to test.php, as it defaults all requests to main.php, hence the returned html.
Apologies for not stating that I was using GAE - I didn't think it was relevant.
Credit to #Dagon for suggesting that it was a redirecting error which led me to the correct answer.

Javascript/AJAX/PHP error: No element found and unable to write to a file

I've been struggling with this error for a couple of days now. Searched stackoverflow and other web sources but so far no luck.
The code is fairly simple. I have a test.html file which calls a saveFile.php. However, I have two problems.
1) In Firefox, I keep getting a "no element found" error. Don't see this problem in Chrome.
2) Even though saveFile.php seems to be getting called, it does not write a file as it should. This is the case with both browsers and I really need to be able to write to a file.
This is the test.html file:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>IIDS: Basic Boilerplate</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
hello world
<script src="../components/jquery/jquery.js"></script>
<script type="text/javascript">
$.ajax({
type: "POST",
url: "saveFile.php",
//url: "http://localhost/~usesr1/mywork/saveFile.php",
//dataType: "json",
data: 'test',
success:function(text) {
console.log(text);
},
error: function(xhr, status) {
alert("unable to save data");
},
});
</script>
</body>
</html>
This is the saveFile.php:
<?php
$tdata = "hello world this is a test";
$testf = fopen('hello123', 'w+');
fwrite($testf, $tdata);
fclose($testf);
echo "yes";
// header("Content-Type: text/plain"); Got this from another stackoverflow question, but this didn't fix the problem.
exit();
?>
Both files are in the same directory under ~/public_html. I gave 777 permissions to the directory. This is a machine running Ubuntu 14.04.
In saveFile.php, tried "GET" instead of "POST" but no luck again.
I'm stuck and any help would be greatly appreciated. Thanks.
EDIT: This question is not a duplicate of the one linked in the comments. The main difference is that I am not able to get my php to write to a file. I don't necessarily care about the "no element found" error as long as the php script is able to write to file. I only decided to include that error in this post because I thought it might be relevant to my real problem.
You have to specify when the AJAX event has to happen.
Since you want it to fire when you open the page add the $(document).ready function and it will fire when document has finished loading. Or you can bind it for example to a .click() event of a button.
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "saveFile.php",
data: 'test',
success:function(text) {
console.log(text);
},
error: function(xhr, status) {
alert("unable to save data");
},
});
});
</script>

How To Set Language to Chinese Using Ajax Form Submit to A Different PHP File?

I am working on a project with Chinese language (gb2312). We have a form that submit customer input data from File 1 to a php File 2 using Ajax. The two files display Chinese without problem. But when the same data was submitted from File 1 to File 2, it turned to be totally wrong characters. For example:
File 1
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div id="msg">0</div>
<form id="add-form" action="file2.php" method="POST">
<input type=text name='content' value='试试这个' >
<input type="button" id="add-post" value="Run Code" />
</form>
<script>
$(document).ready(function()
{
$("#add-post").click(function()
{
$("#add-form").submit(function(e)
{
$("#msg").html("<img src='/image/progress_bar.gif'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url: formURL,
type: "POST",
data : postData,
contentType: "application/x-www-form-urlencoded;charset=gb2312",
success:function(data, textStatus, jqXHR)
{
$("#msg").html('<pre>'+data+'</pre>');
},
});
e.preventDefault(); //STOP default action
e.unbind();
});
$("#add-form").submit(); //SUBMIT FORM
});
});
</script>
</body>
</html>
File 2
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<?php
echo $_POST['content'];
?>
</body>
</html>
Both of the files display Chinese characters without problem. But when submitting content in Chinese from File 1 to File 2 the content becomes garbled not appears to be the correct characters. I think the problem should be somewhere in the Ajax submit script but do not know how to fix it.
Would you please help me? Thank you in advance.
Yes, the problem is definitely occurring at the Ajax request. If you look at the jQuery documentation for the contentType property, you will see the following note:
The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding.
You can return gb2312 characters when rendering the page for the browser, but it looks like the Ajax request will always be sent in UTF-8. You will therefore need to have your PHP script accept UTF-8 in order to get it to parse the data correctly. I suggest removing the contentType header from the Ajax request.
After your PHP received the UTF8-encoded string, you can convert it back into gb2312 using the iconv function:
$chinese_content = iconv('UTF-8', 'GB2312', $_POST['content']);

Categories