I'm trying to send the id of a clicked element via ajax to php. But it isn't working. The value is being sent from php file (contacts.php) to the javascript function callMessage(id) (which does return the right id when clicked), it is then calling the php file (get_message.php) which is supposed to query the result which has the right id. But when I echo the id it returns "Undefined variable".
Here's my code:
contacts.php
<div id="<?php echo $row['id']; ?>" onclick="callMessage(this.id)">
</div>
<div id="createMsg"></div>
contacts.js
function callMessage(id) {
var http = new XMLHttpRequest();
var url = 'includes/get_message.php';
http.open('GET', url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
document.getElementById("createMsg").innerHTML = this.responseText;
}
}
console.log(id);
http.send('id='+id);
}
here console.log(id) does return the id of the element that was clicked.
get_message.php
if(isset($_GET['id'])) {
$msg_id = $_GET['id'];
}
echo $msg_id;
The echo here returns "Undefined variable: msg_id". I've also tried using POST request to send the id value but that hasn't worked either.
A couple of issues:
echo $msg_id; should be inside the if in the PHP. Logically you don't want to echo that if it isn't populated, I would expect.
As per https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send, the 'id='+id will be added to the request body, whereas $_GET in PHP tries to retrieve values from the querystring. Therefore you need to attach the value to your url variable, and url-encode it.
So
if(isset($_GET['id'])) {
$msg_id = $_GET['id'];
echo $msg_id;
}
else echo "No ID supplied";
and
var url = 'includes/get_message.php?id=' + encodeURIComponent(id);
...
http.send();
is the correct solution here.
You are placing the data in a GET request with the 'send' function.
Submitting data via send is relevant for POST & PUT.
Data under send() for GET & HEAD will be replaced with NULL.
If you're using GET method use the URL parameter:
var url = 'includes/get_message.php?id=' + encodeURIComponent(id);
Related
Here is the situation.
I'm trying to pass from some Javascript values to various PHP functions within my ajax so it can properly be displayed on the page.
Here is my code:
$("[data-department-id]").click(function() {
id = $(this).attr('data-department-id');
document.getElementById('department'+id).innerHTML = '';
$.ajax({
url:"/desk/template/fetchtickets.php",
type: 'POST',
dataType: 'json',
data : {
'id' : id
},
success: function (res) {
$('#department'+id).append('<ul>');
for (var key in res) {
var ticketId = res[key].id;
var clientId = res[key].clientid;
var clientName = res[key].name;
var clientColor = res[key].hexColor;
<?php $ticketId = '"+ticketId+"'; ?>
<?php $clientId = '"+clientId+"'; ?>
<?php $clientName = '"+clientName+"'; ?>
<?php $clientColor = 'clientColor'; ?>
$('#department'+id).append('<li class="list-group-item list-group-item-light" data-date-2="<?php echo Ticket::lastReplyStamp($ticketId); ?>"> <span class="text-width">'+res[key].ticket+' '+res[key].subject+'</span><div class="tools" ><span class="client-listing"> <?php clientBadge($clientId,$clientName,$clientColor); ?> <?php // echo "<scipt>document.writeln(test)</script>"; ?> '+test+' </div></div></li>');
}
$('#department'+id).append('</ul>');
}
});
})
When I do a console.log();
It shows the proper value, however, when I do an echo $ticketId, it shows +ticketId+ .
Now I did do a document.write and document.writeln and it still doesn't work.
Is there a proper solution to resolve my problem?
You can not add php code here.You can use JQuery to change value in the Dom or set some hidden inputs value, but you can not set php variable in JS. PHP runs on the server side. When the php code is running, your js code is waiting to be run on the client's computer.
These line are always going to be interpreted as string assign from server side.
<?php $ticketId = '"+ticketId+"'; ?>
<?php $clientId = '"+clientId+"'; ?>
<?php $clientName = '"+clientName+"'; ?>
<?php $clientColor = 'clientColor'; ?>
The order of your code processing is something like this :
PHP code get processed
PHP returns HTML
User clicks an element (in your case data-department-id)
JQuery sends ajax request
Server processes the request and sends response back to the frontend
Ajax success function receives the response and now has the response in javascript variable res which is passed as argument of success(res) function
All the code inside success is executed
Alternatively if the server throws an error response, no 6. and 7. would trigger the error callback
But the main part it, the PHP code in your success() function will NOT run as you are thinking, which is after the Ajax receives response. At this point all you can do is use javascript to manipulate the variables.
So in short, change below part and use javascript or jQuery if you have it to change DOM elements based on response.
<?php $ticketId = '"+ticketId+"'; ?>
...
...
For example, let's say you have an H1 tag which shows ticket id. You would do
// jQuery
$('#ticketIdElement').text(res.id);
The problem is when I click on "submit data" button I get the response (this is correct), but when I click on "go to the php file" link (which is the same php file as previously) I get Undefined index: firstname and Undefined index: lastname error. How can I fix it?
Here is my code:
<html>
<head>
<script>
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "my_parse_file.php";
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var vars = "firstname="+fn+"&lastname="+ln;
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("status").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("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
First Name: <input id="first_name" name="first_name" type="text"> <br><br>
Last Name: <input id="last_name" name="last_name" type="text"> <br><br>
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();"> <br><br>
<div id="status"></div>
go to the php file
</body>
and the php file
<?php
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
?>
Because both are different requests :
As you are passing parameters firstname and lastname using AJAX. You have to pass the same in URL using GET request.
go to the php file
<?php
echo 'Thank you '. $_REQUEST['firstname'] . ' ' . $_REQUEST['lastname'] . ', says the PHP file';
?>
Output :
Thank you abc xyz, says the PHP file
It will work in both Submit button and Hyperlink.
By clicking the link your browser sends not a POST request, but a GET request to your server-side. That is why the global array $_POST doesn't contains the elements you are trying to retrieve in your PHP file. The error message points you that there is no such elements in the $_POST array like "firstname" and "lastname".
It is recommended to add a check whether the array elements exist like so:
<?php
if (isset($_POST['firstname']) && isset($_POST['lastname'])) {
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
} else {
echo 'Nothing to say';
}
Thanks R J for explanation. Now i fixed it and works properly.
But I am worried, because i used this code only for training. In my main problem i need to send the real object (not string etc.) by ajax to my php site, so i cant add it to the url, can I?
When I make a .post() request such as
var data = $(this).serialize();
$('form').on('submit', function(event) {
event.preventDefault();
$.post('server.php', data, function(data) {
$('#data').append('<p>' + data + '</p>');
});
});
everything's working - the name from the database appends to the #data element withing the p tags. But, when I try to pass data as an object like this
var data = $(this).serialize();
$.post('server.php', {id: data}, function(data) {
$('#data').append('<p>' + data + '</p>');
});
than it doesn't work. I tried changing the argument of the function within the .post() to id and probably every combination of names for .post()'s arguments and variables within the PHP file also, without success. Here's the working intact PHP file compatible with the first version of my .post() request in this question:
<?php
$id = $_POST['id'];
$connection = new mysqli('localhost', 'root', '', 'dummy_db');
$query = 'SELECT name FROM dummy_db_table WHERE id = "' . $id . '"';
$result = $connection->query($query);
$row = $result->fetch_assoc();
echo $row["name"];
$connection->close();
?>
Please note that the name of the input field for the ID in the HTML file is 'id'. I do understand that it is this name attribute within HTML which helps PHP determine the value of it, but how is it doing so without me specifying the connection with the PHP through form's action attribute? I'm doing this exclusively through AJAX (.post()) and AJAX is not telling PHP anything specific about THAT id field. What am I missing here? Also, how would I go about sending the object of values instead of a single one through .post()'s data attribute? Thank you.
You have not add the form code here so lets assume your form have two fields name and address.
Actually you need to put the serialize() function under the event. Like
$('form').on('submit', function(event) {
event.preventDefault();
var data = $(this).serialize();
$.post('server.php', {id: data}, function(data) {
$('#data').append('<p>' + data + '</p>');
});
});
Now on your server.php file if you print the following line:
$id = $_POST['id'];
echo $id;
this will show you the results like: name=iffi&address=UK
I hope this will help you more.
What is it that I am doing wrong? the value of myid1 is not being accepted by my PHP script. My Javascript code is below followed by my PHP script. Please help.
Javascript code
function generaterepno(selectedid) {
var idnum=selectedid;
var idnum1=idnum.split(":",1);
var text='[{"myid1":idnum1}]';
var httpc = new XMLHttpRequest();
var url = "reportnumber.php";
httpc.open("POST", url, true); // sending as POST
httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpc.setRequestHeader("Content-Length", text.length);
httpc.onreadystatechange = function() {
if(httpc.readyState == 4 && httpc.status == 200) {
alert(httpc.responseText);
var myArr = JSON.parse(httpc.responseText);
}
httpc.send(text);
document.getElementById('genno').value=idnum1;
}
My PHP is as follows-
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$mynewid=$_POST["myid1"];
$mynewid=strip_tags($mynewid);
include("inc_con.php");
$myquery="SELECT MAX(report_number) AS mrepno FROM childreports WHERE child_id='$mynewid' ORDER BY report_number";
$myresult=mysql_query($myquery);
if(!$myresult) {
$outp = '[{"reportn":"0"}]';
echo ($outp);
die('records do not exist');
}
$outp = "[";
while($rm = mysql_fetch_array($myresult)) {
$outp .= '{"reportn":"'.$rm["mrepno"].'"}';
}
$outp .="]";
mysql_close($con);
echo ($outp);
?>
I am a newbie to JSON and Javascript. Been trying to learn it on my own by reading. The alert message of the responseText is displaying a notice that myid1 is not defined. Also in my Javascript the HTML id genno is supposed to get the the return value from PHP code that is the max report number as obtained from the SQL query. Once I get reportn variable with some value I can JSON parse it and put it in the genno id but my problem is sending the myid1 value properly to my PHP script reportnumber.php.
Can someone help please? Thanks!
After prompt and great help from Kyle I made some changes in my Javascript function as follows and my query appears in the comments section below.
function myFunction(arr) {
var tempans = arr.reportn;
var myans = 0;
if(tempans.length == 0) {
var asknum = prompt('Enter previous report number:');
myans = parseInt(asknum)+1;
} else {
myans = parseInt(tempans)+1;
}
document.getElementById('genno').value=myans;
}
Why am i prompted TWICE for a user input?
You have a problem here. var text='[{"myid1":idnum1}]'; is not valid JSON because you're trying to put the variable idnum1 inside the string. It would be easier to set it in an object and then use JSON.stringify() to convert it to JSON.
var text = JSON.stringify({"myid1": idnum1});
In PHP, you then need to decode it from the request body as it won't be set in $_POST.
$contents = json_decode(file_get_contents("php://input"), true);
$myNewId = $contents['myid1'];
I am following this post:Can't get html5 Canvas signature pad to submit to database, and is a great signature script, but I already have a error when I tried to save it into DB...the console give me this error:
Error: Failed to construct 'XMLHttpRequest': Please use the 'new' operator, this DOM object constructor cannot be called as a function.
Can you help me with this part of javascript to fix it:
$("#saveSig").click(function saveSig() {
//encode URI
var sigData = encodeURIComponent(canvas.toDataURL("image/png"));
$("#imgData").html('Thank you! Your signature was saved');
var ajax = XMLHttpRequest();
ajax.open("POST", 'sign/signature.php');
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(sigData);
$('#debug').html(sigData);
});
The error message says what you should do: you should use the 'new' operator to construct 'XMLHttpRequest'.
Where you create your ajax object, change var ajax = XMLHttpRequest(); to var ajax = new XMLHttpRequest();
Since you are using jquery anyway, you can use jquerys ajax method to make the ajax request instead of dealing with the browser specifics of XMLHttpRequest.
$("#saveSig").click(function saveSig() {
//encode URI
var sigData = encodeURIComponent(canvas.toDataURL("image/png"));
$.ajax({
type: "POST",
url: 'sign/signature.php',
contentType: 'application/upload',
data: sigData,
success: function () {
$("#imgData").html('Thank you! Your signature was saved');
}
});
$('#debug').html(sigData);
});
Update In response to you comments:
You must understand, that this javascript and the... click(function saveSig() {...} is executed in the browser. So you shouldn't put any php in there, because the php must be executed by the webserver. When you click on the "#saveSig" element, the browser executes this function and with the call of $.ajax(...) it sends a new HTTP POST request to the webserver in the background calling the url 'sign/signature.php'. The response data to that request is available to the success function. Here follows an example of how the webserver (php) and the browser (javascript) could work together.
sign/signature.php
<?php
// read the request data:
$sigData = (isset($_POST['data'])) ? $_POST['data'] : "";
$user_id = (isset($_POST['UserId'])) ? $_POST['userId'] : "";
// process your sigData here (e.g. save it in the database together with the user_id)
//generate the response:
echo "Successfully saved signature for user id: ".$user_id.".";
?>
javascript:
$("#saveSig").click(function saveSig() {
//encode URI
var sigData = encodeURIComponent(canvas.toDataURL("image/png"));
$.ajax({
type: "POST",
url: 'sign/signature.php',
contentType: 'application/upload',
data: {
data: sigData,
user_id: $('#user_id').val() // this get's the value from the hidden user_id input
},
success: function (responseData) {
$("#imgData").html('Thank you!' + responseData);
}
});
$('#debug').html(sigData);
});
Maybe the AJAX Introduction by w3schools is interesting to you
I already found the answer!
this is the hidden input in the canvas:
<input type="hidden" value="<?php echo $user_id; ?>" name="user_id" id="user_id" />
here is the code which will run this script:
$("#saveSig").click(function saveSig() {
//encode URI
var sigData = canvas.toDataURL("image/png");
var user_id = $("#user_id").val(); //here the id is showed, like 1, 2, etc
$("#firm").html("Thank you! Your signature was saved with the id: "+user_id);
$("#debug").html(sigData);
var ajax = new XMLHttpRequest();
ajax.open("POST", "sign/signature.php",false);
ajax.onreadystatechange = function() {
console.log(ajax.responseText);
}
ajax.setRequestHeader("Content-Type", "application/upload");
ajax.send("imgData="+sigData);
// ajax.send("user_id"+user_id); //here give me this error: InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.
});
DB connection:
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
$session_id = $_SERVER['REMOTE_ADDR'];
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
//$user_id = (isset($_POST['user_id'])) ? $_POST['user_id'] : ""; //not works
//$user_id = $_POST['userId']; //not works
$user_id = '1'; // when I put a number the id is saved
// process your sigData here (e.g. save it in the database together with the user_id)
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
//echo "unencodedData".$unencodedData;
$imageName = "sign_" . rand(5,1000) . rand(1, 10) . rand(10000, 150000) . rand(1500, 100000000) . ".png";
//Set the absolute path to your folder (i.e. /usr/home/your-domain/your-folder/
$filepath = "../signature/" . $imageName;
$fp = fopen("$filepath", 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
//Connect to a mySQL database and store the user's information so you can link to it later
include_once("CONN/configs.php");
try{
$statement = $conn->prepare("INSERT INTO SIGNATURE (`session`, `user_id`, `signature`) VALUES (?, ?, ?)");
if ($statement->execute(array($session_id, $user_id, $imageName)));
echo '<div class="alert alert-success">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
Firma con id: '.$user_id.' guardada correctamente.</div>';
}
catch (Exception $e)
{
echo '<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
Error al tratar de guardar la firma.</div>';
die;
}
}
?>
I hope someone will need this.
Best regards!