I would like to be able to read XMLHttpRequest that is sent to a PHP page. I am using prototype's Ajax.Request function, and I am sending a simple XML structure.
When trying to print the POST array on the PHP page, I don't get any output.
Any help appreciated.
EDIT: Below is my code
<html>
<head>
<SCRIPT type="text/javascript" src="prototype.js"></script>
</head>
<body>
<script type="text/javascript">
var xml='<?xml version=1.0 encoding=UTF-8?>';
xml=xml+'<notification>';
xml=xml+'heya there';
xml=xml+'</notification>';
xml=xml+'</xml>';
var myAjax = new Ajax.Request('http://localhost:8080/post2.php',{
contentType: 'text/xml',
parameters: xml,
method: 'post',
onSuccess: function(transport){ alert(transport.status); alert(transport.responseText); }
});
</script>
</body>
</html>
post2.php
Welcome <?php print_r($_POST); ?>!<br />
You will read it exactly the sme way you read normal request vars.
$_GET['varname'] and $_POST['varname']
php://input allows you to read raw POST data like
Welcome <?php print(file_get_contents('php://input')); ?>!<br />
Note: php://input is not available with enctype="multipart/form-data".
When you use "method: post" and you want to send a post body, you need the parameter postBody. So something like this might work:
var myAjax = new Ajax.Request('http://localhost:8080/post2.php',{
contentType: 'text/xml',
postBody: xml,
method: 'post',
onSuccess: function(transport){
alert(transport.status); alert(transport.responseText);
}
});
But why did you build a XML doc around your content? You can simply sent the message "heya there" with the postBody without the XML arround.
Edit: Here you'll find all the Ajax.Request options: http://www.prototypejs.org/api/ajax/options
You could use fopen() with the input:// wrapper or $HTTP_RAW_POST_DATA.
Related
i have a page in php to execute query. when i need the parameter from another page with session using jquery. so, how to set session in php from session in jquery. please check my code and give me solution. thanks...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://code.ciphertrick.com/demo/jquerysession/js/jquerysession.js?d56ac9"></script>
<script>
$(document).ready(function(){
var sDecode = $.session.get("sesDecode");
alert(sDecode);
});
</script>
<?php
include('connection.php');
$content= ==> how to get " sDecode " ???
$upd = mysql_query("UPDATE t_modules set content='$content' where id_t_modules='3'") or die(mysql_error());
?>
You can use ajax to send parameter to a php file like this
$.ajax({
url: "connection.php",
data: "Session="+$.session.get("sesDecode"),
type: "POST",
dataType: 'json',
success: function (e) {
console.log(JSON.stringify(e));
},
error:function(e){
console.log(JSON.stringify(e));
}
});
Note that both solutions needs you to check the input since the user could potentially modify it.
Using Ajax
The best way to get sDecode is probably to send it via jQuery.post() (AJAX) to a PHP page that will register the session value (after doing the appropriate checks to it).
$.post('session.php', { d: sDecode }, function (response) {
alert(response);
});
and you get it in PHP via :
$sDecode = $_POST["d"]; // Please test the input here!
You might have to use .serialize() and then unserialize it in PHP depending on the content and how you treat it.
Using Redirection
You can simply redirect to a page and transmit it directly as a GET value:
window.location.href=”session.php?d="+sDecode;
Then on the session.php page you would read it using this code :
$sDecode = $_GET["d"]; // Please test the input here!
You can have PHP fill in the Javascript variable from the session variable.
<?php session_start(); ?>
<html>
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
var sDecode = <?php echo json_encode($_SESSION['sDecode']); ?>;
alert(sDecode);
</script>
PHP execute before Jquery so use ajax after get the parameter from session to do your query
My question is that how to pass query string variables on same page without refreshing the page in php? My code is given below:
<img src="a.jpg">
<?php
$a = $_GET['id'];
$b = $_GET['pid'];
?>
Please help me to resolve this issue
<html>
<head>
<title>Test</title>
<meta name="" content="">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#image_id").click(function(){
var dataString = 'a=10&b=20';
$.ajax({
type:'POST',
url:'foo.php',
data:dataString,
success:function(data) {
if(data=="Something") {
// Do Something
} else {
// Do Something
}
}
});
});
});
</script>
</head>
<body>
<img id="image_id" src="images/bg.jpg" />
</body>
</html>
Then in the 'foo.php' page do this
if(isset($_POST['a'])) {
// DO SOMETHING
}
Remember the things that you want to send to the 'data' of
success:function(data)
must be echoed out in the foo.php page
You can't.
PHP requires execution on the server and so you'd have to either use AJAX and update your page accordingly, or just refresh your page.
You can by sending an AJAX request to the server. Ajax is a way to send asynchronous request via Javascript. Notice that jQuery has a good library about it.
Use jquery to resolve this. By using the $.ajax in jquery you can do the stuff you need without page refresh.
I am trying to pass two variables (below) to a php/MySQL "update $table SET...." without refreshing the page.
I want the div on click to pass the following variables
$read=0;
$user=$userNumber;
the div Basically shows a message has been read so should then change color.
What is the best way to do this please?
here's some code to post to a page using jquery and handle the json response. You'll have to create a PHP page that will receive the post request and return whatever you want it to do.
$(document).ready(function () {
$.post("/yourpath/page.php", { read: "value1", user: $userNumber}, function (data) {
if (data.success) {
//do something with the returned json
} else {
//do something if return is not successful
} //if
}, "json"); //post
});
create a php/jsp/.net page that takes two arguments
mywebsite.com/ajax.php?user=XXX&secondParam=ZZZZ
attache onClick event to DIV
$.get("ajax.php?user=XXX&secondParam=ZZZZ". function(data){
// here you can process your response and change DIV color if the request succeed
});
I'm not sure I understand.
See $.load();
Make a new php file with the update code, then just return a json saying if it worked or not. You can make it with the $.getJSON jQuery function.
To select an element from the DOM based on it's ID in jQuery, just do this:
$("#TheIdOfYourElement")
or in your case
$("#messageMenuUnread")
now, to listen for when it's been clicked,
$("#messageMenuUnread").click(function(){
//DO SOMETHING
}
Now, for the AJAX fun. You can read the documentation at http://api.jquery.com/category/ajax/ for more technical details, but this is what it boils down to
$("#TheIdOfYourImage").click(function(){
$.ajax({
type: "POST", // If you want to send information to the PHP file your calling, do you want it to be POST or GET. Just get rid of this if your not sending data to the file
url: "some.php", // The location of the PHP file your calling
data: "name=John&location=Boston", // The information your passing in the variable1=value1&variable2=value2 pattern
success: function(result){ alert(result) } // When you get the information, what to do with it. In this case, an alert
});
}
As for the color changing, you can change the CSS using the.css() method
$("#TheIdOfAnotherElement").css("background-color","red")
use jQuery.ajax()
your code would look like
<!DOCTYPE html>
<head>
</head>
<body>
<!-- your button -->
<div id="messageMenuUnread"></div>
<!-- place to display result -->
<div id="frame1" style="display:block;"></div>
<!-- load jquery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
//attach a function to messageMenuUnread div
$('#messageMenuUnread').click (messageMenuUnread);
//the messageMenuUnread function
function messageMenuUnread() {
$.ajax({
type: "POST",
//change the URL to what you need
url: "some.php",
data: { read: "0", user: "$userNumber" }
}).done(function( msg ) {
//output the response to frame1
$("#frame1").html("Done!<br/>" + msg);
});
}
}
</script>
</body>
I feel like this is something that I should have learned by now, and I'm sure it's something small I'm missing, but I could use clarification to make sure my approach is correct.
I'm using AJAX to post data to self which is a file that contains php and html. I can write the php fine, but after a successful ajax post, how do I only return the data that is processed via php and not the remaining html? Is it better to just post to a separate script?
If you have the PHP handling the POST request in the beginning of the file, you can just do something like this:
<?php
if (isset($_POST['somevar'])) {
/* do something */
exit(0);
}
?>
exit() will stop the loading of the page at that line.
I, for one, think it's better to be utilizing a separate script to deal with dynamic AJAX requests.
You can scrape changed parts of the resulting document and insert them into the original page. This way you can also make your page work for a user with JavaScript disabled not doing anything specially.
Example:
<html><title>Unobtrusive AJAX Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script><script type="text/javascript">
$("form.ajax[id]").live('submit', function() {
$(this).find("input[type='submit']").attr("disabled", true);
$.ajax({
type: $(this).attr('method') || 'POST',
url: $(this).attr('action') || window.location.pathname,
data: $(this).serialize(),
context: $(this),
success: function(data) {
$(this).html(
$(data).find("#" + $(this).attr("id")).html()
);
}
});
return false;
});
</script>
</head><body>
<div><form method="post" class="ajax" id="main">
<p><?php echo date('H:i:s'); ?></p>
<p><input type="submit"></p>
</form></div>
<!-- keep the div: you got to have at least one div to make it work -->
</body></html>
It always depends on what are your needs, but if using the same script is enough for you then do it.
If you want the script not to send anything more than your answer to an XML HTTP Request, after sending the data, use an exit(); in PHP, which will make the script finish at that point.
Put to the of the script:
if($_POST['id']) {
$data = array('return'=>'returnValue');
$data = json_encode($data);
exit($data); }
Javascript:
$.ajax({
url: 'frmSelf.php',
data: $("#frmSelf").serialize(),
dataType: 'json',
type : 'post',
success : function(returnData) {
console.log(returnData);
}
});
I am trying to send html via jQuery's $.ajax() method, and then dump the html into a new .html file, but the content is getting cut off for some reason.
I have set up a test case:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script >
$(document).ready(function(){
var contents = $('html').html();
var filename = "test/000.html";
$.ajax({
type: "POST",
url: "/file.php",
data: "content="+contents+"&fn="+filename,
dataType: "html",
success: function(msg, ts, xh){
console.log(msg);
console.log(ts);
console.log(xh);
alert("success");
},
processData: false,
error: function(X, textStatus, error){
alert("Error saving... please try again now.")
}
});
});
</script>
</head>
<body>
<div id="rteContainer" class="dev">
<div id="textEditor">
<form>
<textarea name="balh" id="balh" rows="25" cols="103"></textarea>
<input type="button" id="updateContent" value="Update Changes">
<input type="button" id="closeEditor" value="Close Without Saving">
</form>
</div>
</div>
</body>
</html>
the file.php file is:
<?php
header("Content-type:text/html;charset:UTF-8");
$content = "<html>".stripslashes(urldecode($_POST["content"]))."</html>";
$dump_file = $_POST["fn"];
$fp = fopen($dump_file, 'w');
fclose($fp);
echo $content;
?>
Why is is getting cut off? I'm guessing it's come encoding problem, but I can't figure this out.
The html string, contents, has to be url-encoded before you POST it. Javascript provides the escape() function, just for this purpose.
Pass $('html').html() to escape() and assign it to contents, like so:
var contents = escape($('html').html());
Your script is dying of embarrassment at the massive security hole in it.
Never, ever, write into a file where the filename is a form parameter without validating the filename first. Even a novice hacker could use this script to overwrite any file on your system that the webserver has access to.
In your Ajax call, pass a { } style array of key value pairs in the data parameter, don't concatenate the variables with ampersands yourself:
data: { content: contents,
fn: filename }
Oh, and you're never actually writing the content into the dumpfile, so whatever file 'fn' points at will just get truncated.
Hope that helps...
I suspect that the ampersand in the javascript is causing a problem. Try replacing it with '&' and see if that fixes it.