I have a form which I call via AJAX (for use on a CMS) and then this form is used to update the database for the content, however its not working and I cant seem to figure out where.
It all works up to the submit, as in the fields are all filled out correctly with the database rows, columns etc and the data is pre-filled with what is there currently. The issue lies somewhere between the AJAX submit() function and the eupdate.php MySQL query.
eform.php (pulled via another page, eindex.php, to be displayed)
<?php
require("../mcfrdb.php");
// Included database once using the require method
$item = $_POST['item'];
$page = $_POST['page'];
$row = mysql_query("SELECT * FROM mcfr WHERE pageid = '$page'");
$data = mysql_fetch_array($row);
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"> </script>
<script type="text/javascript">var $j = jQuery.noConflict();</script>
<script type="text/javascript">
function submit(){
$j.ajax({
type:"POST",
url:"eupdate.php",
data: "item=" + $j('#item') + "&itemcont=" + $j('#itemcont') + "&page=" + $j('#page'),
success:function(response){
$j("#msg").html(response);
}
});
}
</script>
<div id="msg"></div>
<form id = "edititem" name = "edititem" onsubmit="return false;" method="post" >
<textarea cols="20" rows="5" name="itemcont" id="itemcont"><? echo $data[$item]; ?></textarea> <br/>
<input type="text" name="item" id="item" value="<? echo $item; ?>"><br/>
<input type="text" name="page" id="page" value="<? echo $page; ?>"><br/>
<input type="button" value="make changes" onclick="submit()" >
</form>
eupdate.php
<?php
require("../mcfrdb.php");
// Included database once using the require method
$item=$_POST['item'];
$page=$_POST['page'];
$newcont=$_POST['itemcont'];
$row = mysql_query("UPDATE mcfr SET '$item' = '$newcont' WHERE pageid = '$page'");
?>
When i click my button to submit, upon checking my DB after this, nothing has changed or updated.
Thanks in advance for all replies, here’s hoping we can get this fixed 🙂
Cheers
Since you’re submitting your data with AJAX, you don’t need to use a
formelement (especially that it requires you to do additional things to prevent it from being submitted normally).Anyway, the basic problem is probably how you (don’t) retrieve the values of the fields.
$j('#item')returns the jQuery object bound to theiteminput, not its value. To get the value, use the.val()method, e.g.:$j('#item').val().As a side note, you also need to escape the posted data in your PHP script before using it in any SQL queries, otherwise you’re vulnerable to some terrible SQL injection attacks. See the documentation of
mysql_real_escape_stringfor an explanation: http://php.net/manual/en/function.mysql-real-escape-string.php