Im trying to learn how to use JSON from within codeigniter. I’m trying to use a model to run the ajax code, but its not working.
I need to learn how to pass variables through to the model, and back out; or, if thats incorrect, I need to learn the correct process. The below is my code.
HTML
<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>
<option name='Town Center' value='1' data-icon='../img/structures/tc.png' data-html-text='Town Center<i>
500 minutes<br>50000 gold</i>'>Town Center</option>
<option name='Barracks' value='2' data-icon='../img/structures/barracks.png' data-html-text='Barracks<i>
25 minutes<br>1500 gold</i>'>Barracks</option>
<option name='Dragon Roost' value='3' data-icon='../img/structures/droost.png' data-html-text='Dragon Roost<i>
200 minutes<br>5000 gold</i>'>Dragon Roost</option>
<option name='Mage Hall' value='4' data-icon='../img/structures/mage.png' data-html-text='Mage Hall<i>
40 minutes<br>300 gold</i>'>Mage Hall</option>
<option name='Test Lab' value='6' data-icon='../img/structures/testlab.png' data-html-text='Test Lab<i>
1 minutes<br>10 gold</i>'>Test Lab</option>
</select>
<div id="buildSubmit">
<input id ="btnSubmit" class="button" type="submit" value="Submit"/>
</div>
</form>
</div>
Here is my ajax/js/json
I’m trying a very simple example. I’d like to post the value of the OPTION above (1-6) to the model function insert_build. I don’t know if its doing it, as I can’t really think of a good way to test it. However, I would assume if it returned anything, I would be alerted. I am not.
$(function(){
$(".button").click(function(e, value){
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php $this->structure_model->insert_build() ?>", //the script to call to get data
str_id: value,
dataType: 'json', //data format
success: function(data) //on receive of reply
{
alert("success!");
}
});
});
});
The model code
public function insert_build()
{
$str_id = $this->input->post('str_id');
echo " TESTING $str_id";
}
Any help would be greatly appreciated. Why doesn’t this work? I am still trying to understand the fundamentals of Codeigniter and JSON / JS.
Thanks
The
url:you’re setting in your javascript is the actual function you’re wanting to call when the ajax is submitted. You’ll need to have a controller in place that actually calls that function e.g.Also, setting
dataType:tojsonmeans you’re expecting what’s returned from your function to be encoded as json.