as part of my time isn't dedicated to PHP dev, I'm having an issue which is probably easy to solve, but having absolutely no logs (PHP logs, browser firebug logs...) I'm pretty stuck.
Here's my code; as I'm testing stuff, it's pretty raw.
The index.php file :
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// You may specify partial version numbers, such as "1" or "1.3",
// with the same result. Doing so will automatically load the
// latest version matching that partial revision pattern
// (e.g. 1.3 would load 1.3.2 today and 1 would load 1.4.2).
google.load("jquery", "1.4.2");
google.setOnLoadCallback(function() {
// Place init code here instead of $(document).ready()
$("#shrelock").submit(function(){
var url = $(this).attr('action');
$.ajax({
url: url,
success: function(data) {
alert(data);
}
});
return false;
});
});
</script>
<form id="shrelock" action='stats.php' method='get'>
<input type="text" name="url"/>
</form>
Now the stats.php file :
include("bitly.php");
if ( isset($_POST["url"]) ){
$urlToCheck = $_POST["url"];
$bitly = new bitly('myLogin', 'myKey');
print $bitly->shorten($urlToCheck);
}
I'm not sure what your question is, but I do see a few problems with your code.
The ajax request you perform uses GET while the serverside code seems to expect a POST
and also you forgot to send the 'url' parameter in the ajax call.
$.ajax({
url: url,
type: 'POST',
data: 'url=' + $('#shrelock input[name="url"]').val(),
success: function(data) {
alert(data);
}
});
Related
I created an Ajax post request and for some reason the post data is not being received correctly by the PHP script. I get a 500 internal server error followed by "XHR failed loading: POST".
Here is a portion of my javascript:
$.ajax({
type: "POST",
url: 'newmessage.php',
// Generic form data
data: {name: $("#name").val(), message: $("#message").val()},
success: function(result){
showMessages();
}
});
Here is the PHP:
if(isset($_POST['name']) && isset($_POST['message']))
{
// Do something
}
Having looked at my code in detail I believe that I did something incorrect in my ajax request. Within my PHP file, if I create a javascript alert to output the $_POST variables, nothing gets printed.
<?php
$x = $_POST['name'];
?>
<script language="javascript">
alert ('<?php echo $x; ?>');
</script>
<?php
?>
Well, it's hard to say how your server is configured, but, just at first glance, it looks like your url may be the issue.
$.ajax({
type: 'POST',
url: '/newmessage.php', // <--- notice the leading slash
data: {
name: $('#name').val(),
message: $('#message').val(),
},
success: function(reply) {
//do stuff...
}
});
Check out the docs here: http://api.jquery.com/jquery.ajax/
Also, if you're using Chrome you can use the developer tools to see exactly what's going on under the hood. Specifically the Network tab. https://developers.google.com/web/tools/chrome-devtools/
Lastly, if you just want to troubleshoot your server, you can take jQuery out of the picture and use an app like Postman. https://www.getpostman.com/apps
XHL stands for XMLHttpRequest
Sounds like a there is no servelet (url issue).
or
servlet(php) just aborted your request(csrf token missing)
Solution 1,
Check the url
normal call
URL:"/newmessage.php" //modification needs here
rest call
URL:"/http://address/newmessage.php" //keep it in your mind please
Solution 2,
<form>
//...
<input type="hidden" id="token" value="<?php echo $token; ?>" />
//...
</form>
function sendDatas(){
var token =$("#token).val();
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
jqXHR.setRequestHeader('X-CSRF-Token', token);
});
$.ajax({
type: 'POST',
url: '/newmessage.php', // <--- notice the leading slash
data: {
name: $('#name').val(),
message: $('#message').val(),
},
success: function(reply) {
//do stuff...
}
});
}
I have a session variable $_SESSION['name']. I set in a php file which is called with ajax inside a keyup event. It works well. Until a user uses the previous page button.
When a user uses this button (or mouse button), the last set session variable value is basically not set. It will return to an older set value (the one before the last one). I wonder how/why and what I can do about it.
I've read quite a lot stackoverflow (and other) solutions, but nothing so far seems to work.
HTML:
if(isset($_SESSION['name'])) {
echo '<input type="text" name="name" value="'.$_SESSION['name'].'">'
}
<script type="text/javascript" defer>
$(function() {
var name = $('input[name="name"]').val();
$('input').on('keyup', function() {
$.ajax({
url: 'example.php?name=' + name,
type: 'GET',
dataType: 'json',
success: function(data) {
// blablabal more code
}
});
});
</script>
example.php:
$_SESSION['name'] = 'test';
Please note I'm starting the session on all of my pages with session_start(); and please note that I also tried to regenerate my session id with any hope that would do the trick.
You cannot achieve this you have to reload your page to see the changes.
although here is a suggestion to do this what you want to achieve.
if(isset($_SESSION['name'])) {
echo '<input type="text" name="name" value="'.$_SESSION['name'].'">'
}
<script type="text/javascript" defer>
$(function() {
var name = $('input[name="name"]').val();
$('input').on('keyup', function() {
$.ajax({
url: 'example.php?name=' + name,
type: 'GET',
dataType: 'json',
success: function(data) {
$("[name='name']").val('Your response');
}
});
});
By doing this you can achieve what you are looking for. also if you load the page it will get the value from session
I want to show my php page in android mobile app. I use cordova and i added a php page in my project with this directory "php/load.php". I tried to show this page on index.html i tried like this but it doesn't work.
<button type="submit" onclick="show();">Show it</button>
<script type="text/javascript">
$(document).ready(function() {
function show(){
$.ajax({
method: 'GET',
url: 'php/load.php',
dataType: 'text'
})
.done(function(data) {
alert(data);
})
alert("Pause");
}
});
});
</script>
And this is my php file:
<?php
$a = "AAAAAAAA";
echo $a ;
?>
You've got syntax errors in your JavaScript that's likely causing most of the problem. Have a look at this and give it a try.
<script>
$(function() {
$("#btn_show").on("click", function() {
$.ajax({
method: 'GET',
url: 'php/load.php',
dataType: 'text'
}).done(function(data) {
alert(data);
});
});
});
</script>
<button type="submit" id="btn_show" >Show it</button>
Four important points:
Listen to the cordova deviceready event
Your url in your ajax request is not local and it can't be local because on your device is no server running. So it has to be something like: https://www.example.com/load.php
You have to whitelisten all your external sources.
You should use https.
I would suggest using json_encode function in php.
For example:
<?php
$a = "AAAAAAAA";
echo json_encode($a) ;
?>
this would return a json array object which you can use to be rendered by javascript then put on to those html element.
changing the url for ajax For example: "url:localhost/website/load.php" i think it must be done too for ajax to work properly.
I'm trying to figure this out from 2 hours with no luck, maybe it's not that technical but I need help!
I've an AJAX script that needs to send a GET request to a php script that's on the same page.
The PHP script terminates like this
if ($success) {
print( $state );
}?>
The Javascript is rightly under the php termination and is this.
<script>
$('table button').click( function() {
var button = $(this);
/* if button inside the table is clicked */
var username = button.parent().parent().children('td').html();
var state = button.html();
/* send GET request */
$.ajax({
type: "GET",
url: 'index.php',
data: 'username='+username+'&state='+state,
success: function(response) {
alert(response);
}
});
});
</script>
What I don't understand is why I get the alert containing this text
inside // this is the state, so it's good
<script> // this is the script, not good
$('table button').click( function() {
var button = $(this);
/* if button inside the table is clicked */
var username = button.parent().parent().children('td').html();
var state = button.html();
/* send GET request */
$.ajax({
type: "GET",
url: 'index.php',
data: 'username='+username+'&state='+state,
success: function(response) {
alert(response);
}
});
});
</script>
I've to manipulate the HTML on success by I'm not able to do that because of the messy response that I get from my php code. I'm not sure if I've to post other code. If you need to know more just ask, I'll reply as soon as possible.
Any characters outside <?php ?> tags are sent back in the response. That's how you get that <script> tag in the first place when you access index.php from the browser.
echo and print are obviously going to also send data.
So I guess you should have that if($success) at the begining of index.php and exit; inside it, after print.
Characters outside <?php ?> tags are sent as part of the response for historical and practical reasons.
In our days having PHP code mixed with HTML is a bad practice (as some people already pointed out in the comments bellow). You either use a templating engine (most people know about Smarty) or use PHP itself as a templating engine.
But "back in the day" PHP started out as just a simple templating engine (no classes, external modules, namespaces, autoloaders, etc.), so mixing HTML with PHP was basically the purpose of this language.
As I said, today we still use PHP as a templating language so mixing PHP (control structures, loops) and HTML works.
A quick, but not recommended fix is to avoid the javascript content on an ajax request
Just demonstrating, how it could be,
if($success) {
print( $state );
}
if(!isset($_GET['ajax_call']))
{ ?>
<script>
$('table button').click( function() {
var button = $(this);
/* if button inside the table is clicked */
var username = button.parent().parent().children('td').html();
var state = button.html();
/* send GET request */
$.ajax({
type: "GET",
url: 'index.php?ajax_call=1',
data: 'username='+username+'&state='+state,
success: function(response) {
alert(response);
}
});
});
</script>
<?php
}?>
.....
and you should note that the new ajax call has an additional variable, ajax_call,
This is a quick fix, for you to move on, but i suggest you to use an MVC framework.
I have a PHP file which has code to echo some HTML. I would like to provide the PHP file to some end users which can be done like this:
<?php include 'file.php'; ?>
Unfortunately my users will for instance have index.html and this will not work. I don't want to ask my users to change there HTML file in to PHP. Another approach is to modify the .htaccess file:
<Files index.html>
AddType application/x-httpd-php .html
</Files>
I don't want to ask this of them as well. So what are my other options? Is it possible to show the echoed results in HTML file? Maybe with the help of some Javascript?
You can do this with AJAX. It might look a bit challenging, but it is frankly much simpler than many think. In fact, it's pretty easy.
Ajax goes in your javascript code, and looks like this:
$('#stSelect').change(function() {
var sel_stud = $(this).val();
//alert('You picked: ' + sel_stud);
$.ajax({
type: "POST",
url: "your_php_file.php",
data: 'theOption=' + sel_stud,
success: function(whatigot) {
alert('Server-side response: ' + whatigot);
} //END success fn
}); //END $.ajax
}); //END dropdown change event
Note that the data from the PHP file comes into your HTML document in the success function of the AJAX call, and must be dealt with there. So that's where you insert the received data into the DOM.
For example, suppose your HTML document has a DIV with the id="myDiv". To insert the data from PHP into the HTML document, replace the line: alert('Server-side response: ' + whatigot); with this:
$('#myDiv').html(whatIgot);
Presto! Your DIV now contains the data echoed from the PHP file.
The ajax can be triggered by a change to an control's value (as in the above example), or just at document load:
$(function() {
//alert('Document is ready');
$.ajax({
type: "POST",
url: "your_php_file.php",
data: 'Iamsending=' + this_var_val,
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
} //END success fn
}); //END $.ajax
}); //END document.ready
Look at this example for ideas on how it works.
Note that the above examples use jQuery, and therefore require this reference in the tags of your page:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
This will replace the body of the html page with the contents of the url called.
$('body').load( url,[data],[callback] );
If they can add javascript, an ajax request should do the work...
<script>
var req = new Request({
method: 'get',
url: 'file.php',
onRequest: function() { // loading image
},
onSuccess: function(response) {
document.getElementById("destination").innerHTML = response;
}
}).send();
</script>
They will also need a div for the code to get in:
<div id="destination"></div>