Ajax is submitting the text, but not able to submit HTML data - javascript

I am working on a code that will fetch the data from textarea and submit it through ajax on button click.
In next step, PHP will create a file on server and store the ajax data into file.
I have already tried addslashes function of PHP, but that is not working.
I have tried to do it via the above method and its submitting the text data successfully. But the issue is with HTML data. I think it must be a parsing problem.
The HTML code
<textarea id="textareaCode"></textarea>
The Javascript code with Ajax
<script>
function makePage(){
var comment = document.getElementById('textareaCode').value;
alert (comment);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200)
alert("webpage " + xmlhttp.responseText + " was successfully created!");
}
var content = comment;
xmlhttp.open("GET","makePage.php?content=" + content,true);
xmlhttp.send();
}
</script>
And Finally the PHP code
<?php
$content = $_GET["content"];
$file = uniqid() . ".html";
file_put_contents("userdata/$file", $content);
echo $file;
?>
I am not getting any error message

You should do it with POST instead of GET, like Teemu said:
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
This row set the right header.
<textarea id="textareaCode"></textarea>
test
<script>
function makePage(){
var comment = document.getElementById('textareaCode').value;
alert (comment);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200)
alert("webpage " + xmlhttp.responseText + " was successfully created!");
}
var content = JSON.stringify({ comment: comment });
xmlhttp.open("POST","makePage.php",true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(content);
}
</script>
PHP:
<?php
$data = json_decode(file_get_contents('php://input'), true);
$content = $data['comment'];
$file = uniqid() . ".html";
file_put_contents("userdata/$file", $content);
echo $file;
?>

Post will work this way
function makePage(){
var data = document.getElementById('textareaCode').value;
$.post("makePage.php", {content: data}, function(result){
//Do something with the result
});
};
Then the php
$content = $_POST['content'] or $_REQUEST['content']

Related

Make a table based on the value of a drop down menu

I am stuck in a part where i am trying to fetch the data from php file to the script in json format . I am new to php just trying to learn from w3schools and i got stuck in HTTP method POST to send data to the PHP file and display in html but i am getting an error as
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse ()
at XMLHttpRequest.xmlhttp.onreadystatechange
And here is my code which i had done till now in front part i used html and javascript as :
<script>
function change_myselect(sel) {
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "table":sel, "limit":20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
txt += "<table border='1'>"
for (x in myObj) {
txt += "<tr><td>" + myObj[x].name + "</td></tr>";
}
txt += "</table>"
document.getElementById("demo").innerHTML = txt;
}
};
xmlhttp.open("POST", "get_email.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
}
</script>
<select id="get_email" name="get_email" onchange="change_myselect(this.value)">
<option value="">Choose an option:</option>
<option value="3">Customers</option>
<option value="4">Products</option>
<option value="5">Suppliers</option>
</select>
<p id="demo"></p>
And here is my php file :
<?php
include("admin/include/config.php");
$id=$_POST['get_email']
if(isset($_POST['$id'])){
$sql=mysql_query("select * from subscription where id=".$id);
$returnArray = array();
while ($row=mysql_fetch_array($sql)){
$returnArray =
array("email"=>$row['email'],"creationDate"=>$row['creationDate']);
}
// return JSON response.
header('Content-Type: application/json');
echo json_encode($returnArray);
}
Can you suggest me what i am doing wrong in the above script . Thanks in Advance
You've some error in PHP code, you're just printing the email. That's not a JSON string.
Read this to know more about JSON: https://www.w3schools.com/js/js_json_intro.asp
By reading your JS code you're accessing name from the object, so may need to change the PHP script as follow,
<?php
include("admin/include/config.php");
$id=$_POST['get_email']
if(isset($_POST['$id'])){
$sql=mysql_query("select * from subscription where id=".$id); // You missed semi colon here.
$returnArray = array();
while ($row=mysql_fetch_array($sql)){
$returnArray = array("email"=>$row['email'],"name"=>$row['name']); // assuming column name exists.
}
// return JSON response.
header('Content-Type: application/json');
echo json_encode($returnArray);
}

sending sms through javascript command because curl is not working on server?

$adm=$_POST["admno"];
$phn=$_POST["phn1"];
include("model.php");
$db = new database;
$r=$db->register($adm,$schoolcode);
while($row=mysql_fetch_array($r))
{
if($row["phn_no1"]==$phn || $row["phn_no2"]==$phn || $row["phn_no3"]==$phn)
{
$formatted = "".substr($phn,6,10)." ";
$password = $formatted + $adm;
echo $password;
$db->setpassword($adm,$password,$schoolcode);
$pre = 'Dear%20Parents,Your%20Password%20is%20';
$suf = '%20ThankYou.CV';
$sms = $pre.$password.$suf;
session_start();
?>
<script>
window.onload = function(){
{
$("#active"+id).css({"color":"red"});
var http = new XMLHttpRequest();
var url = "http://www.perfectbulksms.in/Sendsmsapi.aspx?USERID=UID&PASSWORD=UPASS$&SENDERID=SID&TO=<?php echo $phn; ?>&MESSAGE=<?php echo $sms;?>";
var adm = "<?php echo $admno; ?>";
var params = "Id="+ id +"&adm="+adm;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
//alert(http.responseText);
}
}
http.send(params);
window.location.href="#";
}
};
</script>
<?php
header("Location:password.php?msg=new");
this code is not working .. well it is change my password according to code but not sending the sms .. i m not using curl command because it works fine on localhost but on server it is not working..
This is not the right approach, if CURL is not available on your server then install it and then use CURL.
CURL installation process is defined here:
Help Doc
Help Doc

Updating javascript array with click when new mysql data comes in

I am using the following code to send mysql database content into a javascript array. This works fine when I start the page, but when the database gets a new entry, the new entries are not added to the array when I rerun this bit of code - unless I reload the entire page.
<p><button onclick="save_image()">Send image</button></p>
<script type="text/javascript">
function save_image(){
var userName =
<?php
$conn = new mysqli(.........."); //connect to database
$d = mysqli_query($conn, "SELECT name FROM canvas_data" );
$usernames = array();
while( $r = mysqli_fetch_assoc($d) ) {
$usernames[] = $r['name'];
}
echo json_encode( $usernames );
?>;
console.log(userName)
}
</script>
I realize there are other pages about this topic, but I didn't know how to apply them to my case. If you have some ideas. Thanks.
If you want to get information from the database without reloading the page, you'd need to do an Ajax request to retrieve the information.
Something like this would work:
PHP - ajaxendpoint.php
<?php
$d = mysqli_query($conn, "SELECT name FROM canvas_data" );
$usernames = array();
while( $r = mysqli_fetch_assoc($d) ) {
$usernames[] = $r['name'];
}
echo json_encode( $usernames );
?>
JavaScript
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText); //log the response from the database
//if the PHP is returning a JSON object, you can parse that:
var myArray = JSON.parse(xhttp.responseText);
}
}
xhttp.open("GET", "ajaxendpoint.php", true);
xhttp.send();
}
HTML - index.html
<button onclick="getData()">
Load Data via Ajax
</button>
Here is another example Ajax request in this JS Fiddle: https://jsfiddle.net/igor_9000/77xynchz/1/

AJAX: showing updated variable after button click

I just started to use AJAX, so I apologize if the question is very basic.
I use a simple AJAX script to update a session variable depending on which button you click, but I cant get it to update the heading with the new value when clicking the button. At the moment I got a button to reload the page, but I want to remove that and make the header update on each buttonclick.
index.php
<?php session_start(); ?>
<html>
<head>
<script type='text/javascript'>
function setSession( value) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "setSession.php?variable=rider&value=" + value, true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
echo "<h1>You selected: " . $_SESSION['rider'] . "</h1>";
echo "<button type='button' onclick='javascript:setSession(this.value)' value='Kristoff'>Kristoff</button> ";
echo "<button type='button' onclick='javascript:setSession(this.value)' value='Edvald Boasson Hagen'>Edvald Boasson Hagen</button> ";
echo "<input type='submit' value='Re-Load Page'>";
?>
</body>
</html>
setSession.php
<?php
session_start();
if(isset($_REQUEST['variable']) && isset($_REQUEST['value']))
{
$variable = $_REQUEST['variable'];
$value = $_REQUEST['value'];
$_SESSION[$variable] = $value;
}
?>
#Chris and #tej explains the procedure.This is how you do it.
setSession.php
<?php
session_start();
if(isset($_REQUEST['variable']) && isset($_REQUEST['value'])){
$variable = $_REQUEST['variable'];
$value = $_REQUEST['value'];
$_SESSION[$variable] = $value;
echo $_SESSION[$variable];
}
?>
index.php
echo "<h1 id='selection'>You selected: " . $_SESSION['rider'] . "</h1>";
function setSession( value) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "setSession.php?variable=rider&value=" + value, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("selection").innerHTML = "You selected ".xmlhttp.responseText;
}
}
xmlhttp.send();
}
At the moment index.php is only loaded once. Therefore $_SESSION['rider'] has been output once and only once so it won't change. You need to use javascript to read the response from the xhr you're doing (and at the same time output $_SESSION['rider'] in the setSession.php file.
I'm not sure of what your application is trying to do but this can be achieved without any php at all.
After triggering ajax call you have to modify the h1 already displayed.
Add a class to h1 and use jQuery or JavaScript to modify the value once ajax is complete.
if(xhr.status===200){
$('.header').text(//rider text);
}
This will set the value after ajax and if user refreshes page it will automatically load from session.
But as other answer suggests this can easily be attained without php itself but I will leave application technology decision to you.

Using Php, mySql, ajax, (xmlhttp) and JS,how can i create a php multidimensional send it to JS and use it?

I looked a lot on the internet and wasn't able to find the answer i need, so here i come to you.
What i have : A database which look like this :
name latitude longitude
---- --------- ----------
foo 13.323 -51.356
foo 54.698 2.487
What i want to do : I need to retrieve the latitude and longitude from a mysqli request done with php and use it in a function that i defined.
My problem : I'm trying to use xmlrequest but it apparently doesn't work.
The code : JS :
var selI = document.getElementById("nameIti");
selI.onchange = function(){
var val = this[this.selectedIndex].getAttribute("value");
showMark(val);
}
function showMark(str){
var xhr;
if(str==""){
return;
}
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}
else{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status ==200){
var object = JSON.parse(xhr.responseText);
for(var a in object){
newMark(v['lat'], v['lng']);
document.getElementById("pi").innerHTML=JSON.parse(xrh.responseText); // This is a test to display any kind of result.
}
}
}
xhr.open("GET", "getpos.php?q="+str, true);
xhr.send();
}
PHP :
<?php
$nom = $_GET['q'];
include("connexion.php");
$con = connect_LIF4();
$req1= "SELECT Latitude, Longitude FROM etape LEFT JOIN itineraires ON NomLieu=nomEtape WHERE nomIti LIKE '%$nom%'";
$result1 = mysqli_query($con, $req1);
$data = array();
while($row = mysqli_fetch_array($result1){
$data['lat'] = $row['Latitude'];
$data['lng'] = $row['Longitude'];
$resp[] = $data;
}
echo json_encode($resp);
mysqli_close($con);
?>
I tried to use newMark(lat, lng)(Which i coded and works fine) with random values, in showMark outside the onreadystatechange and it works, but i need to use it with the values retrieved from the php.
One problem with your PHP is that
while($row = mysqli_fetch_array($result1){
is missing the second brace. It should be:
while($row = mysqli_fetch_array($result1)){
Also the URL in the ajax request should be the full URL, not just getpos.php
Thirdly you have written xrh.responseText (should be xhr).
Basically there's loads of syntax errors in your code - you should use the javascript console to debug the front end ones, and PHP logging or error display for the back end ones. You should only need help here once you've debugged all obvious syntax errors.
EDIT - below is a working example (although I haven't done the MySQL part)
JS + HTML:
<span id='pi'></span>
<select id='nameIti'>
<option value='foo'>foo</option>
<option value='bar'>bar</option>
</select>
<script>
function newMark(lat,lng) {
console.log(lat);
console.log(lng);
}
var selI = document.getElementById("nameIti");
selI.onchange = function(){
var val = this[this.selectedIndex].getAttribute("value");
showMark(val);
}
function showMark(val){
var str=val;
var xhr;
// if(str==""){
// return;
// }
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}
else{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status ==200){
var result = JSON.parse(xhr.responseText);
console.log(result);
for(var a in result){
newMark(result[a]['lat'], result[a]['lng']);
document.getElementById("pi").innerHTML = result[a]['lat'] + ', ' + result[a]['lng'];
}
}
}
// xhr.open("GET", "getpos.php?q="+str, true);
xhr.open("GET", "getpos.php?q="+str, true);
xhr.send();
}
</script>
PHP:
<?php
$nom = $_GET['q'];
$data = array();
if($nom == 'foo') {
$data['lat'] = '5.12';
$data['lng'] = '0.34';
$resp[] = $data;
}
else if($nom == 'bar') {
$data['lat'] = '2.34';
$data['lng'] = '1.34';
$resp[] = $data;
}
echo json_encode($resp);
?>

Categories

Resources