So... thanks to one of stackoverflow users I tried to implement this fancy feature into my existing Codeigniter application...
In my View I have this:
<script type="text/javascript">
$(function() {
$(".submit_op").click(function() {
var dataString = $("#op_form").serialize();
var url = "<?php echo site_url('submit/insert_data'); ?>";
$.ajax({
type: "POST",
url: url+"/"+dataString,
data: dataString,
cache: false,
success: function(html){
//$("div#op").prepend(html); //PROBLEM HERE???
$("div#op").prepend("<div>TEST</div>");
$("div#op div:first").fadeIn("slow");
//$("#debug").append("<font color=green><b>OK!</b></font> : " + dataString + "<br/>");
},
error: function(html){
//$("#debug").append("<font color=red><b>ER!</b></font> : " + dataString + "<br/>");
}
});
return false;
});
});
</script>
<div id="debug"></div>
<?php
//here goes some data from db... newly added div should go in top of other divs
foreach ($some_data_sent_from_controller as $var) {
echo "<div id=\"op\">";
echo "<table width=\"100%\" border=\"0\">";
//showing data
echo "</table>";
echo "</div>";
}
echo "<form action=\"#\" id=\"op_form\">";
//some clickable stuff...
echo br().form_submit('submit', 'OK', 'class="submit_op"');
echo "</form>";
In my Controller I have a function which handles data sent from View:
function insert_data($input) {
$this->load->model('blah_model');
//processing serialized data and sending it to corresponding tables via Model
$this->blah_model->add_to_table($some_data);
$this->blah_model->add_to_another_table($some_other_data);
}
And the Model is not a biggy :)
function add_to_table($data){
//processing data...
$insert = $this->db->insert('my_table', array('array_which_contains_actual_data'));
if ($insert == TRUE) {
return TRUE;
} else {
return FALSE;
}
}
//etc.
As far as I can tell, my problem is not in my M-V-C pattern, since every time I submit a form the data is correctly inserted in all possible tables in my relational db... But the newly added row just won't show up unless I refresh a page.
I think that I'm doing something wrong inside of my jQuery.ajax lines... If I run my script with this line $("div#op").prepend("<div>TEST</div>"); and when I submit a form, I get desired result - text TEST shows up on top of my page every time I submit... But if I change that line to $("div#op").prepend(html); nothing show up until refreshing...
What am I doing wrong here??
Thanks a lot for any help!
wow, this was probably pretty lame from me... But in the end I figured out that I have to echo out my result in controller, not return it... So when I change the function in my controller into
function insert_data($input) {
$str = "<div>KILLROY WAS HERE!</div>";
echo $str; // <----- !!!!!!
}
I can see a message on my page...
Now to other things... Thanks for self-brainstorming :)
Related
I am submitting form data via Ajax and would like to display a message above the form on successful submit.
Currently the form does send the data successfully. It should render the feedback message on form submit <?php $this->renderFeedbackMessages(); ?> as defined in my config.php
Where am I going wrong? Possibly doing things in the wrong order due to first time working with mvc?
my config.php file I have the following defined;
define("FEEDBACK_BOOK_ADD_SUCCESSFUL", "Book add successful.");
my model;
public function addIsbn($isbn)
{
// insert query here
$count = $query->rowCount();
if ($count == 1) {
$_SESSION["feedback_positive"][] = FEEDBACK_BOOK_ADD_SUCCESSFUL;
return true;
} else {
$_SESSION["feedback_negative"][] = FEEDBACK_NOTE_CREATION_FAILED;
}
// default return
return false;
}
my controller;
function addIsbn()
{
// $_POST info here
header('location: ' . URL . 'admin/searchIsbn');
}
my searchIsbn.php;
<?php $this->renderFeedbackMessages(); ?>
<div>
//my html form here
</div>
<div id="result"></div>
<script>
$('#form').submit(function() {
event.preventDefault();
var isbn = $('#isbn_search').val();
var url='https://www.googleapis.com/books/v1/volumes?q=isbn:'+isbn;
$.getJSON(url,function(data){
$.each(data.items, function(entryIndex, entry){
$('#result').html('');
var html = '<div class="result">';
html += '<h3>' + entry.volumeInfo.isbn + '</h3>';
html += '<hr><button type="button" id="add" name="add">add to library</button></div>';
$(html).hide().appendTo('#result').fadeIn(1000);
$('#add').click(function(ev) {
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>admin/addIsbn',
data: {
'isbn' : isbn
}
});
});
});
});
});
</script>
No console error messages.
You are redirecting here:
header('location: ' . URL . 'admin/addIsbn');
remove it.
echo the success message here and add it to an HTML element's .html() API.
Your page will not be refreshed.
Your page is making the call to admin/addIsbn which is redirected to admin/searchIsbn. So you already have the output of renderFeedbackMessages() being sent to your function.
Use the success callback to output the results to the page:
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>admin/addIsbn',
data: {
'isbn' : isbn
},
success: function(data) {
$('#result').html(data);
}
});
The only way I could get this to work was to add an auto-refresh to my Ajax success function as follows;
window.location.reload(true);
Working however open to suggestions.
I have a php page where i have used a jquery function to get the dynamic value according to the values of checkboxes and radio buttons and text boxes. Whats' happening is i have used two alerts
1.) alert(data);
2.)alert(grand_total);
in the ajax part of my Jquery function just to ensure what value i'm getting in "grand_total". And everything worked fine, alerts were good and data was being inserted in the table properly.
Then i removed the alerts from the function, and after sometime i started testing the whole site again and i found value of grand_total in not being inserted in mysql table.
I again put those alerts to check what went wrong, again everything started working fine. Removed again and problem started again. Any idea folks what went wrong?
here is the code snippet of JQUERY func from "xyz.php":
<script type="text/javascript">
$(document).ready(function() {
var grand_total = 0;
$("input").live("change keyup", function() {
$("#Totalcost").val(function() {
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).val(), 10);
});
var textVal = parseInt($("#min").val(), 10) || 0;
grand_total = total + textVal;
return grand_total;
});
});
$("#next").live('click', function() {
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
},
success: function(data) {
// do something;
}
});
});
});
Corresponding HTML code:
<form method="post" id="logoform3" action="xyz_sql.php">
<input type="text" name="Totalcost" id="Totalcost" disabled/>
<input type="submit" id="Next" name="next"/>
This the code from *"xyz_sql.php"*:
<?php
session_start();
include ("config.php");
$uid = $_SESSION['uid'];
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2 (total,uid)VALUES('$total','$uid');";
if($total > 0){
$res = mysql_query($sql);
}
if($res)
{
echo "<script> window.location.replace('abc.php') </script>";
}
else {
echo "<script> window.location.replace('xyz.php') </script>";
}
?>
And last but not the least: echo " window.location.replace('abc.php') ";
never gets executed no matter data gets inserted in table or not.
First you submit form like form, not like ajax - cause there is no preventDefault action on clicking submit button. That's why it looks like it goes right. But in that form there is no input named "grand_total". So your php script fails.
Second - you bind ajax to element with id "next" - but there is no such element with that id in your html that's why ajax is never called.
Solutions of Роман Савуляк is good but weren't enough.
You should casting your $total variable to integer in php file and also use if and isset() to power your code, so I'll rewrite your php code:
<?php
session_start();
include ("config.php");
if(isset($_SESSION['uid']))
{
$uid = $_SESSION['uid'];
if(isset($_POST['grand_total']))
{
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2(total,uid) VALUES('".$total."','".$uid."')";
if((int)$total > 0)
{
if(mysql_query($sql))
{
echo "your output that will pass to ajax done() function as data";
}
else
{
echo "your output that will pass to ajax done() function as data";
}
}
}
}
and also you can pass outputs after every if statement, and complete js ajax function like:
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
}
}).done(function(data) {
console.log(data); //or everything
});
I have wrote this code in php:
public function getinfo($username){
$this->autoRender = false;
if($this->request->is('ajax')){
if(!ereg('^[A-Za-z0-9_.]+$',$username)){
echo 'username';
}
else{
$user = $this->User->find('all',array('conditions'=>array('User.username'=>$username)));
if(empty($user)){
echo 'Fail';
}
else{
$this->loadModel('Question');
$question = $this->Question->find('all',array('conditions'=>array('Question.id'=>$user[0]['User']['questionid'])));
echo 'Sec Question : ' . $question[0]['Question']['title'] . '<br />';
echo 'Answer: <input type="text" id="userAnswer" class="loginField" name="data[answer]" /> ';
echo '<input type="submit" id="sendAnswer" class="button" value="send" /> <br />';
echo '<span id="recoverErr"></span>';
$this->Session->write('recoverPass',$user[0]);
}
}
}
else{
$this->redirect(array('controller'=>'message','action'=>'forbidden'));
}
}
And I have wrote this in my jquery file:
$('#send').click(function(){
var recover = $('#recoverUsername').val();
$('#recErr').css('color', 'red');
if(recover == ''){
$('#recoverUsername').focus();
$('#recErr').html('Enter username');
return false;
}
$.ajax({
url: $('#base').html() + '/users/getinfo/'+recover,
type: 'POST',
success: function(data){
if(data.match('username')){
$('#recErr').html('Enter correct username.');
}
else if(data.match('Fail')){
$('#recErr').html("This username doesn't exist");
}
else{
$('#recErr').html('');
$('#recoverWindow').html(data);
$('#recoverWindow').dialog('open');
}
}
});
});
$('#sendAnswer').click(function(){
var answer = $('#userAnswer').val();
$.ajax({
url: $('#base').html() + '/users/getanswer/'+answer,
type: 'POST',
success: function(data){
if(data.match('answer')){
$('#recoverErr').html('Enter answer');
}
else if(data.match('Fail')){
$('#recoverErr').html('answer is false.');
}
else if(data.match('Bad')){
$('#recoverErr').html('fail too send mail.');
}
else{
$('#recoverWindow').html('');
$('#recoverWindow').html('Email was sent, check your spam if it is not in your inbox.');
}
}
});});
but when I click and the server found the User's info and put it in recoverWindow the click function doesn't work and doesn't send the answer to the action.
please Help me, i don't have time
You have used Ajax for creating recover form in your php function. so you can't put $('#sendAnswer').click() in ready function. Because sendAnswer element doesn't exist in your HTML and you want create in your php file.
So you should write click function for this element after ajax execution. With this explanation your JQuery Code should change to this:
$('#send').click(function(){
var recover = $('#recoverUsername').val();
$('#recErr').css('color', 'red');
if(recover == ''){
$('#recoverUsername').focus();
$('#recErr').html('Enter username');
return false;
}
$.ajax({
url: $('#base').html() + '/users/getinfo/'+recover,
type: 'POST',
success: function(data){
if(data.match('username')){
$('#recErr').html('Enter correct username.');
}
else if(data.match('Fail')){
$('#recErr').html("This username doesn't exist");
}
else{
$('#recErr').html('');
$('#recoverWindow').html(data);
$('#recoverWindow').dialog('open');
$('#sendAnswer').click(function(){
var answer = $('#userAnswer').val();
$.ajax({
url: $('#base').html() + '/users/getanswer/'+answer,
type: 'POST',
success: function(data){
if(data.match('answer')){
$('#recoverErr').html('Enter answer');
}
else if(data.match('Fail')){
$('#recoverErr').html('answer is false.');
}
else if(data.match('Bad')){
$('#recoverErr').html('fail too send mail.');
}
else{
$('#recoverWindow').html('');
$('#recoverWindow').html('Email was sent, check your spam if it is not in your inbox.');
}
}
});});
}
}
});});
Help me, i don't have time
thats the reason you didn't search for other related answer..
anyways like many other answers in stackoverflow including mine , here i go again..
you need to delegate click event for dynamically added element using on
$('#recoverWindow').on('click','#sendAnswer',function(){
....
instead of
$('#sendAnswer').click(function(){
If your element with id="sendAnswer" is loading via ajax and you wrote click event for that in your main page then you have to use .on() or .live() method to get it executed.
But they both methods are used for different jQuery versions.
Please write it as following
$(document).ready(function() {
//if you are using jQuery version after 1.7 then use following
$(document).on('click', '#sendAnswer', function(){
//your logic
});
//if you are using jQuery version upto 1.7 then use following
$('#sendAnswer').live('click', function(){
//your logic
});
});
I have this
"fsField" is the class of all elements in the form. So whenever the user blurs to another field it submits the form using the function autosave() - given below. It saves data when the user blurs but when the user clicks the button with class "save_secL" to go to next page it does not save.
$('.fsField').bind('blur', function()
{
autosave();
}
});
but when i use this code
$('.save_secL').click(function()
{
var buttonid = this.id;
{
var answer = confirm("You have left some questions unanswered. Click OK if you are sure to leave this section? \\n Click CANCEL if you want stay in this section. ");
if(!answer)
{
var spl_items = valid().split(',');
$(spl_items[0]).focus();
return false;
}
else
{
$('#hidden_agree').append('<input id="secLuseragreed" name="secL_user_agreed" value="unanswered" type="hidden" />');
autosave();
window.location= buttonid+".php"
}
}
else
{
$('#hidden_agree').append('<input id="secLuseragreed" name="secL_user_agreed" value="answered all" type="hidden" />');
autosave();
window.location= buttonid+".php"
}
}
});
**autosave_secL.php is the php source thats saving the data in the database. I ran it independently and it does save data okay. **
function autosave()
{
var secL_partA_ques_1_select = $('[name="secL_partA_ques_1_select"]').val();
var secL_partA_ques_1 = $('[name="secL_partA_ques_1"]:checked').val();
var secL_partA_ques_2_select = $('[name="secL_partA_ques_2_select"]').val();
$.ajax(
{
type: "POST",
url: "autosave_secL.php",
data: "secL_partA_ques_1_select=" + secL_partA_ques_1_select + "&secL_partA_ques_1=" + secL_partA_ques_1 + "&user_id=<?php echo $row_token[user_id]?>" + "&updated_by=<?php echo $member."-".$key;?>",
cache: false,
success: function()
{
$("#timestamp").empty().append('Data Saved Successfully!');
}
});
}
**
valid() is a validation function that checks if any field is empty and returns a value if there is an empty field.**
function valid()
{
var items = '';
$('.fsField').each(function()
{
var thisname = $(this).attr('name')
if($(this).is('select'))
{
if($(this).val()=='')
{
var thisid = $(this).attr('id')
items += "#\"+thisid+\",";
$('[name=\"'+thisname+'\"]').closest('td').css('background-color', '#B5EAAA');
}
}
else
{
$('[name=\"'+thisname+'\"]').closest('td').css('background-color', '');
}
});
return items;
}
Can anyone please help? i am stuck for a day now. Can't understand why it saves when the user goes field to field but does not save when button is clicked with validation.
Tested with Firefox. this line appears in red with a Cross sign beside when the button(save_secL class) is clicked. I am using a ssl connection.
POST https://example.com/files/autosave_secL.php x
Here is the modified code trying to implement the solution
$('#submit_survey_secL').click(function()
{
if(valid() !='')
{
var answer = confirm("You have left some questions unanswered. Are you sure you want to Submit and go to Section B? ");
if(!answer)
{
var spl_items = valid().split(',');
$(spl_items[0]).focus();
return false;
}
else
{
$('#hidden_agree').append('<input id=\"secLuseragreed\" name=\"secL_user_agreed\" value=\"unanswered\" type=\"hidden\" />');
autosave(function(){
window.location= "part1secM.php?token=1&id=4"
});
}
}
else
{
$('#hidden_agree').append('<input id=\"secLuseragreed\" name=\"secL_user_agreed\" value=\"unanswered\" type=\"hidden\" />');
autosave(function(){
window.location= "part1secM.php?token=1&id=6"
});
}
});
function autosave(callback)
{
var secL_partL_ques_1_select = $('[name="secL_partL_ques_1_select"]').val();
var secL_partL_ques_1 = $('[name="secL_partL_ques_1"]:checked').val();
var secL_partL_ques_2_select = $('[name="secL_partL_ques_2_select"]').val();
$.ajax(
{
type: "POST",
url: "autosave_secL.php",
data: "secL_partL_ques_1_select=" + secL_partL_ques_1_select + "&secL_partL_ques_1=" + secL_partL_ques_1 + "&user_id=<?php echo $row_token[user_id]?>" + "&updated_by=<?php echo $member."-".$key;?>",
cache: false,
success: function()
{
$("#timestamp").empty().append('Data Saved Successfully!');
if($.isFunction(callback))
{
callback();
}
}
});
}
I don't understand why this doesn't work as callback should totally work. Firebug does not show POST https://example.com/files/autosave_secL.php in red any more but it shows that it has posted but I think the callback is not triggering for some reason
$('.save_secL').click(function() {
//...
//start autosave. Note: Async, returns immediately
autosave();
//and now, before the POST request has been completed, we change location...
window.location= buttonid+".php?token=$row_token[survey_token]&$member=$key&agr=1"
//....and the POST request gets aborted :(
Solution:
function autosave(callback)
{
//...
$.ajax(
{
//...
success: function()
{
$("#timestamp").empty().append('Data Saved Successfully!');
if($.isFunction(callback))
callback();
}
});
}
//and
autosave(function(){
window.location= buttonid+".php?token=$row_token[survey_token]&$member=$key&agr=1"
});
By the way, your autosave function is pretty hard for your server. Did you consider using localStorage + a final POST request containing all data?
I got the solution.
It might be one of the several. scr4ve's solution definitely helped. So here are the points for which I think its working now.
Moved "cache: false, " and removed "async:false" before url: in the ajax autosave function. Before I was putting it after "data: "
Added a random variable after autosave_secL.php/?"+Match.random()
Added scr4ve's solution so that POST is completed before redirect
I am have a table that shows the user suggestions that they have recieved on clicking read more some ajax is fired and in the database the suggestion is marked as read. Currently if the suggestion is new I show a closed envelope, if it is read I show an open envelope, however I can get it to reload the table when the user clicks the read more link so that the new class can be added. Currently it half works, they click read more and the full suggestions fades in but I need the envelope to change also.
<table>
<?php
$colours = array("#f9f9f9", "#f3f3f3"); $count = 0;
if(isset($newSuggestions)) {
foreach($newSuggestions as $row) {
if($row['commentRead'] == 0) {
$newRow = "new";
} else {
$newRow = "old";
}
?>
<tr id="a<?=$row['thoughtId'];?>" bgcolor="<?php echo $colours[$count++ % count($colours)];?>">
<?php
echo "<td class='".$newRow."'>".substr($row['thought'], 0,50)."...</td>";
echo "<td class='read'><a href='".base_url()."thought/readSuggestion/".$row['thoughtId']."' class='readMore'>Read More</a>";
echo "</tr>";
}
} else {
echo "You have no new suggestions";
}
?>
</table>
</div><!--/popular-->
</div><!--/widget-->
<div id="readMore">
</div>
<script type="text/javascript">
$(document).ready(function() {
//alert("hello");
$('#tabvanilla').tabs({ fx: { opacity: 'toggle', height:'toggle' } });
$('a.readMore').click(function(){
$('#readMore').fadeIn(500);
var url = $(this).attr('href');
$.ajax({
url : url,
type : "POST",
success : function(html) {
$('#readMore').html(html)
},
complete : function(html) {
$('table').html()
}
});
return false;
});
});
</script>
In the JavaScript where you open/fill in the full suggestions, you can modify the envelope image as well, using something like:
$('#envelope').attr('src', 'src/to/envelope.png');
I see no img tags, so you need to add one and fill in the id, so it is found by the JavaScript.
BTW: Having HTML and PHP on the same lines/parts, makes the total very unreadable. Only use <?php ... ?> for large PHP code blocks, otherwise use echo (or something similar).