How to alert success message in modal form? - php

I'm new to ajax/jquery. I want to use sweetalert on my website, i set it up as in tutorial, but when i open modal form and click send button, it goes to another page, page send.php.
Here my form:
<form id="contactForm1" action="send.php" method="post">
<div class="field-block">
<label for="text">Message1</label>
<textarea id="message1" class="field" required name="message1" rows="4" placeholder=""></textarea>
</div>
<div class="field-block">
<label for="text">Message2</label>
<textarea id="message2" class="field" required name="message2" rows="4" placeholder=""></textarea>
</div>
<div class="field-block">
<label for="text">Message3</label>
<textarea id="message3" class="field" required name="message3" rows="4" placeholder=""></textarea>
</div>
<button id="button" class="button" type="submit">Отправить</button>
<div class="result">
<span id="answer"></span>
<span id="loader"><img src="images/loader.gif" alt=""></span>
</div>
</form>
inside this form sweetalert doesn't work, but outside of form it's working.
Here sweetalert jquery and ajax request:
<script>
$("#contactForm1").on('submit',function(event) {
event.preventDefault(); // to prevent default page reloading
var dataString = $(this).serialize(); // to get the form data
$.ajax({
type: "POST",
url: "send.php",
data: dataString,
success: function(data){
$('#contactForm1')[0].reset(); // to reset form data
}
}).done(function(data){
setTimeout(function () {
Swal.fire(
'Thank you!',
'Your request has been accepted!',
)
}, 2000);
});
});
</script>
what could be the problem? Please help

The problem is you're not sending request with AJAX.
Solution:
First remove action="send.php" from your form
then add this to your script.
<script>
$('.button').click(function(){
swal({
title:"Red Stapler",
text: "Are You Sure?",
buttons: {
cancel: true,
confirm: "Submit"
}
}).then((value) => {
<!-- When the user click submit send Ajax request -->
$.ajax({
url: "send.php",
method: "POST",
data:{
message1: $(#message1).val(),
message2: $(#message2).val(),
message3: $(#message3).val()
},
success: function(data)
{
// some actions
}
});
});
});
</script>

You can send it without ajax request also try this change
$('.button').click(function(){
to
function submitForm(){
your function will look like this:
function submitForm(){
swal({
title:"Red Stapler",
text: "Are You Sure?",
buttons: {
cancel: true,
confirm: "Submit"
}
});
}
Now in the form add
onsubmit="return submitForm()"

swal({ title: "Done", text: "Record updated successfully!", type: "success" }, function () {location.reload();});
Simply use this line code, it will automatically hide alert and reload the page when click "OK".

Related

success message in popup div without refreshing page

I want to display text message for success in popup div without refreshing the page
My popup form like this
<div class="modal-content">
<div id="message">Your message has been sent.<br /><br /></div>
<form action="<?php echo $_SERVER['REQUEST_URI'];?>" id="CallBackForm" name="CallBackForm" method="post">
<div class="form-group">
<input id="custmobileNo" name="custmobileNo" type="text" required="required">
<input type="submit" value="call" id="callback" name="callback" class="btn btn-info">
</div>
</form>
</div>
When I click on this link pop up will call
<a href="#" data-toggle="modal" data-target="#call-back">
<input type="submit" value="Call" class="btn-d btn-doctor" >
</a>
CSS:
<style type="text/css">
#message {
display:none;
font-size:15px;
font-weight:bold;
color:#333333;
}
</style>
Ajax Call:
<script>
$("#callback").click(function () {
var custmobileNo = $("#custmobileNo").val();
$.ajax({
url: "<?php echo base_url('Call'); ?>",
type: 'post',
data: {custmobileNo: custmobileNo},
beforeSend: function () {
if (custmobileNo != "") {
$("#message").fadeIn(); //show confirmation message
$("#CallBackForm")[0].reset(); //reset fields
}
}
});
});
</script>
I wrote beforeSend function() with some data either it was standard code or not I don't know. It was calling message fine but it was not closing I want it will close with in some seconds and click on again that button success message validation was showing I want clear that text also.
Try something like this maybe :
$.ajax({
url: "<?php echo base_url('Call'); ?>",
type: 'post',
data: {custmobileNo: custmobileNo},
beforeSend: function () {
if (custmobileNo != "") {
$("#message").fadeIn(); //show confirmation message
$("#CallBackForm")[0].reset(); //reset fields
}
},
success: function() {
setTimeout(function() { //hide message after a certain time
$("#message").fadeout();
}, 5000); // choose after how many time message should hide, here 5s
}
});
But if your Ajax call fail you won't go in the success part so becareful !
You can do the same with complete : function() {...} instead of success : function() {...}, here is some information about Ajax event : https://api.jquery.com/Ajax_Events/
Is it what you are looking for?

Sending Multiple data to PHP page without reloading page

Please I am new to jQuery so i just copied the code:
<div id="container">
<input type="text" id="name" placeholder="Type here and press Enter">
</div>
<div id="result"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "action.php",
data: {name: info},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
};
});
});
</script>
And here is the php code:
<?php
if (isset($_POST['name'])) {
echo '<h1>'.$_POST['name'];
}
?>
Its Working perfectly but now i want to have more than one input field like this:
<input type="text" id="name" >
<input type="text" id="job">
but i don't know how to run the jQuery code for the 2 input fields so that it can transfer them to the php page. Please i need help
You can pass multiple values using data param of ajax request like this.
$.ajax({
method: "POST",
url: "action.php",
data: {
name: $('#name').val(),
job: $('#job').val()
},
success: function(status) {
$('#result').append(status);
$('#name, #job').val(''); // Reset value of both fields
}
});
You need to change your code with some addition in html and JS.
Wrap your inputs in form tag. and add a preventDefault on submit.
Use jQuery .serialize() method
and event.preventDefault()
event.preventDefault() : If this method is called, the default
action of the event will not be triggered. (it will prevent page
reload / redirection) to any page.
.serialize() : Encode a set of form elements as a string for
submission.
serialized string output will be like key=value pair with & separated. :
name=john&job=developer.....
HTML
<form id="myform">
<input type="text" id="name" placeholder="Type here and press submit">
<input type="text" id="job" placeholder="Type here and press submit">
<input type="submit" name="submit" value="Submit Form">
</form>
JS
$(document).ready(function() {
$('#myform').submit(function(event) {
event.preventDefault();
var serialized = $('#myform').serialize();
$.ajax({
method: "POST",
url: "action.php",
data: serialized,
success: function(status) {
$('#result').append(status);
$('#myform').reset();
}
});
});
});

Ajax POSTs data inspite of false Twitter bootstrap form validation

I am trying to submit a form and send the data to my php function with Ajax. The problem is that, When I send data without ajax call and just using form action, My form validation works, but when I want to use Ajax, Form will be submitted without being validated. Here is my code:
html:
<form novalidate="" class="form-horizontal">
<div class="control-group">
<label for="email" class="control-label">Email address</label>
<div class="controls">
<input type="email" required="" id="email" name="email">
<p class="help-block">Email address we can contact you on</p>
</div>
</div>
<div class="control-group">
<label for="emailAgain" class="control-label">Email again</label>
<div class="controls">
<input type="email" name="emailAgain" id="emailAgain" data-validation-matches-message="Must match email address entered above" data-validation-matches-match="email">
<p class="help-block">And again, to check for speeling miskates</p>
</div>
</div>
<button id="button" class="button" type="submit" name="submit">Check your
</form>
Ajax:
$(document).ready(function () {
$(function () {
$("#button").click(function () {
$('.error').hide();
// Process form
var email = $("input#email").val();
var emailagain= $("input#emailagain").val();
var dataString = 'email=' + email + '&emailagain=' + emailagain;
$.ajax({
type: "POST",
url: "send_email.php",
data: dataString,
success: function (data) {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("Thank you ")
});
}
});
return false;
});
});
});
I also tried submitHandler: function(form){} with Ajax call, but in that case, my success function in Ajax call won't work and it seems that the data will be sent through GET method instead of POST! weird!!! Thanks in advanced!
Ok you have a submit button and on clicking this you are doing some ajax, so you need to use event.preventDefault()
Here how the code should be and it should work, also check for any syntax error in your code. Below is the code I just tested and worked on my linux box.
<script>
$(document).ready(function () {
$(function () {
$("#button").click(function (x) {
x.preventDefault(); // lets stop the default behaviour which is submit
$('.error').hide();
// Process form
var email = $("input#email").val();
var emailagain= $("input#emailagain").val();
var dataString = 'email=' + email + '&emailagain=' + emailagain;
$.ajax({
type: "POST",
url: "send_email.php",
data: dataString,
success: function (data) {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("Thank you ");
}
});
});
return false;
});
});
</script>

CodeIgniter and AJAX form submit

I am trying to save data submitted from a form into my mysql database and and then update the div element with the last posted item prepended to the list in the div.
Right now I am only trying to get a response back, I'm not worried about having the formatting correct at the moment.
My problem is the form won't submit with e.preventDefault(); in place, but without it the form does the normal method of posting to the db then refreshing the page.
Here is my AJAX call:
$(document).ready(function() {
$('form#feedInput').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: $('.feed-input').val(),
dataType: "html",
success: function(data){
debugger;
$('#feed-container').prepend(data);
},
error: function() { alert("Error posting feed."); }
});
});
});
I don't think it's necessary for me to post my controller code, seeing as how my issue is the form won't make it past the e.preventDefault(); function.
How can I get this form to submit via AJAX if the e.preventDefault() function is stopping it before it can reach the $.ajax() function?
The data attribute of the ajax call is invalid. It should be either in JSON format { key: $('.feed-input').val() } or in query format 'key='+$('.feed-input').val().
Also there is an unnecessary debugger variable in the success method.
A working code could be:
$('form#feedInput').submit(function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: form.serialize(), // <--- THIS IS THE CHANGE
dataType: "html",
success: function(data){
$('#feed-container').prepend(data);
},
error: function() { alert("Error posting feed."); }
});
});
Html part in view
<form id="comment" method="post">
<h2>Enter Your Details</h2>
<center><div id="result"></div></center>
<div class="form_fld">
<label>Name</label>
<input type="text" placeholder="Enter Your Full Name" name="name" required="">
</div>
<div class="form_fld">
<label>Email ID</label>
<input type="text" placeholder="Enter Email ID" name="email" required="">
</div>
<div class="form_fld">
<label>Contact Number</label>
<input type="text" placeholder="Enter Contact Number" name="contact" required="">
</div>
<div class="form_fld">
<label>Developer</label>
<select name="developer">
<option>Lotus</option>
<option>Ekta</option>
<option>Proviso</option>
<option>Dosti</option>
<option>All</option>
</select>
</div>
<div class="form_fld">
<button type="submit" id="send">Submit</button>
</div>
</form>
After Html Part Just put ajax request
<script type="text/javascript" src="<?php echo base_url('assets/'); ?>js/jquery.js"></script>
<script>
$(function(){
$("#comment").submit(function(){
dataString = $("#comment").serialize();
$.ajax({
type: "POST",
url: "home/contact",
data: dataString,
success: function(data){
// alert('Successful!');
$("#result").html('Successfully updated record!');
$("#result").addClass("alert alert-success");
}
});
return false; //stop the actual form post !important!
});
});
</script>
Within Controller
public function contact()
{
$ip = $_SERVER['REMOTE_ADDR'];
$data = array('name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'number' => $this->input->post('contact'),
'developer' => $this->input->post('developer'),
'ip' => $ip,
'date' => date("d/m/Y"));
$result = $this->User_model->contact($data);
print_r($result);
}
You don't have to use preventDefault(); you can use return false; in the end of function submit() but I doubt this is the problem.
You should also use url encoding on $('.feed-input').val() use encodeURIComponent for this.
You should also check if you have errors in your console.
To determine if default action is prevented you can use e.isDefaultPrevented(). By default action in this case I mean submit action of the form with id feedInput.
You didn't name your param in data. Check jquery ajax examples.
You are probably getting an error e.preventDefault(); is not stopping the ajax.
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: $("#form").serializeArray(),
success: function(resp){
$('#container').html(resp);
},
error: function(resp) { alert(JSON.stringify(resp)); }
});

jQuery making a post request and retrieving result

So I have a test input and a submit button. I want to send the data via jQuery and retrieve the result from the post request and then display the value that the post request returns, without refreshing the page.
Here is my html:
<div id="middle">
<form id="searchForm" action="/">
<input placeholder="E.g. http://www.google.co.nz" id="url" type="text" name="forward_to"/>
<input id="button" type="submit" name="shorten" value="Go"/>
</form>
<div id="result"></div>
</div>
Here is my php
if($query) {
print("<div id='content'>http://www.website.co.nz/u/$short</div>");
} else {
print("<div id='content'>Error</div>");
}
Is there anyway to do this?
$(document).ready(function(){
$('#button').click(function(e){
e.preventDefault();
$.ajax({
type: 'post',
url: '/',
data: { query: $('#url').val() },
success: function(data) {
$("#result").html(data);
},
error: function() {
$("#result").html("Some error occurred.");
}
});
});
});

Categories