简体   繁体   中英

Add new data from HTML form in external XML file using Ajax and PHP

I am stuck and unsure. The webpage is displaying a table, based on an existing XML file.

I just want to give the option of adding a new line in the table. I read that I cannot use JS to write on external XML file, so I have to use a PHP script.

The problem is I'm not sure about the implementation logic. Here is my point:

  1. the page is displayed with an empty table (done).
  2. Javascript fills the table with the XML file data (done).
  3. The user fills the HTML form fields.
  4. When the user press 'submit' button, javascript captures the fields content and send them to PHP script (POST method) (not developed yet).
  5. PHP catches the POST data, then append them to the XML file (not developed yet).
  6. When its done, javascript refresh the table using the freshly updated XML file (not developed yet).

Am I doing this right? Thank you for your help!

--

EDIT

Thank you all for our help. Unfortunately, i cannot make this thing working. the form value cannot be retrieved (pEnseigne is undefined)

Here is the HTML form (extract)

<form class="form-inline" name="newlineform">
<input type="text" class="input-small" placeholder="Enseigne" name="enseigne"/>
<button type="submit" class="btn btn-primary" id="zou">Zou!</button>
</form>

Here is the JS functions (extracts)

$('#zou').on('click', function(){
exportLine();
$('.form-inline').hide();
$('#ajouter').fadeIn();
return false
});

function exportLine(){
var pEnseigne = $('#enseigne').val();
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
loadData();
}}
xmlhttp.open("POST","php/form-process.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fenseigne="+pEnseigne);
}

And the PHP thing

<?php
$enseigne = htmlentities($_POST['fenseigne']);
$lignes = simplexml_load_file('../list.xml');
$lignes->ligne->addChild("enseigne",$enseigne);
?>

Could you please give me a hand again?

I think your general process is sound. However instead of doing a straight post-form, I would use javascript to capture the form and send it. This allows you to set a javascript method to wait for the the php to return a status code before triggering the update.

See the bit here about sending the request asynchronously and using a handler to deal with the results.

http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

Sounds fine. Take a look at using AJAX to perform 6.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM