I dont know much about ajax or jquery yet but i currently have an ajax script that does successfully send A variable through and does work properly.
--the way i have it set up is like this for my loop:
<?php
$tt= mysql_query("SELECT * FROM monsters");
while ($row= mysql_fetch_array($tt))
{
$namee= $row['name'];
echo "<a id='namee' onclick='post();'>$namee</a>", "</br>";
}
which echos:
horseman
dragon
---the results do make a list of all the names from the table as shown above and they are clickable which is working great
my ajax request is this:
<script type="text/javascript">
function post(){
var hr = new XMLHttpRequest();
var url = "mess.php";
var vars =document.getElementById("namee").innerHTML;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("new").innerHTML = return_data;
}
}
hr.send(vars); // Actually execute the request
alert(vars);
}
</script>
the alert when i click on horseman returns "horseman"
but when i click on dragon it still alerts "horseman"
i would like to get the specific variable ( when i click horseman it says horseman and when i click dragon it says dragon etc) so i can send it through ajax to update a database ( which i already know to to set up)
please help me and show me if you can full code so i can learn and see how it works and understand your response since im new like i said :)
thanks in advance:
if have any questions feel free to ask
Thats because ids should be unique, jquery will get only the first element with that id, my suggestion is to pass the value by parameter:
echo "<a class='namee' onclick='post($namee);'>$namee</a>", "</br>";
And then the js:
function post(vars) {
var hr = new XMLHttpRequest();
var url = "mess.php";
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function () {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("new").innerHTML = return_data;
}
}
hr.send(vars); // Actually execute the request
alert(vars);
}
Related
<script src="jquery-3.2.1.min.js">
function ajax_post(){
loadScript('javascript/jquery-3.2.1.min.js');
// Create our XMLHttpRequest object
alert("button clicked");
// code for modern browsers
// Create some variables we need to send to our PHP file
var hr = new XMLHttpRequest();
var url = "comments.php";
var bid='<?php echo $b; ?>';
var userid='<?php echo $userid; ?>';
var cm = document.getElementById("latest_comment").value;
var vars = "your_comment="+cm+"&bookid="+bid+"&uid="+userid;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("comment").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("comment").innerHTML = "processing...";
}
</script>
this is javascript function which should run when i click the csubmit button, but when i click it the console gives an error written in the title. this function has to take the data written in the input tag, go to the comments.php page and insert it in database and display the comments in the comment div
I HAVE BEEN STUCK ON THIS ERROR FOR A VERY LONG TIME,BUT NOT ABLE TO FIND WHERE IS THE ERROR
<input type="button" id="csubmit" value="SUBMIT" onclick="ajax_post();">
Put ajax_post function in other script tag, you can not put JS code in script tag which already have src
<script src="jquery-3.2.1.min.js"></script>
<script>
function ajax_post() {
loadScript('javascript/jquery-3.2.1.min.js');
// Create our XMLHttpRequest object
alert("button clicked");
// code for modern browsers
// Create some variables we need to send to our PHP file
var hr = new XMLHttpRequest();
var url = "comments.php";
var bid = '<?php echo $b; ?>';
var userid = '<?php echo $userid; ?>';
var cm = document.getElementById("latest_comment").value;
var vars = "your_comment=" + cm + "&bookid=" + bid + "&uid=" + userid;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("comment").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("comment").innerHTML = "processing...";
}
</script>
This is the problem with your code: Your script is inside a <script> tag with a src attribute. When a src attribute is present, the content inside the <script> tag is completely ignored.
This should work:
<script src="jquery-3.2.1.min.js">
function ajax_post(){
loadScript('javascript/jquery-3.2.1.min.js');
// Create our XMLHttpRequest object
alert("button clicked");
// code for modern browsers
// Create some variables we need to send to our PHP file
var hr = new XMLHttpRequest();
var url = "comments.php";
var bid='<?php echo $b; ?>';
var userid='<?php echo $userid; ?>';
var cm = document.getElementById("latest_comment").value;
var vars = "your_comment="+cm+"&bookid="+bid+"&uid="+userid;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("comment").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("comment").innerHTML = "processing...";
}
</script>
echo "<input type=\"button\" id=\"csubmit\" value=\"SUBMIT\" onClick=\"<script type='text/javascript'>ajax_post();</script>\">";
when I click the csubmit button ajax_post method is not called, no alert is given and data is not getting inserted inside database which is done inside comments.php
<script>
function ajax_post(){
// Create our XMLHttpRequest object
alert("button clicked");
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "comments.php";
var bid='<?php echo $b; ?>';
var userid='<?php echo $userid; ?>';
var cm = document.getElementById("latest_comment").value;
var vars = "your_comment="+cm+"&bookid="+bid+"&uid="+userid;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("comment").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("comment").innerHTML = "processing...";
}
</script>
Replace with
echo "<input type=\"button\" id=\"csubmit\" value=\"SUBMIT\" onClick=\"ajax_post()\">";
I am not able to select text which i retrieve from directoryScanner.php file into the div container. So what ever gets displayed in div container , i cannot select it by mouse.
<div id="file_link_panel">
</div>
Following javascript code
function dirRefresher(){
ajax = new XMLHttpRequest();
ajax.open("POST","directoryScanner.php");
ajax.onreadystatechange = function(){
if(ajax.readyState ==4 & ajax.status == 200){
msg = this.responseText;
document.getElementById("file_link_panel").innerHTML = msg;
}
}
ajax.send();
}
setInterval(dirRefresher,1000);
And this simple php script named directoryScanner.php
<?php
echo "kunal";
echo "pankaj";
echo "shekhar";
?>
The problem is you are making tons of Ajax calls and updating the element over and over again so as you try to make the selection, it is being replaced. You are better off increasing the timeout and only firing the next one after you get the call back from the server. Also there is no need to replace the html, if the content is the same.
function dirRefresher(){
var ajax = new XMLHttpRequest();
ajax.open("POST","directoryScanner.php");
ajax.onreadystatechange = function(){
if(ajax.readyState ==4 & ajax.status == 200){
var msg = this.responseText;
var elem = document.getElementById("file_link_panel");
if(elem.innerHTML !== msg) {
elem.innerHTML = msg;
}
setTimeout(dirRefresher, 5000);
}
}
ajax.send();
}
dirRefresher()
If you need quicker updates, you should be looking into webSockets, not Ajax.
Try using innerText besides innerHTML:
You return from php just text so you need to include innerText. Like so:
function dirRefresher(){
ajax = new XMLHttpRequest();
ajax.open("POST","directoryScanner.php");
ajax.onreadystatechange = function(){
if(ajax.readyState ==4 & ajax.status == 200){
msg = this.responseText;
document.getElementById("file_link_panel").innerText= msg;
}
}
ajax.send();
}
setInterval(dirRefresher,1000);
I'm submitting a form through AJAX for the express purpose of displaying a pre-selected image. Selecting an image from the local drive will trigger the "onchange" event for the file-type input, and in turn call the AJAX routine. It works fine, and upon a successful "move_uploaded_file", the PHP handler returns the validated file name. The following illustrates how the AJAX submission was effected:
var xhr = new XMLHttpRequest();
var xForm = new FormData(document.forms.namedItem("form"));
xhr.open("POST", "handler.php", true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
document.getElementById("imgDiv").src = xhr.responseText;
}
}
xhr.send(xForm);
Instead of getting the handler to return the file name, is there any way to access the $_POST and $_FILES variables after returning from an AJAX submission? This is usually possible when returning from a normal form post, using:
<?php echo $_POST['stringInput'];?>
<?php echo $_FILES['imageInput']['fileName'];?>
but I'm not able to get anything in this case.
Thanking you,
Sofia
EDIT: in case it may be relevant, the handler is not in the same HTML script, but in a separate PHP file. Thanks again!
Because you made a mistake in code typing here:-
Old code
x.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
document.getElementById("imgDiv").src = xhr.responseText;
}
}
New code
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
document.getElementById("imgDiv").src = xhr.responseText;
}
}
Means replace x.onreadystatechange with xhr.onreadystatechange
I'm trying to send parametres from a .php file to my Javascript but I can't even manage to send a String.
Javascript fragment:
var params = "action=getAlbums";
var request = new XMLHttpRequest();
request.open("POST", PHP CODE URL, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.send(params);
request.onreadystatechange = function() {
var phpmessage = request.responseText;
alert(phpmessage);
};
PHP fragment:
$deviceFunction = $_POST["action"];
if ($deviceFunction == "") $deviceFunction = $_GET["action"];
// Go to a function depending the action required
switch ($deviceFunction)
{
case "getAlbums":
getAlbumsFromDB();
break;
}
function getAlbumsFromDB()
{
echo "test message!";
}
The alert containing phpmessage pops up but it's empty (it actually appears twice). If I do this the alert won't even work:
request.onreadystatechange = function() {
if(request.status == 200) {
var phpmessage = request.responseText;
alert(phpmessage);
}
};
The readystatenchange event will be called each time the state changes. There are 5 states, see here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#readyState
Rewrite your JS:
request.onreadystatechange = function () {
if (request.readyState == 4) {
console.log('AJAX finished, got ' + request.status + ' status code');
console.log('Response text is: ' + request.responseText);
}
}
In your code, you only check for the returned status code. The code above will check for the ready state and then output the status code for debbuging.
I know that this answer is more a comment than an answer to the actual question, but I felt writing an answer in order to include nicely formatted code.
I faced a similar problem working with Django. What I did:
I used a template language to generate the javascript variables I needed.
I'm not a PHP programmer but I'm going to give you the idea, let me now if works. The following isn't php code, is just for ilustrate.
<?php
<script type="text/javascript" ... >
SOME_VARIABLE = "{0}".format(php_function()) // php_function resolve the value you need
</script>
?>
The I use SOME_VARIABLE in my scripts.
Please specify your onreadystatechange event handler before calling open and send methods.
You also should make your choice between GET and POST method for your request.
If you want to popup your message only when your request object status is OK (=200) and readyState is finished whith the response ready (=4), you can write :
request.onreadystatechange = function() {
if (request.readyState==4 && request.status==200) {
var phpMessage = request.responseText;
alert(phpMessage);
}
};