CI + AJAX, Double posting + refreshing of page - ajax

So I have a normal form with 1 textarea and two hidden inputs, which I would like to post via AJAX to a CI controller I have that inserts the information into the database.
The problem I'm having is that a) the page action is still called and the output of the controller is displayed and b) because the initial AJAX request is still processed plus the extra loading of the action target the information gets inserted twice.
This is my javascript code:
$(document).ready(function() {
$("#submit-comment").click(function(){
var post_id = <?=$p->id?>;
var user_id = <?=$user->id?>;
var content = $("textarea#content").val();
if(content == '') {
alert('Not filled in content');
return false;
}
$.ajax({
type: "POST",
url: "<?=site_url('controller/comment')?>",
data: "post_id="+post_id+"&user_id="+user_id+"&content="+content,
success: function(msg){
alert(msg);
}
});
});
});
I have tried doing
...click(function(e)... ... e.preventDefault
with no luck.
What am I doing wrong? :P
Thanks
Ps. All the information is processed properly and accessed, it's just the preventing the form which is screwing it up..

Just realised I was using a input type="submit", rather than input type="button".
Doh!

Related

Print fetched data with ajax in codeigniter

I am trying to make chat room with ajax. Till now I am able to store data in db without page load. And also able to fetch data and display onscreen using ajax. Here is what I did with ajax
$('#chat').submit(function(){
var chatmsg = $("#chatmsg").val(); //chat message from input field
var chatroomid = $("#chatroomid").val(); //hidden input field
$.ajax({
url: baseurl+'User_dash/chatmessage', //An function in ctroller which contains only insert query
type: 'post',
data: {chatmsg:chatmsg, chatroomid:chatroomid},
dataType: 'json',
success: function (argument) {
if(argument['status']){
$("#chatting").append(" <li id='"+getvalue+"'>"+argument['msg']+"</li>."); //Here I am printing chat message which resently submitted in database
}
}
},
error: function (hrx, ajaxOption, errorThrow) {
console.log(ajaxOption);
console.log(errorThrow)
}
});
return false;
});
This method with ajax is working fine. But issue I faced here is that, this display chat message only to current user. Not to other side of user whome message is being sent via chat.
To solve this issue I come up with one idea which doesn't seems to be working as I planed. Here it is how I modified my previous ajax code..
$('#chat').submit(function(){
var chatmsg = $("#chatmsg").val();
$.ajax({
url: baseurl+'User_dash/chat', //controller function which contains insert query, after that select query to fetch chat data from db and store in view
type: 'post',
data: {chatmsg:chatmsg},
dataType: 'json',
success: function (argument) {
if(argument['status']){
//Not doing anything here this time
}
},
error: function (hrx, ajaxOption, errorThrow) {
console.log(ajaxOption);
console.log(errorThrow)
}
});
return false;
});
In updated version of script I thought If I will call a controller function which is storing data in view (chat page) then It will run query and print data without page load.
But with this method, I am getting chat onscreen only after page load, although it is getting submit in db with ajax fine.
Here is controller code for my second method with ajax if needed
public function chat(){
if(!empty($_POST['chatmsg'])){
$chatdata = array('CHAT_ROOM'=>$_POST['chatroomid'],
'VENDOR'=>$this->session->userdata('USER_ID'),
'BUYER'=>49,
'MESSAGE'=>$_POST['chatmsg']
);
$this->db->insert('tbl_chat', $chatdata); //inserting data
}
$data['chatroom'] = $this->db->where('CHAT_ROOM', 1)->get('tbl_chat')->result_array(); //fetching data from db
$this->load->view('userDash/chat', $data);
}
How do I achieve to run insert and then select query and print data on screen without page load?
Where I am getting wrong?
I solved my issue earlier, What I did was, just added this jquery script which keep refreshing (every second) a certain div inside page in which I have put query to fetch chat from db and printing them.
setInterval(function(){
$("#chatting").load(location.href + " #chatting");
}, 1000);

Reading data attribute after AJAX call

I'm having some trouble reading a data attribute value after updating through an AJAX call.
Here's the call, which works and updates the data-paged value successfully.
$('.block-resource-feed').on('click','#get-more-posts div',function(){
// Get current paged value
var paged = $(this).data('paged');
$.ajax({
type: 'POST',
url: jsVar.ajax_url,
dataType: "html",
data: {
action : 'get_more_posts',
paged : paged
},
success: function( response ) {
// Return data
$('#post-feed').append(response);
// Updated paged value
$('#get-more-posts div').attr('data-paged',paged + 1);
}
});
})
and the HTML side for the button;
<div id="get-more-posts">
<div data-count="13" data-paged="2">More resources</div>
</div>
The issue arrises when clicking the div again and the value always stays at 2, despite changing in the DOM.
I thought using the above on click method should allow reading of DOM elements after the call?
You should set/update this values on instance of your this element.
Add this above ajax call
const self = $(this);
and change your code in success callback
$('#get-more-posts div').attr('data-paged',paged + 1);
to
self.data('paged',paged+1);
This will work now.
JSFIDDLE

Form post but do not reload the page

I am stuck in this like I have never before.
My situation : I am making a shopping cart. When user click "Add" button, it posts the form and in the server side i.e inside if(IsPost){....}, corresponding item gets added to the the the cart table in my database.
Everything is fine, except it reloads the page and scrolls back to top. With a little research, I got to know that may be Ajax could help. Then I created a new .cshtml page add-to-cart.cshtnl. Now my current page doesn't reload but it opens add-to-cart.cshtml which is not how I wanted. Now I even tried to learn AJAX and try doing things looking at examples. Nothing helps. Please help!
Here is what my code looks like : P.S I am using razor in webmatrix.
<form method="post" id="productForm" action="~/add-to-cart.cshtml">
<input ............"Input Something.............../>
<button type="submit" id="add-button" >ADD</button>
</form>
At my add-to-cart.cshtml, I don't have anything on the UI. It just processes data.I don't want that page to ever load. It looks something like this:
ifIsPost(){
............ADD item to the cart table of database..............
}
Now I am convinced, AJAX is my solution but how????
Please don't give me incomplete answers. I have already wasted 3 days in it :/
Try this
$('#productForm').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data : $(this).serialize(),
success : function(response) {
//write your code here
},
error : fucntion(response) {
//write your code here
}
});
});
Put this script into <script> tag.
Note: Don't forgot to include jquery in your page.
Here is the complete working solution :
$(function () {
$('#productForm').submit(function (ev) {
var frm = $(this);
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
//Do What Ever You Wanna Do
}
});
ev.preventDefault();
});
});

Ajax send parameters through url

I'm new with ajax and thought i'd be a fun experiment to put into my project. I've created my own lightbox type feature to send a message on a website I'm creating. When the user clicks "Send Message", that's when the lightbox appears, and at the top I'm trying to get it to say "Send message to User", where User is the name of the user they're sending a message too. My lightbox html elements are actually on a seperate webpage, which is why I'm using ajax. this is what I have so far, and can't seem to figure out what the problem is:
user.php page
<div id = "pageMiddle"> // This div is where all the main content is.
<button onclick = "showMessageBox(UsersName)">Send Message</button>
</div>
Note: The username passes correctly into the javascript function, I have checked that much.
main.js page
function showMessageBox(user){
alert(user); // where i checked if username passes correctly
var ajaxObject = null;
if (window.XMLHttpRequest){
ajaxObject = new XMLHttpRequest();
}else if (window.ActiveXObject){
ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
}
if (ajaxObject != null){
ajaxObject.open("GET", "message_form.php", true);
ajaxObject.send("u="+user);
}else{
alert("You do not have a compatible browser");
}
ajaxObject.onreadystatechange = function(){
if (ajaxObject.readyState == 4 && ajaxObject.status == 200){
document.getElementById("ajaxResult").innerHTML = ajaxObject.responseText;
// use jquery to fade out the background and fade in the message box
$("#pageMiddle").fadeTo("slow", 0.2);
$("#messageFormFG").fadeIn("slow");
}
};
}
message_form.php page
<div id = "messageFormFG">
<div class = "messageFormTitle">Sending message to <?php echo $_GET['u']; ?></div>
</div>
Note: When accessing this page directly through the URL, giving it a parameter of u and a value, it displays correctly
Use jQuery.ajax();
http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "GET",
url: "message_form.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
freakish way to do it (old school) :)
anyway i think the problem may be that you are loading an entire html page to a div! meaning tags and stuff, a good way to understand what's wrong would be to use a debugger and see what comes in ajaxObject.responseText.
Hope this helps.
Btw convert to jQuery ajax!! saves you loads of time =)
I believe that you need to add a request header prior to sending your data. So you'd have this:
ajaxObject.open("GET", "message_form.php", true);
ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxObject.send("u="+encodeURIComponent(user));
Instead of what you have.
However, it may be a good idea to allow a library to do this for you. It looks like you already have jQuery loaded, so why not let it handle your AJAX requests instead?
I figured it out after watching some ajax tutorials from bucky :) aka thenewboston. If I'm using the GET method, i just had to add the parameter to the end of the url in the .open function, instead of passing it through the send function (like you would a post method).
if you want to send number of field values using ajax.you can use serilalize function.
Example:
jQuery.ajax({
url: 'filenamehere.php',
type: 'post',
data: $("#formidhere").serialize(),
success: function(data){
..//
}
});

How to avoid redirect after form submission if you have a URL in your form's action?

I have a form that looks like this:
<form name="formi" method="post" action="http://domain.name/folder/UserSignUp?f=111222&postMethod=HTML&m=0&j=MAS2" style="display:none">
...
<button type="submit" class="moreinfo-send moreinfo-button" tabindex="1006">Subscribe</button>
In the script file I have this code segment where I submit the datas, while in a modal box I say thank you for the subscribers after they passed the validation.
function () {
$.ajax({
url: 'data/moreinfo.php',
data: $('#moreinfo-container form').serialize() + '&action=send',
type: 'post',
cache: false,
dataType: 'html',
success: function (data) {
$('#moreinfo-container .moreinfo-loading').fadeOut(200, function () {
$('form[name=formi]').submit();
$('#moreinfo-container .moreinfo-title').html('Thank you!');
msg.html(data).fadeIn(200);
});
},
Unfortunately, after I submit the datas, I'm navigated to the domain given in the form's action. I tried to insert return false; in the code (first into the form tag, then into the js code) but then the datas were not inserted into the database. What do I need to do if I just want to post the data and stay on my site and give my own feedback.
I edited Eric Martin's SimpleModal Contact Form, so if more code would be necessary to solve my problem, you can check the original here: http://www.ericmmartin.com/projects/simplemodal-demos/ (Contact Form)
Usually returning false is enough to prevent form submission, so double check your code. It should be something like this
$('form[name="formi"]').submit(function() {
$.ajax(...); // do your ajax call here
return false; // this prevent form submission
});
Update
Here is the full answer to your comment
I tried this, but it didn't work. I need to submit the data in the succes part, no?
Maybe, it depends from your logic and your exact needs. Normally to do what you asking for I use the jQuery Form Plugin which handle this kind of behavior pretty well.
From your comment I see that you're not submitting the form itself with the $.ajax call, but you retrieve some kind of data from that call, isn't it? Then you have two choices here:
With plain jQuery (no form plugin)
$('form[name="formi"]').submit(function() {
$.ajax(...); // your existing ajax call
// this will post the form using ajax
$.post($(this).attr('action'), { /* pass here form data */ }, function(data) {
// here you have server response from form submission in data
})
// this prevent form submission
return false;
});
With form plugin it's the same, but you don't have to handle form data retrieval (the commented part above) and return false, because the plugin handle this for you. The code would be
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$(form[name="formi"]).ajaxForm(function() {
// this call back is executed when the form is submitted with success
$.ajax(...); // your existing ajax call
});
});
That's it. Keep in mind that with the above code your existing ajax call will be executed after the form submission. So if this is a problem for your needs, you should change the code above and use the alternative ajaxForm call which accepts an options object. So the above code could be rewritten as
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$(form[name="formi"]).ajaxForm({
beforeSubmit: function() { $.ajax(...); /* your existing ajax call */},
success: function(data) { /* handle form success here if you need that */ }
});
});

Resources