I want to send an ajax request and reload the div from which it came. As of current I am getting the proper request but it isn't reloading the div - it just makes it blank (nothing there). And I have to refresh the page to see my data. How can I get it to display properly?
my add_amenity.php page works fine
*also, don't be suspicious of the var id = $('.editblock').find('#id').val(); It gets the value it needs and sends it to add_amenity.php just fine. My only problem is getting the div to reload on an add.
php and html on same page as JS below. (This is not add_amenity.php)
<div class="editunitamenities">
<?php
require_once('config/db.php');
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$query = 'SELECT id, unit, amenities FROM amenities WHERE unit = '.mysqli_real_escape_string($con, $_GET['id']).'';
$result = mysqli_query($con, $query);
while ($row= mysqli_fetch_assoc($result))
{
echo '<div class="checkbox"><input type="checkbox" id="'.$row['id'].'" checked
class="amenitiescheckbox" name="'.$row['amenities'].'" value="'.$row['amenities'].'" />
<label title="'.$row['unit'].'">'.$row['amenities'].'</label></div>';
}
mysqli_close($con);
?>
<div class="newamenitywrap">
<div class="button"><button class="smallbutton" id="addamenity">New</button></div>
<div><input type="text" name="amenity" style="width:120px;" id="amenity" placeholder="Amenity Name" /></div>
</div>
</div> <!-- end editunitamenities -->
Here is the AJAX request
<script>
$('#addamenity').click(function() {
var id = $('.editblock').find('#id').val();
var amenity = $( "#amenity" ).val();
var dataString ={id:id,amenity:amenity};
console.log(dataString);
if (amenity != '')
{
$.ajax({
type: "POST",
url: "classes/add_amenities.php",
data: dataString,
cache: false,
async:false,
success: function(html)
{
$('.editunitamenities').html(html);
}
});
}
});
</script>
I suggest the following changes:
(1) Remove the following line. I can't imagine it is doing what you expect it to because it will try to make an ajax call to the URL ".editunitamenities", and this may be what is blanking out the <div>.
$(".editunitamenities").load('.editunitamenities');
(2) Add the following property to the ajax options. This will prevent jQuery from converting the data value into an object if it thinks it looks like JSON.
dataType: 'html'
(3) Add the following line to the success handler to check what is getting returned.
console.log(data);
The following line also appears suspicious to me, but since you say the request is correct, I will assume it is working as it should.
var id = $('.editblock').find('#id').val();
I find the above line suspicious because there would have to be an element with an id value equal to "id". Also, since you are trying to find that element within another element, it makes me think you have multiple such elements, but id values should be unique throughout the entire page.
It would be useful to see the code for classes/add_amenities.php to see exactly what's going on, but you should check one or more of the following:
in the PHP you use $_GET['id'] and the ajax request is type: "POST"
also I see in your ajax request you do $('.editblock').find('#id').val(); but I see no element in your markup with class editblock or with id id - so either these nodes are not in the markup you posted or you should change you js call
the second line in the success function is redundant
I found a workaround. None of the other suggestions worked for me.
I made another page called display_amenities.php:
<?php
require_once('../config/db.php');
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$query = 'SELECT id, unit, amenities FROM amenities WHERE unit = '.mysqli_real_escape_string($con, $_GET['id']).'';
$result = mysqli_query($con, $query);
while ($row= mysqli_fetch_assoc($result))
{
echo '<div class="checkbox"><input type="checkbox" id="'.$row['id'].'" checked
class="amenitiescheckbox" name="'.$row['amenities'].'" value="'.$row['unit'].'" />
<label title="'.$row['unit'].'">'.$row['amenities'].'</label></div>';
}
mysqli_close($con);
?>
<div class="newamenitywrap">
<div class="button"><button class="smallbutton" id="addamenity">New</button></div>
<div><input type="text" name="amenity" style="width:120px;" id="amenity" placeholder="Amenity Name" /></div>
</div>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"> </script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$('#addamenity').click(function() {
var id = $('.editblock').find('#id').val();
var amenity = $( "#amenity" ).val();
var dataString ={id:id,amenity:amenity};
console.log(dataString);
if (amenity != '')
{
$.ajax({
type: "POST",
url: "classes/add_amenities.php",
data: dataString,
cache: false,
async:false,
success: function(html)
{
//$('.editunitamenities').html(html);
$('.editunitamenities').load('classes/display_amenities.php?id='+id);
}
});
}
});
</script>
And then called it from the main page:
$('#addamenity').click(function() {
var id = $('.editblock').find('#id').val();
var amenity = $( "#amenity" ).val();
var dataString ={id:id,amenity:amenity};
console.log(dataString);
if (amenity != '')
{
$.ajax({
type: "POST",
url: "classes/add_amenities.php",
data: dataString,
cache: false,
async:false,
success: function(html)
{
//$('.editunitamenities').html(html);
$('.editunitamenities').load('classes/display_amenities.php?id='+id);
}
});
//$('.editunitamenities').load('.editunitamenities');
}
});
Definitely not ideal, but it works.
Related
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();
i want to post data to current page with ajax.But i couldnt do that.
I have doctor panel and i wanna get patient's data from 'hastalar' table in my db by using patient's national id:'tc'.Session is using by doctor so i guess i cant use $_SESSION for patient at same time.And i wanna use only one php page.So i cant see my patient's datas in current page.Pls help me guys.
dokyon.php
textbox
<a href="#" id="ara" class="ara" ><br/>SEARCH PATIENT</a>
<input type ="text" id="tc" name="tc" />
JQUERY
<script type="text/javascript" >
$(function() {
$(".ara").click(function(){
var tc = $('#tc').val();
$.ajax({
url:'dokyon.php'//current page
type: 'POST',
data:{tc:tc},
success: function(){
alert(data);
}
});
});
});
</script>
php codes
<?php
$tc=$_POST['tc'];
echo $tc;
$query = mysqli_query($connection,"select * from hastalar where tc_no=$tc");
while($hasta = mysqli_fetch_array($query)){
echo $hasta['name'];}
?>
For your ajax code, you need to add dataType parameter and add the parameter of success: function(data), so like this:
$.ajax({
url:'dokyon.php'//current page
type: 'POST',
data:{tc:tc},
dataType:"html",
success: function(data){
alert(data);
}
});
For additional: always do debuging for sending data with inspect element of browser.
Hopefully it will be success for you :)
I am a ajax beginner, Here I am trying to show a text box value in same page using Ajax.
My Controller code:
<?php
class Merchant extends CI_Controller
{
public function ajaxtest()
{
$this->load->helper('url');
$this->load->view('ajaxtest');
$fullname = $this->input->post("fullname");
echo $fullname;
}
}
?>
Here is my view code:
<head>
<script src="<?php echo base_url();?>assets/js/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#getinfo").click(function()
{
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>merchant/ajaxtest",
data: {textbox: $("#fullname").val()},
dataType: "text",
cache:false,
success:
function(data){
$('#mytext').html(data);
}
});
return false;
});
});
</script>
</head>
<body>
<form method="post">
<input type="text" id="fullname"/>
<input type="button" value="getinfo" id="getinfo"/>
<span id="mytext"></span>
</form>
</body>
When I click on the button getinfo, I want to show the text inside the text box as span text. But now it shows nothing..
Updated:
After experts' opinion, I edited some text(see my edit note), Now When i click on the button, it shows again a textbox and a button.. !!
Did you set the base_url variable with a link on the Javascript?
Because your post url contains this variable and you need set this to make it work. So initialize the variable with the base_url link.
See the corrected example below . Set your domain instead of the yourbaseurl.com
<script type="text/javascript">
$(document).ready(function(){
var base_url='http://yourbaseurl.com/index.php/';
$("#getinfo").click(function()
{
$.ajax({
type: "POST",
url: base_url + "merchant/ajaxtest",
data: {textbox: $("#fullname").val()},
dataType: "text",
cache:false,
success:
function(data){
$('#mytext').html(data);
}
});
return false;
});
});
</script>
Your base_url variable seems to be undefined in your JavaScript.
One simple approach to get the base URL is to echo it out in a hidden input, and then grab the value of that input in your JS code:
HTML
<input type='hidden' id="baseUrl" value="<?php echo base_url(); ?>" />
JS
var base_url = $('#baseUrl').val();
$.ajax({
type: "POST",
url: base_url + "/merchant/ajaxtest",
data: {textbox: $("#fullname").val()},
dataType: "text",
// ...
you are passing in textbox as parameter from your ajax to controller and trying to get POST data with name fullname. That wont work, since you passed in the name of parameter as textbox, access that in your post, as :
class Merchant extends CI_Controller
{
public function ajaxtest()
{
$this->load->helper('url');
//you dont need to load view so comment it
//$this->load->view('ajaxtest');
$fullname = $this->input->post("textbox"); //not fullname
echo $fullname;
}
}
js
<script type="text/javascript">
$(document).ready(function(){
var base_url='http://yourbaseurl.com/index.php/';
$("#getinfo").click(function() {
var fullname = $("#fullname").val();
alert("Fullname:" + fullname); //do you get this alert
$.ajax({
type: "POST",
url: base_url + "merchant/ajaxtest",
data: {textbox: fullname},
cache:false,
success:function(data){
alert("Response:" + data); //do you get this alert
$('#mytext').html(data);
}
});
return false;
});
});
</script>
Try using this:
<base href="<?=base_url();?>">
<script src="assets/js/jquery-latest.min.js"></script>
And this in ajaxtest:
$this->load->helper('url');
And also Comment out this:
// $this->load->view('ajaxtest');
Might be a little late with this response - but someone might find this while searching for a solution.
I was having the same issues with Codeigniter and JQuery ajax/post response. I could not get this to work no matter what I tried.
In the end, it turned out to be php_error that was causing the problem. Once I removed it, everything worked fine with my post/response.
I'm currently doing an ajax add,update and delete. And I think I'll just start with the delete since it is the easiest and hope that it might help me in the others.
In jquery (this is inside $doc.ready and the event is triggered properly)
if ($a == "Delete")
{
var postid = $(this).next('.postid').val();
$(this).closest(".todo-content").fadeOut();
jQuery.ajax({
type: "POST",
dataType: 'json',
url: "<?=base_url()?>.index.php/classes/deletepost",
data: {postid: postid},
async: false,
});
}
in html
<form method="post">
<button class="btn" onclick="return confirm('Are you sure to delete this item?')">Delete</button>
<input type="hidden" value="<?php echo $id; ?>" name="postid">
</form>
In controller
public function deletepost(){
$id = $this->input->post('postid');
$data = array('active' => 0);
$this->Model_name->deletepost($id,$data);
redirect('/abc/123');
}
This is already working but then I am planning on making the crud to ajax. I'm trying to pass the postid from ajax to controller to delete this post. The fadeout already works but only the ajax does not. I'm very new to ajax so I do not know where I am going wrong and I might also ask questions again regarding the other parts of crud.
Fixed!
The problem was the url inside the $.ajax. It returns a garbage.
So I added a script in the header
<script type="text/javascript">
var BASE_URL = "<?php echo base_url();?>";
</script>
And just use BASE_URL in the url: like so url: BASE_URL+'classes/deletepost',
Please Try to follow this:
In Codeigniters View:
<!-- Store ID and baseurl as attributes . this would help you to fetch data -->
<button class="btn" postId="5" baseUrl="<?php echo base_url();?>" id="button">Delete</button>
<!-- Store ID and baseurl as attributes . this would help you to fetch data -->
<button class="btn" postId="5" baseUrl="<?php echo base_url();?>" id="button">Delete</button>
<!-- reading jquery file .. -->
<script type="text/javascript" src="http://localhost/jquery/js_search/jquery.js"></script>
<!--you can write file in extra js file .. it depends on you -->
<script type="text/javascript">
$('#button').click(function(){
// ask for confirmation
var result = confirm("Want to delete?");
// if it is confirmed
if (result) {
// get baseURL and ID using attributes
var base_url = $('#button').attr('baseUrl');
var postid = $('#button').attr('postId');
// make a ajax request
$.ajax({
url: base_url,
type: "POST",
dataType: 'json',
success: function (data) {
if(data){
// Fade out the content id
$('#content_id').closest(".todo-content").fadeOut();
}
}
});
}
});
</script>
in controller:
// You just need to delete the post and return a status code of "200"
public function deletepost(){
$id = $this->input->post('postid');
$data = array('active' => 0);
$this->Model_name->deletepost($id,$data);
redirect('/abc/123');
}
bit of a selfish question but I am really strugerling with ajax in general so I need some help. So basically Im trying to update and sql database using an 'onblur' function. heres my code:
code on index.php
function saveStatus(){
var status =document.getElementById("statusForm").value;
$.ajax({
url: 'saveStatus.php',
type: 'post',
data: 'feed_id=' + status,
success: function(result){
}
}
<form id="statusUpdate" action = "whosout.php" method="post">
<input type="text" id="statusForm" onblur="saveStatus()"
placeholder="<?php if($status!=null){ echo '‘'.$status.'’';}
else { echo 'Enter your status here.';}?>">
</form>
and code on saveStatus.php
<?
require 'core.php';
require 'connect.php';
$status = $_POST['feed_id'];
$idPerson = $_SESSION['user_id'];
$query = "UPDATE person SET status = '".mysql_real_escape_string($status)."'
WHERE idPerson = '$idPerson'";
$query_run = mysql_query($query);
?>
at the moment the sql database does not update when i click of the input box. Any help would be great!!
Answer:
You have to devide scripts and html output
You forget );.You have to close $.ajax block.
You miss } closing function saveStatus().
Code:
<script>
function saveStatus(){
var status =document.getElementById("statusForm").value;
$.ajax({
url: 'saveStatus.php',
type: 'post',
data: 'feed_id=' + status,
success: function(result){
}
}); // <-- Also, you forget `);` here
} // <-- Also, you foget closing `}` here
</script>
<form id="statusUpdate" action = "whosout.php" method="post">
<input type="text" id="statusForm" onblur="saveStatus()"
placeholder="<?php if($status!=null){ echo '‘'.$status.'’';}
else { echo 'Enter your status here.';}?>">
</form>
Not error, but advice:
Also, note this: you used jQuery ajax function, so use jQuery in other cases too (you used pure JavaScript instead).
You getting value this way:
var status = document.getElementById("statusForm").value;
Use jQuery syntax instead:
var status = $("#statusForm").val();
Additional info
As, #Utkanos noticed in comments to this answer:
...all of which would be obvious if you look in the error console.
You have to use some debug tool, like FireBug or DevTools (Chrome, also in Chrome you can use CTRL+SHIFT+J). Not have to. You MUST do it.