Using Codeigniter, I am trying to get a php script to run after a user clicks on a submit button. I have followed quite a few tutorials and have come up with the following code:
If it would help to see the actual page you can visit it here: http://rickymason.net/townbuilder guest/guest to login (currently required)
In my view (structures.php), I have :
<div id="structures">
<h1>Build</h1>
<form name="buildForm" id="buildForm" method="POST">
<select name="buildID" class="buildClass">
<option value="0" selected="selected" data-skip="1">Build a Structure</option>
<?php foreach ($structures as $structure_info): ?>
<option name='<?php echo $structure_info['str_name'] ?>' value='<?php echo $structure_info['str_id'] ?>' data-icon='<?php echo $structure_info['str_imageloc'] ?>' data-html-text='<?php echo $structure_info['str_name'] ?><i>
<?php echo $structure_info['timebuildmins'] ?> minutes<br><?php echo $structure_info['buy_gold'] ?> gold</i>'><?php echo $structure_info['str_name'] ?></option>
<?php endforeach ?>
</select>
<div id="buildSubmit">
<input class="button" type="submit" value="Submit"/>
</div>
</form>
</div>
<div id="output"> Result here</div>
This creates my select form and creates it in html. I then created a .js file to run the ajax:
$("#submit").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: '../php/build.php',
data: "",
dataType: 'json',
success: function(data)
{
alert("success!");
}
});
});
I tried to keep it as simple as I could, just for testing purposes. Javascript is new to me, and I find it extremely confusing for some reason. From what I can gather, this script should activate after the submit button is pressed. It then runs the build.php script, then if it returns an echo through json, it alerts success. right?
my build.php script is below:
<?php
$query = "INSERT INTO user_structure (str_id, user_id) VALUES ('7', '7')";
mysql_query($query) or die ('Error updating database');
echo "success";
?>
Again, very simple...
Unfortunately, when I click submit, the page seems to "refresh" but nothing happens. I don't expect anything to happen on the page, but the database doesn't receive any values either.
I do not have the build.php or build.js files in a controller or model, they are outside the application directory and are accessed outside the CI uri/url structure.
As of right now, I am simply trying to successfully run a php script by clicking submit. My final goal is to take the str_id value that is created for the form, then pass that variable and the user_id into the build.php file, create the db entry, then refresh the page to display the updated DB info.
Obviously, it is not working! Any help would be greatly appreciated.
echo "success";
doesn't return a JSON string. Also you don't prevent the form from being submitted. Also do you really need all those opening / closing php tags to build your select box? – PeeHaa Mar 5 '12 at 16:43