Show data immediately after insert to db mysql using codeigniter MVC - javascript

I have one text box and one button, after filling in the text box and then clicking the button, the data will be saved to mysql.
My question is, how do I when I click the save button, the ID of the data that I save will immediately appear on that page. I mean the ID of the data that just i insert into mysql
This is the view
<label for="userAnswer">Answer</label>
<textarea name="userAnswer" id="userAnswer" class="form-control"></textarea>
<button onclick="saveAnswer()">Submit Answer</button>
This is the js
function saveAnswer(){
var inputAnswer = $('#userAnswer').val();
$.ajax({
type: "GET",
url: GLOBAL_URL + '/Session/saveAnswer?&inputAnswer='+inputAnswer,
dataType: 'json',
});
}
This is the Controller
function saveAnswer(){
$data = array(
'id' => uuid(false),
'answer' => $this->input->get_post("inputAnswer")
);
$this->db->insert('tableAnswer', $data);
}
Thanks

Views File
add this code
<input type="text" id="id">
Controller File
After insert, add this code
echo json_encode(array("val"=> $data['id']));
Javascript
$.ajax({
type: "GET",
url: GLOBAL_URL + '/Session/saveAnswer?&inputAnswer='+inputAnswer,
dataType: 'json',
success: function(val){
document.getElementById("id").value = val.val;
}
});
Thats it...

use this code:-
function saveAnswer(){
var inputAnswer = $('#userAnswer').val();
$.ajax({
type: "GET",
url: GLOBAL_URL + '/Session/saveAnswer?&inputAnswer='+inputAnswer,
dataType: 'json',
sucess:function(result){
alert(result);
},
});
}
the result wll carry your id and it will be shown in alert box, and the returning of id from ajax use this code:-
function saveAnswer(){
$data = array(
'id' => uuid(false),
'answer' => $this->input->get_post("inputAnswer")
);
$this->db->insert('tableAnswer', $data);
$id = $this->db->insert_id;
if($id > 0){
echo $id;
}
}
if you get the result don't forget to tick it right, so other can get help

after insert your data, paste below line in modal
return $this->db->insert_id();
it will reflect last insert data ID

You have to echo the id and not return it to get it from Js
echo $this->db->insert_id();

Related

load a file using variable from client side

I need to load a file inside a container, but using an argument - to get some data from database firstly:
$('#story').load('test.php');
test.php
$st = $db->query("select * from users where id = " . $id);
... processing variables... load the finished content
Here I need $id from client side. Is it possible?
yes ..you could pass with url query
$('#story').load('test.php?id=1');
test.php
$id = isset($_REQUEST['id'])?$_REQUEST['id']):'';
$st = $db->query("select * from users where id = " . $id);
You can use ajax request and on success you load your file something like:
$.ajax({
type: 'POST',
url: "test.php", //make sure you put the right path there
data: {id: id},
dataType: "json",
success: function (resultData) {
$('#story').load('test.php');
}
})
Just make sure that your php function returns/echos the id you want.
That way you make a call to your php file and when it's successful you will load your file and you can put extra logic there if you want to return more data to use it of course.
resultData holds the output of your php function so it's up to you what info you want to be there.
You could use Ajax to post the ID to your php code.
$.ajax({
type: "POST",
url: "test.php",
data: { 'id': foo },
cache: false,
success: function(){
alert("Order Submitted");
}
});
php:
<?php
$id = $_POST['id'];

Inserting data in mysql table with javascript / AJAX

When the user clicks a button i want to update a value in mysql table, but somehow I'm doing something wrong and nothing happens.
<button class="btn btn-primary" id= "openchest" onclick="insertvalue();"> Open </button>
javascript
function insertvalue(){
makeRequest('addgold.php');
}
EDIT: changed the javascript BUT it still doesnt do anything..
the addgold.php doesnt show any mysql error.
function insertvalue(){
$.ajax({
type: "POST",
url: "addgold.php",
cache: false,
data:{id:'openchest'},
}).done(function( msg ) { console.log(msg);
});
}
addgold.php
<?php include ("connection.php");
if(isset($_REQUEST)) {
$sql= "UPDATE members SET coins = coins + 10 WHERE id ='".mysqli_real_escape_string($link, $_SESSION['id'])."' LIMIT 1";
$result = mysqli_query($link, $sql);
}
?>
you have to use ajax function on click and dont forget to include jquery libray
function insertvalue(){
$.ajax({
type: "POST",
url: "addgold.php",
cache: false,
data:{id:'anything'},
}).done(function( msg ) { console.log(msg);
});
}

How to send select value to php using ajax?

i m trying to passe the value of the selected item from a select tag using ajax for that :
here it is the select tag(it is not in a form):
<select class="select" id="select" >
</select>
here it is the code that fill the select from the database using php:
$(document).ready(function(){
<?php foreach ($espace_ids as $row ) {?>
$('#select').append('<option value="<?php echo $row['espace_id']; ?>"><? php echo $row['nom']; ?></option>');
<?php }?> });
for sending data from the actual page to dashbored.php,here it is the code:
$("#select").change(function() {
$.ajax({
type: 'post',
url: "<?php //echo base_url(); ?>index.php?directeur/dashboard ?>",
data: espace_id: $("#select").val(),
success: function( data ) {
alert( data );
}
});
well i retrieve the value sent with :
$espace_id=$_POST['espace_id'];
the probleme that it display : undefined refrence to espace_id in dashboard.php.
well , the pupose is to load the espace info from the database according to the espace selected by the user.each time the user select an option i should load the appropiate info related to the espace selected.
i wish that you gonna help me.
thanks
You can use following example to get espace id in index.php.
$(document).ready(function ()
{
$('#select').on('change', function ()
{
if ($('#select').val() === null) {
alert("Error");
}
else
{
var selectedValue = $('#select').val();
$.ajax
({
url: 'index.php',
type: 'POST',
data: 'espace_id=' + selectedValue,
success: function(response)
{
alert(response);
}
});
}
});
});
on index.php
if(isset($_POST['espace_id']) && !empty($_POST['espace_id']))
{
// do whatever you want to do here!!
}
For those that want to keep it lighter than Jquery you could do something like this:
<select onchange="livesearch(this.value)"><option></option></select>
<script>
function livesearch(id){
xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET","url?id="+id, false); xmlhttp.send(null); document.getElementById("searchresults").value=xmlhttp.responseText; }
</script>

Using AJAX/Jquery to Replace div

I am trying to set the content of an empty div after an AJAX call with the data message. I also wired the function to my CHtml::submitButton, which should call the function when clicked, but nothing is happening. Any suggestions?
<div id="myResult">
</div>
JavaScript:
function successMessage(){
$.ajax({
type: "GET",
data: "<div> Replace div with this contentf</div>",
success: function(data){
$('myResult').html(data);
}
})
}
PHP:
echo CHtml::beginForm(array('myForm'), 'get', array('form'));
echo '<div class="row form">';
echo '<div class="row buttons">';
echo CHtml::submitButton('Download Content', array('htmlOptions' => 'successMessage()'));
echo '</div>';
echo '</div>';
Your problem relies in the following line:
$('myResult').html(data);
Here, you are trying to do a jquery selection to an element, which you are not using in your html (this is only possible via pollyfils). So you have to select the element by its ID:
$('#myResult').html(data);
And another thing i've seen, what is the url where you are doing the request?
<script>
function successMessage(){
$.ajax({
type: "GET",
url: "/please/add/an/url/",
data: "<div> Replace div with this contentf</div>",
success: function(data){
$('myResult').html(data);
}
})
}
</script>
first of all, when you are using onclick function like this :
<input type="submit" onclick="successMessage()">
you should use this instead:
<input type="submit" onclick="successMessage();result false;">
but when you are already using jquery, then better approach is:
$( document ).ready(function() {
successMessage(){
// your ajax goes here
}
$('#myResult').click(function(e){
e.preventDefault();
successMessage();
});
});
Then you need to repair your successMessage function. You see, the data you are setting there are not the data, that are coming out as an output. If you need ajax then you probably want to get the result from some php script on some other url. Then you should do it like this :
function successMessage(){
$.ajax({
type: "GET",
url : 'index2.php',
dataType: "json",
data: { mydata: '<div> Replace div with this content</div>'},
success: function(data){
$('#myResult').html(data);
}
})
}
Then you need a php file named index2.php which can look like this :
<?php
echo json_encode($_GET['variable']);
?>
And i dont know if this your line :
echo CHtml::submitButton('Download Content', array('htmlOptions' => 'successMessage()'));
also put the </form> tag after the form to close it.
This should work for you. I tried it and it works fine.
Try this:
$.ajax({
url: "test.html",
type: "GET",
data: "<div> Replace div with this contentf</div>",
success: function(data){
$('#myResult').html(data);
}
})
selector jQuery incorrect in response ajax. and define Url in ajax.

Javascript passing variable issue not returning

Hi All I have the following code to pass a JS variable using AJAX as seen below:
function buttonCallback(obj){
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: "/project/main/passid",
data: { 'id': id },
success: function(msg){
window.alert(msg);
}
});
}
if I put an alert box in I can see the object id is successfully getting grabbed. however if in php I want to simply return the variable - I am getting a null has anyone got any ideas:
heres my PHP function (I am using Codeigniter):
public function passid(){
$courseId = $this->input->post('id');
echo $courseId;
}
EDIT: the success alert box appears - but appears blank and that is my issue I am hoping to see the ID
1. Can you make sure id equals something by doing this:
function buttonCallback(obj){
var id = $(obj).attr('id');
alert( id ); // What does it alert?
$.ajax({
type: "POST",
url: "/project/main/passid",
dataType: "json",
data: { 'id': id },
success: function(msg){
window.alert(msg.id);
}
});
}
2. Your javascript looks good... Can you try this instead to see if it works:
JS
function buttonCallback(obj){
var id = $(obj).attr('id');
$.ajax({
type: "POST",
url: "/project/main/passid",
dataType: "json",
data: { 'id': id },
success: function(msg){
window.alert(msg.id);
}
});
}
PHP
public function passid(){
$courseId = $this->input->post('id');
$response = array( "id" => $courseId );
header('Content-Type: application/json');
echo json_encode( $response );
}
3. If this does not work, can you try and rename from id to something like poopoo, just to make sure id is not taken and being weird?
4. Can you check what the network response is of your ajax request - Go to developer toolbar and goto network section, make sure you hit the record/play button. then send your request off. When you see your request come up in the network list, check the "details" of it and goto response.

Categories

Resources