Ajax success function loading div repeatly in codeigniter - php

My ajax code is here,
Success function always shown two times.
If i have two records in database means it will retrieve that two rows on two times, Three row means retrieve two times
<script type="text/javascript">
$(document).ready(function()
{
$('form#form1').submit(function(e) {
var form = $(this);
var srpid = form.find('#srpid').val();
//$('#cmd_'+srpid).html(" ");
e.preventDefault();
$.ajax({
'type': "POST",
url: "<?php echo base_url('pages/post/comments'); ?>",
'data': form.serialize(), // <--- THIS IS THE CHANGE
//dataType: "html",
'success': function(data){
$('#cmd_'+srpid).html(data);
},
//error: function() { alert("Error posting feed."); }
});
return false;
});
});
</script>
<div class="post-scroll" id="cmd_<?php echo $post_id; ?>">
<?php
$command = $this->db->order_by('comment_date','DSC')->where('post_id',$post_id)->get('sr_post_comment')->result();
foreach($command as $cmd){
$usercmdview = $this->db->get_where('users',array('id' => $cmd->user_id))->result();
?>
<div class="post-cnt" style="float:left;">
<div class="post-img">
<img src="<?php echo $usercmdview[0]->image; ?>" />
</div>
<div class="post-name">
<p><?php echo $usercmdview[0]->firstname." "; ?><br /><span><?php echo $cmd->comment_date; ?></span></p>
</div>
<div class="post-cmd">
<p class="cmdlist_<?php echo $cmd->comment_id; ?>"><?php echo $cmd->comments; ?></p>
</div>
</div>
<?php } ?>
</div>

You defined an ajax request at "submit" action, but you didn't stop the form submit. It means when you click the "submit" button, the following actions will be done.
ajax submit the data to server
the form submit also, and it will refresh page.
<script type="text/javascript">
$(document).ready(function(){
$('form#form1').submit(function(e) {
...
return false;
});
});
</script>

Related

Ajax html input value appears empty

I am trying to submit a form via ajax post to php but the value of the input tag appears to empty.
I have cross-checked defined class and id and it seems ok. I don't where my mistake is coming from. Here is the code
index.html
<div class="modal">
<div class="first">
<p>Get notified when we go <br><span class="live">LIVE!</span></p>
<input type="text" class="input" id="phone" placeholder="Enter your email adress" />
<div class="arrow">
<div class="error" style="color:red"></div>
<div class="validator"></div>
</div>
<div class="send">
<span>Subscribe</span>
</div>
</div>
<div class="second">
<span>Thank you for<br />subscribing!</span>
</div>
</div>
<script src='jquery-3.3.1.min.js'></script>
<script src="script.js"></script>
script.js
$(document).ready(function(){
function validatePhone(phone) {
var re = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
return re.test(phone);
}
$('.input').on('keyup',function(){
var formInput = $('.input').val();
if(validatePhone(formInput)){
$('.validator').removeClass('hide');
$('.validator').addClass('valid');
$('.send').addClass('valid');
}
else{
$('.validator').removeClass('valid');
$('.validator').addClass('hide');
$('.send').removeClass('valid');
}
});
var phone = $('#phone').val();
var data =
'phone='+phone;
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
});
subscribe.php
```php
$phone = htmlentities($_POST['phone']);
if (!empty($phone)) {
echo 1;
}else{
echo "Phone number cannot be empty";
}
```
An empty results with the error code is all I get. Can any one help me out here with the mistakes I am making. Thanks
Change next
JS:
$('.send').click(function(){
$.ajax({
type:"POST",
url:"subscribe.php",
data: data,
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
})
});
to
$('.send').click(function(){
var data = $('#phone').val();
$.ajax({
type:"POST",
url:"subscribe.php",
data: {phone: data},
success: function(data){
alert(data);
if (data ==1) {
$('.modal').addClass('sent');
}else{
$('.error').html("Error String:" +data);
}
}
});
});
If you send a POST request via ajax you need to format data as a JSON object, see my code below.
Replace this:
var data =
'phone='+phone;
with this:
var data = {phone: phone};

How to get the POST data from a form inside of an iframe

I have a form inside of an iframe in my CodeIgniter application:
<div class="settings"><h2>Einstellungen</h2>
<div class="main-content">
<iframe src="" name="main-content">
<form id="new-role-form" method="post" action="<?php echo base_url('index.php/home/settings') ?>">
<input class="role-input" type="text" placeholder="Rolle" name="role"><input class="role-input" type="password" placeholder="Passwort" name="password"><button class="button role-submit" type="submit"><span class="glyphicon glyphicon-plus"></span></button>
</form>
</iframe>
</div>
</div>
When submitting this form the following code should be executed (the submit is working I tested it; I can get the inputs of the form here):
$(document).on('submit', '#new-role-form', function(event) {
var form = $(this);
var name = $('input[name="role"]', form).val();
var password = $('input[name="password"]', form).val();
$.ajax({
url: '<?php echo base_url('index.php/ajax/insertRole'); ?>',
type: 'POST',
data: {name: name, password: password},
success: function() {
alert("success");
}
});
event.preventDefault();
});
And this is the insertRole function of my ajax controller:
public function insertRole() {
$this->Database->insert($this->input->post('name'), $this->input->post('password'));
}
This is where I get the error: ...index.php/ajax/insertRole 500 (Internal Server Error)
How can I retrieve the POST data from a form inside an iframe?
If you have problems catching the 'submit' event you could use this:
<script type="text/javascript">
$('#frame').load(function() {
$(this).contents().find('form').submit(function() {
//do your stuff here
});
});
</script>
In order to 'wait' for the iframe being loaded and then catch the submit event. You also could create a function in the main file:
function valueFromIframe(val) {
alert(val)
}
And call from the iframe:
<script type="text/javascript">
parent.valueFromIframe("Hello world");
</script>
Hope it helps

Submit an AJAX FORM from within an AJAX Success

I need to perform another AJAX Form Post from within the first forms success function.
Example, this does 2 AJAX requests.
Search Movie => Pick Movie Wanted => View Specific Movie Details
I am able to load the results into a div <div id="results"></div> just fine but once I select a movie title it isnt performing another AJAX Request, the request goes to the main window.
Here is the initial search page that handles the results.
<script type="text/javascript">
$(document).ready(function(){
$("#searchtitle").submit(function() {
var id = $(this).children('input[name="thetitle"]').attr('value');
$.ajax({
type: "POST",
url: "s.php",
data: $('#searchtitle').serialize(),
cache: false,
success: function(data){
$('#status').html(data);
}
});
return false;
});
});
</script>
<form id="searchtitle">
<input type="text" name="thetitle" />
<input type="submit" name="submit" class="button expand postfix" value="Search" />
</form>
<div id="status"></div>
s.php which returns results within #results
<?php
if(empty($_POST['thetitle'])) {
?>
<div class="alert-box error">
<div class="alert-error"></div>
Error: Nothing Found
</div>
<?php
}
if(!empty($_POST['thetitle'])) {
$myid = strtoupper($_POST['thetitle']);
$searchReults = $tmdb_V3->searchMovie($myid,'en');
?>
<?php
foreach($searchReults['results'] as $result) {
?>
<form class="sform">
<input type="hidden" name="mid" value="<?php echo $result['id']); ?>" />
<h5><?php echo $result['title']; ?></h5>
<span class="mreleased">Year: <?php echo $result['year']; ?></span>
<input type="submit" class="button" value="Select">
</form>
<?php
}
}
?>
This is the code that will post the results from s.php
<script type="text/javascript">
$(".sform").submit(function () {
$.ajax({
type: 'POST',
url: 'sx.php',
data: $(this).closest("form").serialize();
success: function (response) {
$('#status').load(response);
$('#status').find('script').each(function (i) {
eval($(this).text());
});
}
});
return false;
}
</script>
I have tried putting this within s.php, within the bottom of the initial search page, in the head of the initial page and no luck, it submits fine just not the sx.php where it should.
In s.php the statement:
<input type="hidden" name="mid" value="<?php echo $result['id']); ?>" />
Should be:
<input type="hidden" name="mid" value="<?php echo $result['id']; ?>" /> //remove extra bracket
In your javascript code in s.php there are some typos:
data: $(this).closest("form").serialize(); // here should be comma not semicolon
After return false you should close the script properly } should be });.
And since you are trying to submit the dynamic content $(".sform").submit(function () will not work. You should use on for dynamic contents. So the correct script would be:
<script type="text/javascript">
$(document).on('submit', '.sform', function () {
$.ajax({
type: 'POST',
url: 'sx.php',
data: $(this).closest("form").serialize(),
success: function (response) {
$('#status').load(response);
$('#status').find('script').each(function (i) {
eval($(this).text());
});
}
});
return false;
});
</script>
I have checked and verified in my localhost (with a simple setup). It is making both ajax request. Hope this helps!

issue sending a retrieving value using ajax

This is a cleaner code of my preview problem, the idea is to send and retrieve a value using ajax, but the value is not being sent nor ajax seems to work. I updated this code because this way it could be easily tested on any machine. First time using ajax. Here is the code:
Javascript
<script>
jQuery(document).ready(function() {
jQuery('#centro').click( function() {
$.ajax({
url: 'request.php',
type:'POST',
data: $("#form").serialize(),
dataType: 'json',
success: function(output_string){
alert(output_string);
$('#cuentas').html(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
HTML:
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
PHP file, request.php
<?php
$centro = $_POST['centro'];
$output_string = ''.$centro;
echo json_encode($output_string);
?>
Try Changing Your Code A bit like Below .
Jquery part
success: function(d){
var output=d[0].data; // Will output only first record
$('#cuentas').html(output);
} // End of success function of ajax form
PHP PART
$centro = $_POST['centro'];
$output_string = array('data'=>$centro);
echo json_encode($output_string);
if still not works Check The Developer tool in chrome or firebug in firefox to monitor the Requests
Looking at your code:
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
I miss an ending-tag for the div id="centro". Therefore the click-event for jQuery("#centro") will not trigger.
I suppose it should be like this: (Always set <form> and </form> inside OR outside of a div, do not mix and put <form> outside and </form> inside of a div. Some things wont work as expected when you do a mix like that.
<?php
$result = 'works';
?>
<div id="centro">
<form id="form">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
</div> ><!-- end of div centro -->
<div id="cuentas">
</div>
I solved it, now this works, plus I added a gif loader:
Javascript:
<script>
jQuery(document).ready(function() {
jQuery('#centro').click( function() {
var result = $("input#centro").val();
$.ajax({
url: 'request.php',
type:'POST',
data: { 'dataString': result },
beforeSend: function(){
$("#loader").show();
},
success: function(output_string){
$("#loader").hide();
$('#cuentas').html(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
HTML
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
<div id="loader" style="display:none"><img src="ajax-loader.gif" width="20px" height="20px"></div>
Click here
<br>
<input type="hidden" name="centro" id="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
PHP
<?php
$data = $_POST['dataString'];
$output_string = '';
$output_string = '<h3>'.$data.' '.'testing'.'</h3>';
echo $output_string;
?>
Output: "works testing"

How to get Ajax to execute within an Ajax generated FancyBox?

I'm facing a problem using the FancyBox plugin. I'm trying to submit a form with Ajax and just print a nice little success message, no validation just yet, trying to get it to work. I can submit with jQuery and display the value of any input within the FancyBox. However when I try to execute Ajax it just closes the FancyBox down. I'm not an expert...
The FancyBox's content is generated using Ajax because it requires data from a database.
Here are the important code parts: (Texts are German...)
The file loaded into the FancyBox using Ajax
<script>
$("#submit").click(function() {
var login = $("#login").val();
$.ajax({
type: "POST",
url: "handleuseredit.php",
cache: false,
data: { login: login },
success: function(data){
if(data=='ok')
{
alert('Richtig.');
}
else
{
alert('Falsche Benutzername/Passwort Kombination.');
}
}
});
});
</script>
<div class="login">
<div class="widget_header">
<h4 class="widget_header_title wwIcon i_16_wysiwyg">Benutzer Bearbeiten</h4>
</div>
<div class="widget_contents lgNoPadding">
<form method="post" id="form-edit">
<p id="errormessagehere"></p>
<div class="line_grid">
<div class="g_3 g_3M"><span class="label">Benutzername</span></div>
<div class="g_9 g_9M">
<input type="text" name="login" id="login" value="<?php echo getusername($_GET['u']) ?>" class="simple_field tooltip" placeholder="Benutzername" autocomplete="off"></div>
<div class="clear"></div>
</div>
<div class="line_grid">
<div class="g_3 g_3M"><span class="label">Passwort</span></div>
<div class="g_9 g_9M">
********
</div>
<div class="clear"></div>
</div>
<div class="line_grid">
<div class="g_6">Abschicken
</div>
<div class="clear"></div>
</div>
</form>
</div>
</div>
Here's how I call the Fancy box
$(document).ready(function() {
$(".fancybox").fancybox({
'scrolling' : 'no',
'padding' : 0,
'titleShow' : false
});
});
handleuseredit.php just echoes "ok" to fullfill the data variable requirement.
You can test something like this with the version 2 of fancybox (http://fancyapps.com/fancybox/):
<script>
$("#submit").click(function() {
var login = $("#login").val();
$.ajax({
type: "POST",
url: "handleuseredit.php",
cache: false,
data: { login: login },
success: function(data){
if(data=='ok')
{
$.fancybox( '<h1>Richtig.</h1>' );
}
else
{
$.fancybox( '<h1>Falsche Benutzername/Passwort Kombination.</h1>' );
}
}
});
});
</script>

Categories