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.
url: "<?php echo base_url(); ?>/structure/insert/?str_id=" + $('#buildID').val(),
Also, setting dataType: to json means you're expecting what's returned from your function to be encoded as json.
Maybe change this:
url: "<?php echo $this->structure_model->insert_build() ?>"
Related
I have the following 3 checkboxes which are populated from a php database. I need assistance with JQUERY that once any select box is changed the value is posted to a php file and able to return a response through JQUERY.
Each select box should be standalone to only send that checkbox value & name to the PHP file.
I have the below JQUERY to start with to send the first checkbox but am getting no response back.
What amendments need to be made to the JQUERY to receive the input of the other checkboxes and then send the data correctly?
The php file will simply have echo "WHAT EVER THE RESPONSE IS" using if statements.
Any help grately appreciated with thanks.
$(document).ready(function() {
$('select.person-1').change(function() {
$.ajax({
type: 'POST',
url: 'lib/positionMarshalProcess.php',
data: {
selectFieldValue: $('select.person-1').val(),
changeCol1: $('input[name$="changeCol1"]').val()
},
dataType: "html",
},
success: function(data) {
var a = data.split('|***|');
if (a[1] == "update") {
$('#msg').html(a[0]);
}
}
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name='person-1' class='marshal-select'>
<option value='1'>John Smith</option>
</select>
<input type='hidden' name='changeCol1' value='person-1'>
<select name='qty' class='marshal-select'>
<option value='1'>1</option>
</select>
<input type='hidden' name='changeCol2' value='qty'>
<select name='person-2' class='marshal-select'>
<option value='1'>John Smith</option>
</select>
<input type='hidden' name='changeCol3' value='person-2'>
The selectors you've used are incorrect for the HTML displayed. .person-1 is a class selector, yet the select elements have that value in their name.
In addition your success property is outside the options object of the $.ajax call - it needs to be inside.
You can fix this issue and DRY up the code to make it more extensible by removing the hidden fields, hooking the change event handler to the common marshal-select class on all the select elements, and by using the name attribute of the select elements to fill the changeCol property of the data you send in the AJAX request. Try this:
$(document).ready(function() {
$('select.marshal-select').change(function() {
let $select = $(this);
// in your AJAX request...
let data = {
selectFieldValue: $select.val(),
changeCol: $select.prop('name')
};
console.log(data);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="person-1" class="marshal-select">
<option value="1">John Smith</option>
<option value="2">Jane Doe</option>
</select>
<select name="qty" class="marshal-select">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select name="person-2" class="marshal-select">
<option value="1">John Smith</option>
<option value="2">Jane Doe</option>
</select>
As an aside, the logic in the success handler implies that you're returning plain text and then hacking the string around using split(). Do not do this. Return a serialised data structure, such as JSON instead. This is more extensible and makes the code far more robust.
Update:
With your code you have added could you just add an edit where how you would receive a response ideally I want a positive response to show the msg div and where you would call the php file?
Sure, here you go:
$(document).ready(function() {
$('select.marshal-select').change(function() {
let $select = $(this);
$.ajax({
type: 'POST',
url: 'lib/positionMarshalProcess.php',
data: {
selectFieldValue: $select.val(),
changeCol: $select.prop('name')
},
dataType: "html",
success: function(data) {
// assuming a JSON response:
if (data[1] === 'update') {
$('#msg').html(data[0]).show();
}
}
});
});
});
Note that I've not included the PHP which would generate the JSON response as I'm not a PHP dev. I'm sure there are lots of topics covering that if you search.
I have a table with multiple rows that lists records from my database.
These records are projects' information and in each row, I have drop down list to modify the status of the project.
To do so, I used Ajax because I hate to refresh the whole page after update.
This is the function I created to do the update:
function call(){
var projid=$('#projid').val();
var projstatus=$('#projstatus').val();
var dataall={'projid':projid, 'projstatus':projstatus};
$.ajax({
type: 'POST',
url: "stsproj.php",
data: dataall,
success: function (data) {
}
});
}
And below is my drop down list:
<?php do { ?>
<td>
<form action="<?php echo $editFormAction; ?>" method="post" name="form2" id="form2">
<input type="hidden" name="MM_update" value="form2" />
<input type="hidden" name="projid" id="projid" value="<?php echo $row_projlist['projid']; ?>" />
<select name="projstatus" id="projstatus" class="select1" onchange="call()">
<option value="<?php echo $row_status['projstatus'];?>"><?php echo $row_status['sts'];?></option>
<option value="1">Awaiting</option>
<option value="2">Ongoing</option>
<option value="3">Finishing</option>
</select>
</form>
</td>
<?php }while($row_projlist = $projlist->fetch(PDO::FETCH_ASSOC)); ?>
My problem is the following:
When I update the status of the first project, it works but when I try to do it with other projects, it doesn't work.
To be more specific, the parameters of the first project are sent always (this is what firebug says).
Please help!
Your problem is due to duplicate ids. You don't need to use ids(actually do not use id for automatic list generation. Id names must be unique). Remove call function from your select box and use below javascript;
You can use such js to handle that;
$(function() {
$("select[name='projstatus']").change(function() {
var projid = $(this).parent("form").find("input[name='projid']").val();
var projstatus = $(this).val();
var dataall = {'projid':projid, 'projstatus':projstatus};
$.ajax({
type: 'POST',
url: "stsproj.php",
data: dataall,
success: function (data) {
}
});
});
});
You can see working example for form manipulating part here : http://jsfiddle.net/cubuzoa/SYf8s/
The previous answer will probably solve your problem, but I think it can be simplified.
for the form...
<form>
<select class="select1" onchange="call(<?=$row_projlist['projid']?>)">
<option value="<?=$row_status['projstatus']?>"><?=$row_status['sts']?></option>
<option value="1">Awaiting</option>
<option value="2">Ongoing</option>
<option value="3">Finishing</option>
</select>
</form>
and the javascript
function call(id)
{
$.post('stsproj.php',{'projid':id, 'projstatus':$('#projstatus').val()} )
.done(function(data){
//do something with data
});
}
This is my html code
<select name="course" id="course" onchange="valuesOfAll(this.value)">
<option value=""> select </option>
<option value="1"> Diploma in Computing</option>
</select>
<input name="course_credits" id="course_credits" type="text" />
and my database table is like this
courseId courseName courseCredits
1 Diploma in Computing 5
So my request is, if i change the value in the 'select' the 'courseCredits' value should appear in the textbox. for this how can i write jquery code?
"Ajax with Jquery" is what your are looking for. It will work like this:
the user chooses an option from the select box
you submit via Javascript the chosen option to a PHP script
the php script fetches the data from the database
the php script returns the result as json encoded data
there is a callback function in your javascript code. This js code will manipulate the HTML in whatever way you want, e.g. "add the option to your select box"
There are tons of tutorials on how to do Ajax requests in detail, e.g. http://openenergymonitor.org/emon/node/107
Check out one of those tutorials - eventually you will want to update your question so that it becomes a bit more specific? :-)
it is good practice to seperate you html from scripts so i would like to change :
<select name="course" id="course" onchange="valuesOfAll(this.value)">
to
<select name="course" id="course" >
then my script will be following (hoping you add reference of latest jquery )
<script>
$(document).ready(function(){
//bind change event once DOM is ready
$('#course').change(function(){});
getResult($(this).val());
});
function getResult(selectedValue){
//call ajax method to get data from database
$.ajax({
type: "POST",
url: url,//this should be replace by your server side method
data: "{'value': '"+ selectedValue +"'}", //this is parameter name , make sure parameter name is sure as of your sever side method
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (Result) {
alert(Result.d);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
</script>
use $.post.. (ajax or get)... i am using post here....go through the docs if you want to read more about jquery post..
javascript
function valuesofAll(val){
$.post('test.php',{data:val},function(result){
$('#course_credits').val(result.coursecredit)
}, "json"); //expect response as json..
}
test.php
$data=$_POST['data']; //this is the value posted
//make you query in db get result..
$courseCredits= $row; //db returned courseCreadit value
echo json_encode(array('coursecredit'=>$courseCreadits)); //send response as json
this will helps you .....
<script>
function valuesOfAll(value)
{
var base_url="http://.../../hello.php";
var ip=new Object();
ip.course=value;
var inputParam=JSON.stringify(ip);
var module="getcourseCredits"
$.ajax({
type: "POST",
url: base_url,
data: {coursevalue:inputParam,module :module},
dataType: "json",
success: function(msg)
{
$("#course_credits").val(msg.credit);
}
});
}
</script>
<body>
<select name="course" id="course" onchange="valuesOfAll(this.value)">
<option value=""> select </option>
<option value="1"> Diploma in Computing</option>
</select>
<input name="course_credits" id="course_credits" type="text" />
</body>
In your PHP file
<?php
if(isset($_POST['module']))
{
if($_POST['module']=='getcourseCredits')
{
$val=json_decode($_POST['coursevalue'],true);
$courseval=$val['course'];
// do the connectivity and query here and finally echo the result as json format that is the response to the ajax call
.
.
.
.
}
}
?>
My original goal was to get a php file to execute on a button press. I used ajax. When the javascript was in the view, it worked.
However, I tried to switch the javascript to its own .js file and include it in the header. It doesn't work anymore. I am confused.
the model code:
public function insert_build($user_id)
{
$query = "INSERT INTO user_structure (str_id, user_id) VALUES ('7', '$user_id')";
mysql_query($query) or die ('Error updating database');
}
Something interesting to note here is that when I include $user_id as a value, it completely negates my headertemplate. As in, it simply doesnt load. When I replace $user_id with a static value (i.e. '7') it works no problem.
This is my view code :
<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 id ="btnSubmit" class="button" type="submit" value="Submit"/>
</div>
</form>
</div>
Heres my .js file :
$(".button").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php $this->structure_model->insert_build($user_id) ?>", //the script to call to get data
data: "", //you can insert url arguments here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on receive of reply
{
alert("success!");
}
});
});
I am almost sure I know the problem: That structure_model->insert_build($user_id) ?> doesn't work when its outside the view. Though, I dont know the alternative.
I excluded the header file. I confirmed that the .js file is indeed being directed to the correct path.
Could someone please explain the correct way to do this? Thank you!
Did you move your javascript to a .js that is being directly accessed by the browser? I.E: If you view source, so you see the <?php ... ?> in the javascript code?
To me, it sounds as though the PHP is not getting parsed. If this is not the case, then can you please clarify.
If you need to include PHP variables in your javascript, you should use CI to generate the JS page for inclusion. You can even create a View that is purely JS and call it like a normal page.
Otherwise, if you want to seperate the JS from CI, you should reference JS variables instead of PHP. Then in your CI page somewhere, define them with a <script>var jsVar = <?php echo phpvar(); ?></script> tag.
When you move the js file to it's own file, php variables will not be accessible anymore. You can either move the js code back to your view file, or fetch the url through javascript. See below for example.
HTML:
<div id="structures">
<h1>Build</h1>
<form name="buildForm" id="buildForm" method="POST">
<input type="hidden" name="url" value="<?php $this->structure_model->insert_build($user_id) ?>" />
<!-- Rest of your code -->
</form>
</div>
Javascript:
$(".button").click(function(e){
var form_url = $(this).closest('form').find('input[name=url]').val();
e.preventDefault();
$.ajax({
type: "POST",
url: form_url, //the script to call to get data
data: "", //you can insert url arguments here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on receive of reply
{
alert("success!");
}
});
});
I am trying to use jQuery with MYSQL and I wrote something like this :
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
function example_ajax_request() {
$('#example-placeholder').html('<p>Loading results ... <img src="ajax-loader.gif" /></p>');
$('#example-placeholder').load("loadres.php");
}
</script>
</head>
<body>
<div id="query">
<select name="show" id="box" >
<option value="0">Select A Test</option>
<option value="All">--All--</option>
<option value="M1">Model1</option>
</select>
<input type="button" onclick="example_ajax_request()" value="Click Me!" />
</div>
<div id="example-placeholder">
<p>Placeholding text</p>
</div></body>
</html>
Basically I want to pass parameters to the loadres.php file. But unable to figure out the exact way to do.
Any help is appreciated.
Thanks.
You should use the $.ajax() method from jQuery. you can pass data to the url and have a callback at the end.
$.ajax({
url: 'loader.php',
data: 'somedata',
type: 'GET',
success: function(data){
$('#example-placeholder').text(data);
}
});
This will do the trick. This method also provides far more flexibility. You can have different functions such as error functions and complete functions.
$('#example-placeholder').load("loadres.php?show=" + $('#box option:selected').val());
This will use jquery to get the selected value from the drop down list and append it to the URL as a querystring parameter, which you can access in the loadres.php page.
similar to saif-bechan's post you can use ajax with post and data can hold an object to pass multiple parameters
$.ajax({
type:"POST",
url: loadres.php,
data: {
foo:'bar',
selected:$('#selector').val()
},
dataType: 'json',
error: function(data) {
//error code here
},
success: function(data) {
//success code here
}
});
I will also note that is is better to put your click event in jquery context not in the html
so in script somewhere use
$('#button_id').click(function(){
//call to ajax
};