After new elements has been injected run JQuery - javascript

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
});

Related

how to upload an image using ajax

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(){
}
});
});

jquery (ajax) click makes php script to run multiple times

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.

Complete Javascript Ajax php confusion

Hi all I am developing a site in Codeigniter and I have a form that I am posting using PHP and this is absolutely fine. However I have a small dropdown on the side of my page which I am using to jump between pages - in order to do this I am simply using a href and passing variables within the URL.
I need to POST some data however when they click on the link. I don't wish to use a button and was wondering whether this could be acheived using an ajax onclick() event?? - the data I need to post however is within the form. The code structure is roughly:
<form action="main/postback" method="post">
<input type="hidden" name="pagereference" value="2" />
<input type="hidden" name="supervariable" value="7" />
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
<div>
<ul>
<li><a href = 'http:localhost/landing'>click me</a></li>
</ul>
</div>
When someone clicks on the link I want to send an Ajax Post request, but In the php file that I am posting the data I want to be able to retrieve data from within the form. Is this possible? if so could someone please provide an example AJAX request and how to retrieve the data in PHP as I am majorly confused. I tried the following:
<li><a onclick='myFunction()'>click me</a></li>
<script type="text/javascript">
function myFunction()
{
var "test";
$.ajax({
type: "POST",
url: "http://localhost/ciproject/assessment/test",
dataType: String,
success: function(msg){
alert( "Data Saved: " + msg ); //Anything you want
}
});
window.alert("TEST");
}
</script>
Any ideas would be much appreciated, many thanks
You will probably run into problems using complete urls (with the domain name) due to CORS so I would recommend removing that, but you can easily do what you want using something like:
<li><a class="postFormLink">click me</a></li>
<script type="text/javascript">
$('.postFormLink').on('click', function() {
$.ajax({
type: "POST",
url: "/ciproject/assessment/test",
data: $('form').serialize(),
success: function(msg){
alert( "Data Saved: " + msg ); //Anything you want
}
});
window.alert("TEST");
}
</script>
If you have more than one form on your page, you should add an ID or a class to target it instead of using $('form').
Note that I have also removed the inline event handler.
Try the following:
<form action="main/postback" method="post" id="form1">
<input type="hidden" name="pagereference" value="2" />
<input type="hidden" name="supervariable" value="7" />
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
<li><a id="clickme">click me</a></li>
<script type="text/javascript">
$(function () {
$("#clickme").click(function () {
var form_data = $('#form1').serialize();
$.ajax({
type: "POST",
dataType: "text",
url: "ciproject/assessment/test",
data: form_data,
success: function(response){
alert('Job well done');
}
})
})
})
</script>
The following should work, if you put it into your ajax options. You will need to identify your form, the easiest way is to use an id.
data: $("#theFormId").serialize()

Stop 2 Instances of an Ajax form on the same page interfering with each other

I've the following form twice on my homepage:
<form id="get-consultation-form" action="javascript:alert('success!');" >
<h3 class="sub-heading">Book a Consultation</h3>
<div id="message"></div>
<div id="fields">
<input type="text" maxlength="" name="Consultation[name]" placeholder="NAME" />
<input type="text" maxlength="" name="Consultation[number]" placeholder="NUMBER" />
<input type="text" maxlength="" name="Consultation[email]" placeholder="EMAIL" />
<button type="submit" class="btn">Submit</button>
</div>
</form>
The form uses jQuery/Ajax/PHP to forward the data via email:
$(document).ready(function() {
$("#get-consultation-form").submit(function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "http://novicecoder.co.uk/priestley/consultation-process.php",
data: str,
success: function(msg) {
$(document).ajaxComplete(function(event, request, settings) {
NProgress.set(0.0);
if (msg === 'OK') {
result = '<div class="thanks" id="thanks">Thank you, we will contact you <span>shortly.</span></div>';
$(this).find("#fields").hide();
NProgress.set(0.5);
$("#message").hide();
$("#message").html(result).slideDown(100);
$("#message").html(result);
}
else
{
result = msg;
$("#message").hide();
$("#message").html(result).slideDown(200);
$("#message").html(result);
}
NProgress.set(1.0);
});
}
});
return false;
});
});
The first form is working perfectly, however as you'll see in my working example, the 2nd is not:
My website
Any ideas why this is happening????
IDs are unique.
Try to change form elements to diferent ids.
Or instead use classes.
If you use classes you can use $('.messages-class').closest() inside the form submit() for only interact in the current form.
You can't have an element with the same ID on a page twice. Replace your #get-consultation-form ID with a class, that should solve your issue. This also applies to the elements within the form like #fields and #message.

Multiple show/hide forms in jquery

Hello I want to have list of files in directory and a form below each of them that allows my users to name them.
That's all clear - I made it in php, but now I want to have this list and hidden forms, and when I'm clicking on one of my file's name, the form shows under the clicked name.
Something like here: http://papermashup.com/demos/jquery-sliding-div/#
Here is the code: http://papermashup.com/simple-jquery-showhide-div/
But it works in a way, that when i click on one of files, all forms shows or all hides. How to fix it to work only for clicked file?
JSFIDDLE EXAMPLE: http://jsfiddle.net/qbNrR/
#UPDATE - SIMILAR PROBLEM
Hey, I've got similar problem with submitting ajax forms - using this tutorial: http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
my forms are in div id=#upform and when i'm trying to submit any of them via $.ajax it submits only the first one, here's the code:
<script>
$(function() {
$(".button").click(function() {
var txt = $(".tekst#test").val();
var dataString = 'tekst=' + tekscior;
$.ajax({
type: "POST",
url: "upload/base",
data: dataString,
success: function() {
$('#upform').html("<div id='message'></div>");
$('#message')
.html("<h2>described!</h2>")
.append("<p>thanks!</p>")
.hide()
.fadeIn(1500, function() {
$('#message')
.append("<img id='checkmark' src='http://artivia-dev2/i/check.png' />");
});
}
});
return false;
});
});​
</script>
AND Here are my forms:
// ONLY THIS ONE IS SUBMITTED, EVEN WHEN I'M SUBMITTING THE SECOND ONE!
<div class="slidingDiv">
<div id="upform">
<form name="contact" action="">
<input type="text" value="TESTFORM" class="tekst" id="test">
<input type="submit" name="submit" class="button" id="submit" value="Send" />
<form>
</div>
<div class="slidingDiv">
<div id="upform">
<form name="contact" action="">
<input type="text" value="TESTFORM" class="tekst" id="test">
<input type="submit" name="submit" class="button" id="submit" value="Send" />
<form>
</div>
You can use the next() jQuery method. Then your code will look something like:
$(document).ready(function() {
$(".slidingDiv").hide();
$(".show_hide").show();
$('.show_hide').click(function(e) {
$(e.target).next(".slidingDiv").slideToggle();
});
});​
Try event.currentTarget to get the form that triggered the click event
on click event use jquery like
$(this).show(); // or hide();
as in example
$('.show_hide').click(function(){
//$(".slidingDiv").slideToggle();
$(this).slideToggle();
});

Categories