Ajax: how to do it?
Solved
sevs
-
sevs -
sevs -
Hello,
I am looking to configure an AJAX script that would allow me to save the data from a textarea.
The question is how can I correctly retrieve the variable in my PHP?
Configuration: Windows / Chrome 54.0.2840.99
I am looking to configure an AJAX script that would allow me to save the data from a textarea.
The question is how can I correctly retrieve the variable in my PHP?
Configuration: Windows / Chrome 54.0.2840.99
4 réponses
Sure....
I've finally decided to code.
First of all.. I didn't realize you were using CKEditor. (which is not the same as a simple textarea).
On the HTML side, it looks like this:
And for the PHP:
P.S.: Remember to modify your variables with your database connection info
Next...
[]
Best regards,
Jordane
I've finally decided to code.
First of all.. I didn't realize you were using CKEditor. (which is not the same as a simple textarea).
On the HTML side, it looks like this:
<html> <head> <meta charset="utf-8"> <title>news</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> <!-- Make sure the path to CKEditor is correct. --> <script src="ckeditor.js"></script> </head> <body onload='timer()'> <form action="Mail3" method="POST"> <textarea name="editor1" id="editor1" rows="10" cols="80" placeholder="Enter your message here"></textarea> <input type="submit" name="submit" value="send"> </form> <input id="infosMsg" value="" style="width:200px;"> <script text="javascript"> var ck = CKEDITOR.replace('editor1').on('change', function(e) { if (document.activeElement.nodeName == "IFRAME") { var thisHTML = e.editor.getData(); var tempDiv = $('<div>').html(thisHTML); thisText = tempDiv.text(); note(thisText); } }); function note(value){ var data = {'text':value}; var urlAjx = "brouillon.php"; //for testing console.log(" Note = " + value ); //send ajax $.ajax({ async : false, type: "POST", url: urlAjx, data: data, dataType: 'json', success: function(response) { //console.log(response); $("#infosMsg").val(response.result); }, error: function(xhr, status, error) { var err = eval("(" + xhr.responseText + ")"); alert(err.Message); } }); } </script> </body> </html> And for the PHP:
<?php //display php errors error_reporting(E_ALL); $result = array(); //return variable at the end of the script //Proper retrieval of variables $text = isset($_POST['text']) ? $_POST['text'] : ''; // ----- /!\ ------- //Variables to modify with your info $bddName = "mabdd"; $user = "root"; $pwd = ""; //Connect to the DB try{ $bdd = new PDO('mysql:host=localhost;dbname='.$bddName.';charset=utf8', $user, $pwd); $bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $bdd->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); } catch(PDOException $e) { $result['error'][] = 'Error: ' . $e->getMessage(); } $sql = 'UPDATE test set message= :txt'; $datas = array(":txt"=>$text); if($bdd){ try{ $req = $bdd->prepare($sql); $req->execute($datas); $result['result'] = 'Draft saved '.date(' h:i:s A'); }catch(Exception $a){ $result['error'][] = "Error! ".$e->getMessage(); $result['result'] = "Insertion failed" ; $result['error'][] = $_POST; } }else{ $result['error'][] = "Database connection problem:".$bddName; } //Return the result in json echo json_encode($result); ?> P.S.: Remember to modify your variables with your database connection info
Next...
[]
WARNING: You absolutely need to have your php files encoded in UTF8 as well as your DB.
Check here: https://forums.commentcamarche.net/forum/affich-37584944-php-html-caracteres-accentues-et-l-utf8Best regards,
Jordane
An AJAX request is a standard HTTP request, it is just executed asynchronously. You can send parameters via AJAX like this:
To retrieve the value in PHP, you just need to proceed as usual.
--
- "If it’s not on the computer, it doesn’t exist."
$.ajax({
type: $(this).attr("method"), // POST OR GET
url: $(this).attr("action"), // URL TO CALL
data: $(this).serialize(), //PARAMETERS
success: OnSuccess // CALLBACK
});.
To retrieve the value in PHP, you just need to proceed as usual.
--
- "If it’s not on the computer, it doesn’t exist."
Thank you for your reply.
But how can I modify this so that everything is automated?
I read online that it is possible to make copies of a message we are typing using AJAX.
Thank you.
But how can I modify this so that everything is automated?
I read online that it is possible to make copies of a message we are typing using AJAX.
<script text="javascript"> function timer() { comp=(setTimeout("go()",5000)); } function getXhr(){ var xhr = null; if(window.XMLHttpRequest) // Firefox and others xhr = new XMLHttpRequest("post","",true); else if(window.ActiveXObject){ // Internet Explorer try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } } else { // XMLHttpRequest not supported by the browser alert("Your browser does not support XMLHTTPRequest objects..."); xhr = false; } return xhr } function go() { var xhr = getXhr() // Define what we will do when we have the response xhr.onreadystatechange = function() { // We only do something if we have everything received and the server is ok if(xhr.readyState == 4 && xhr.status == 200) { var html = xhr.responseText; document.getElementById('cible').innerHTML = html; } } xhr.open("POST","draft",true); xhr.send(null); setTimeout('go()',5000); } </script> Thank you.
Thank you for your piece of code. However, since I am a young AJAX coder, I do not understand which function I can use to automate the saving at regular intervals and to fetch everything to save it in my database. Given that it doesn't even call my PHP script anymore, I can't see the echo that I've done.
Hello,
If by "regular interval" you mean: as the user types.... then you can use onkeyup or onkeypress on your textarea
https://html.com/attributes/textarea-onkeypress/
Otherwise, if you really want to do it at regular intervals... in JavaScript there are the setTimeout and setInterval functions
However, you forgot to send the data to your PHP script (you need to include the variables during the SEND
Afterward... as suggested by douarfyduck .. it is preferable to use AJAX in jQuery
Here is a complete example: https://forums.commentcamarche.net/forum/affich-33258760-remplir-un-formulaire-dynamiquement-en-fonction-d-une-combobox#2
--
Best regards,
Jordane
What function can I use to automate the registration at regular intervals
If by "regular interval" you mean: as the user types.... then you can use onkeyup or onkeypress on your textarea
https://html.com/attributes/textarea-onkeypress/
Otherwise, if you really want to do it at regular intervals... in JavaScript there are the setTimeout and setInterval functions
However, you forgot to send the data to your PHP script (you need to include the variables during the SEND
xhr.send(tesparams);
- tesparams could be in the form of:
var text = document.getElementById('id_de_ton_textarea').value; var tesparams = "nomeavariablequetuveux="+text ; Afterward... as suggested by douarfyduck .. it is preferable to use AJAX in jQuery
Here is a complete example: https://forums.commentcamarche.net/forum/affich-33258760-remplir-un-formulaire-dynamiquement-en-fonction-d-une-combobox#2
--
Best regards,
Jordane
Good evening Jordane45;
First of all, thank you for all your advice. I'm interested in your onkeypress function, so I did some research http://stackoverflow.com/questions/33944951/save-content-of-textarea- Is it like this? Or am I really starting off on a very bad footing by following this tutorial?
First of all, thank you for all your advice. I'm interested in your onkeypress function, so I did some research http://stackoverflow.com/questions/33944951/save-content-of-textarea- Is it like this? Or am I really starting off on a very bad footing by following this tutorial?
I continue to swim...
To be honest, it's no longer swimming but it's like I'm drowning...
I don't understand where my mistake is. I master PHP perfectly, and I admit that I'm struggling with JS
The code on the html page
Usually, I include my connection data; I will fix everything once I understand the trick well.
To be frank, I don't want ready-made code; otherwise I won't learn. Just a pointer to my mistakes
Thank you for all the time you give me.
To be honest, it's no longer swimming but it's like I'm drowning...
I don't understand where my mistake is. I master PHP perfectly, and I admit that I'm struggling with JS
The code on the html page
<html> <head> <meta charset="utf-8"> <title>news</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> <!-- Make sure the path to CKEditor is correct. --> <script src="ckeditor.js"></script> </head> <body onload='timer()'> <form action="Mail3" method="POST"> <textarea name="editor1" id="editor1" rows="10" cols="80" > Enter your message here </textarea> <script> CKEDITOR.replace( 'editor1' ); </script> <script text="javascript"> $(document).ready(function() { $("#editor1").bind("keypress", function() { note(this.value) }); }); function note(value) { $.ajax({ async : false, type: "POST", url: "./brouillon.php", data: { 'text' : value }, success: function(data) { $("#editor1").html(data); } }); }</script> <input type="submit" name="soumettre" value="send"> </form> </body> </html> Still on the test page, because initially, I wanted to make backups before putting it online and the one on the processing page that I named draft <?php header('Content-type: application/json; charset=utf-8'); function note() { $bdd = new PDO('mysql:host=localhost;dbname="";charset=utf8', '', ''); $req = $bdd->prepare('UPDATE test set message= ?'); $req->execute(array($_GET['text'])); if($req) { echo('Draft saved'.date(' h:i:s A').'') ; } else { echo("Insertion failed") ; } ?> Usually, I include my connection data; I will fix everything once I understand the trick well.
To be frank, I don't want ready-made code; otherwise I won't learn. Just a pointer to my mistakes
Thank you for all the time you give me.
<?php //display PHP errors error_reporting(E_ALL); $result = array(); //return variable at the end of the script //clean retrieval of variables $text = isset($_POST['text']) ? $_POST['text'] : ''; //Database connection try{ $bdd = new PDO('mysql:host=localhost;dbname="";charset=utf8', '', ''); $bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $bdd->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); } catch(PDOException $e) { $result['erreur'][] = 'Error: ' . $e->getMessage(); } $sql = 'UPDATE test SET message= :txt'; $datas = array(":txt"=>$text); try{ $req = $bdd->prepare($sql); $req->execute($datas); }catch(Exception $a){ $result['erreur'][] = "Error! ".$a->getMessage(); } if($req) { $result['resultat'] = 'Draft saved '.date(' h:i:s A'); } else { $result['resultat'] = "The insertion failed"; } //Return the result in json echo json_encode($result); ?>
But I ended up doing it this way. Sorry I just saw your post
<script> $(document).ready(function(){ function draft(){ var myText = $('#editor1').val(); $.ajax({ method: "POST", url: "draft.php", data: {msg:myText}, success: function(data){ $('.result').html(data); } }); }; setInterval(function(){ draft(); }, 10000); }); </script>however, I wonder how to adapt your script for ckeditor so that it is compatible. Because here, it is not and I have to remove the editor
Thank you Jordane for your help