I'm having a button, and when is clicked, it renders (with the help of ajax), the content of a php script (basically it's a contact form). My problem is that when the button is clicked, this calls the php script twice or more times. I've tried many solutions, but none worked.
HTML
<ul class="nav navbar-nav navbar-right">
<li>CONTACT</li>
</ul>
JavaScript
$(document).ready(function(){
$('#contact').off();
// the above line I've replaced it with:
// 1. $('#contact').off('click');
// 2. $('#contact').unbind();
// 3. $('#contact').unbind('click');
$('#contact').click(function(e){
$.ajax({
type: "POST",
url: "contact.php",
success: function(html){
$('#content').html(html);
}
});
e.preventDefault();
});
});
The response I get when I run the page which contains the HTML and JS:
The contact.php receives the data send with ajax (from index.php - the page which contains the above code), and then sends the new contact to another php script (which is a class), who stores the new contact in the database, and gives back (to contact.php) a response.
contact.php
<form id="form">
<div class="form-group col-xs-12 col-md-4">
<input type="text" class="form-control" id="nume" value="<?php echo Escape::esc($nume);?>" style="pointer-events:none;background:#EFEFEF;"/>
</div>
<div class="col-xs-12"></div>
<div class="form-group col-xs-12 col-md-4">
<input type="text" class="form-control" id="prenume" value="<?php echo Escape::esc($prenume);?>" style="pointer-events:none;background:#EFEFEF;"/>
</div>
<div class="col-xs-12"></div>
<div class="form-group col-xs-12 col-md-10">
<textarea class="form-control" id="mesaj" rows="20" data-toggle="mesaj" data-placement="bottom" title="Va rog introduceti mesajul dvs."></textarea>
</div>
<div class="col-xs-12"></div>
<div style="clear:both"></div>
<button class="btn btn-default" onclick="return validate();" style="margin-left:15px;">TRIMITE</button>
</form>
<script type="text/javascript">
function validate(){
var nume = $('#nume').val();
var prenume = $('#prenume').val();
var mesaj = $('#mesaj').val().trim();
if (mesaj == '' || mesaj.length < 3){
$(function(){
$('[data-toggle="mesaj"]').tooltip();
document.getElementById('mesaj').focus();
});
return false;
}
$('#form').off();// here I tried to unbind all the previous submit events too
$('#form').on('submit',function(e){
$.ajax({
type: "POST",
url: "../../app/classes/Contact.php",
data: {nume:nume, prenume:prenume, mesaj:mesaj},
success: function(html){
$('#content').html(html);
}
});
e.preventDefault();
});
}
</script>
Any tip is welcomed! Thank you!
From what I understand, JavaScript does not execute functions sequentially by nature. In your first jQuery snippet it looks like your code assumes that it will first unbind any events bound to $('#contact') and then create a new binding, but that's not necessarily true.
Also, the off() command only works if you bound the event to the element using a corresponding on() command, but your code uses click() instead of on().
You may want to try something like this instead:
$(document).ready(function(){
$('#contact').on('click', function(e){
$.ajax({
type: "POST",
url: "contact.php",
success: function(html){
$('#content').html(html);
}
});
e.preventDefault();
});
});
Using $('#contact').on('click', function(e) ... will allow you to call $('#contact').off() after the e.preventDefault(); if you want to try to use that to troubleshoot the double-posting problem.
I'm not sure that will fix your issue, but hopefully it's a step in the right direction.
Related
I want to upload an image without refreshing the page,But my page still refresh when i hit submit button to upload image. what is wrong with my ajax code. This works when am submitting form with plain text but not with image file.
test.php
<div class="preview_d_p" id="preview_d_p">
<div class="preview">
<div class="p_preview">
<div id="p_p_image"><div id="myimage"></div></div>
</div>
<div id="lab"> <label for="photo_upload">upload</label></div>
<form enctype="multipart/form-data">
<input type="file" id="photo_upload" name="image_upload">
<input type="submit" value="save" id="insert_img" onclick="return loadimage()">
</form>
</div></div>
<script>
function loadimage(){
var image = documentElement('photo_upload').value;
$.ajax({
type:'post',
url:'profile.php',
data:{
image:image
},
cache:false,
success: function(html){
}
});
return false;
}
</script>
my advice is changing the input to a button (type="button") - I prefer buttons to inputs as they're more easily stylable.
But you can do something like this to govern submitting data without page refresh:
HTML EXAMPLE (NOT A COPY OF YOUR HTML):
<div id="container">
<form action="" method="post" id="myForm">
<input type="text" value="hello world!" />
</form>
<!-- what's great about buttons, is that you don't have to place inside the form tags -->
<button type="button" id="submitBtn">
JS To match
$(document).ready(function()
{
$('#submitBtn').on('click', function()
{
//ajaxy stuff
//will show the success callback function though:
success: function(res)
{
$('#container').html(res);
}
})
});
if your post script returns html then this should work. Let me know if otherwise :)
I solved this problem using formdata to send my image file to server
$(document).on("submit","form",function(e){
e.preventDefault();
var file = $("#product-file-i").val();
var p = $("#product-upload-f").children("input[name=name]").val();
$.ajax({
type:"post",
url:"profile.php",
data:new FormData(this),
contentType:false,
processData:false,
cache:false,
success: function(feedback){
alert(feedback);
},
error: function(){
}
});
});
Form :
<form method="post" id="loginForm">
<div class="form-group">
<label for="email-signin">Email address:</label>
<input type="email" class="form-control" id="email-signin" name="email-signin">
</div>
<div class="form-group">
<label for="pwd-signin">Password:</label>
<input type="password" class="form-control" id="pwd-signin" name="pwd-signin">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default" id="signIn" name="signIn">Sign In</button>
<div id="error">
<!-- error will be shown here ! -->
</div>
</form>
jquery :
$("#signIn").on("click", function(e) {
e.preventDefault();
var values = $("#loginForm").serialize();
console.log( values );
$.ajax({
type: "POST",
url: "../php/BusinessLayer/User.php",
data: values,
beforeSend: function() { $("#error").fadeOut() },
success : function(response)
{
console.log("Success");
if(response=="ok"){
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> '+response+' !</div>');
});
}
}
});
php:
<?php
session_start();
include ("../DataLayer/VO/UserVO.php");
include ("../DataLayer/DAO/UserDAO.php");
// Database Execution for User Related Request
$userDAO = new UserDAO();
print_r($_POST);
if(isset($_POST['signIn']))
{
echo 'test2';
$user = new UserVO();
$user->setEmail(trim($_POST['email-signin']));
$user->setPassword(trim($_POST['pwd-signin']));
// Request signin
$userDAO->signIn($user);
}
Using this code, my if(isset($_REQUEST['signIn'])) in my php file never returns true. I have tried multiple things, and nothing seems to work.
PS : I am using Jquery 1.12.4
Also, my print_r($_POST); returns an empty Array.
jQuery's serialize function does not encode the values of buttons. Taken from here
NOTE: This answer was originally posted by slashingweapon
jQuery's serialize() is pretty explicit about NOT encoding buttons or submit inputs, because they aren't considered to be "successful controls". This is because the serialize() method has no way of knowing what button (if any!) was clicked.
I managed to get around the problem by catching the button click, serializing the form, and then tacking on the encoded name and value of the clicked button to the result.
$("button.positive").click(function (evt) {
evt.preventDefault();
var button = $(evt.target);
var result = button.parents('form').serialize()
+ '&'
+ encodeURIComponent(button.attr('name'))
+ '='
+ encodeURIComponent(button.attr('value'))
;
console.log(result);
});
As far as the var dump being empty on the PHP side, try using jQuery's .click instead of the .on event.
$('#signIn').click(function(){});
Also, remove the method from your form. It looks like the form may be submitting as soon as you click the button. Also, remove
e.preventDefault();
and place
return false;
at the VERY END of the on click function. return false does 3 things
e.preventDefault()
e.stopPropigation();
return immdediatly
In my page there are several DIVs, which are supposed to show different news items depending on the user selection and a press of a submit button.
Am I able to refresh only a single DIV when the relevant submit button is clicked?
I tried <input type ="button"> instead of <input type="submit"> but that didn't work as expected. My code is below:
<div class="dloader"></div>
<div class="search">
<form action="" method="post">
Furniture:
<input type="text" name="val1" id="val1" value="<?=$_POST['val1']?>" />
<input type="submit" value="Submit" name="submit" />
</form>
</div>
<?php
if( isset($_POST['submit']) ){
$postItemHeader = htmlentities($_POST['val1']);
}?>
<script>
$(window).load(function() {
$(".dloader").fadeOut("slow");
})
</script>
Take One Button For Post Event
<input type="submit" id="add" name="add" />
If You want to pass the Text Data, so a text value from the Text to fetch the particular data
<div id="result">Result should appear here</div>
Use Javascript To POst The Text Data To Back End
$(document.ready(function() {
$("#add").click(function(e) {
e.preventDefault();
$.ajax({
url: 'test.php',
type: 'POST',
data: $('#add').val,
success: function(data, status) {
$("#result").html(data)
}
});
});
});
What you need is AJAX. (read the documentation). A simple example is here.
The HTML
<div id="target_div"></div> <!-- Here is where you gonna place your new content -->
<input type='button' id='trigger' onClick="get_new_data()" value="Get new Content"> <!-- When this button is pressed get new content -->
The Javascript
function get_new_data()
{
$.ajax(
{
type: POST,
url: "you-url-here.php",
dataType:"HTML", // May be HTML or JSON as your wish
success: function(data)
{
$('div#target_div').html(data) // The server's response is now placed inside your target div
},
error: function()
{
alert("Failed to get data.");
}
}); // Ajax close
return false; // So the button click does not refresh the page
} // Function end
I been looking for the way to do this since yesterday, I have a <div class="list"> where I append some element using PHP
HTML:
<div id="list"></div>
<input type="button" value="Populate" onClick="populate();">
Javascript
function populate(){
var url = 'http://mylink.com/edit.php?region_name='+region_name;
$.ajax({
type: "GET",
url: url,
success:function(results){
$('#list').html(results);
}
});
}
Then my generated HTML after running clicking on the button is;
<div id="list">
<label>region</label>
<br>
<div class="edit">
<input class="num" type="text" value="east" readonly="">
</div>
</div>
As it is not in a right structure, I want to run a JQuery after the elements has been populated
var length = $('.edit').length;
for(var a = 0; a <= length - 1; a++){
$('.edit:eq('+ a +')').find('input').appendTo($('label:eq('+ a +')'));
Fiddle sample here.
And BTW, I tried to bind it with DOMSubTreeModified
$("#List").bind("DOMSubtreeModified", function() {
//My JQuery
});
But still no result.
Try this one
call your js function in done block
$.ajax({
url: "test.html",
}).done(function() {
//your jquery method
});
i have a main form on my main page, the form get an email address from the user and check if the email exist.
My target is to show the results on the same page with bootstrap collapse.
I am using this code in the javascript side:
$(".emailCheckForm").bind("submit", function () {
return $.ajax({
type: "POST",
width: "auto",
height: "auto",
padding: 10,
cache: !1,
url: "_/php/checkemail.php",
data: $(this).serializeArray(),
success: function (t) {
$(".res").append(t).collapse();
},beforeSend: function(){
$( "#message" ).empty();
}
}), !1
}),
my html code:
<form action="" method="post" class="col-md-8 centered emailCheckForm">
<div class="input-group">
<input type="email" name="email" class="form-control checkFrame" placeholder="you#youremail.com">
<div class="input-group-btn">
<input type="submit" value="answer me!" class="btn btn-default checkFrame" tabindex="-1" />
</div>
</div><!-- /.input-group -->
</form>
<div class="res"></div>
Now this working but the problem is that if i want to check another email i get the same results until i will refresh the page.
So i want to implement a before send function that will remove\empty the div results.
I cant make this happen because that every time that i insert the beforsesend function the post not working, any suggestions to make proccess like that in the right way?
How about this one. On every successful callback it will clean up results from previous request and re-populate latest:
...
success: function (t) {
$(".res").empty().append(t).collapse();
}
...