I couldn't find a solution for the following problem I'm having. I'm using some javascript code to make my (live) search work (via ajax). The problem is that the Javascript only works when I place it below the HTML:
<form action="filter.php" name="filter" method="get" id="filter">
<input type="text" id="search_bar" name="s" placeholder="Type hier je zoekterm..." />
</form>
<ul id="result"></ul>
Javascript
$("#filter").submit(function(event) {
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
$.ajax({
url: "tracks_content.php",
type: "get",
data: values,
success: function(data){
$('#result').html(data);
},
});
});
$(this).mouseup(function() {
document.getElementById('result').style.display='none';
});
$("#result").mouseup(function(){
return false;
});
$("#filter").bind('input',(function(event){
var query = document.getElementById('search_bar').value;
if(query!=""){
$("#filter").submit();
document.getElementById('result').style.display='block';
}
else{
$('#result').html('');
document.getElementById('result').style.display='none';
}
}));
How can I make it work when putting the Javascript in front of the HTML?
This is because you are referring to HTML that doesn't exist yet when the JavaScript is on top.
Wrap your code in $( document ).ready(). Thi smakes the browser wait until the DOM is loaded before firing the JavScript.
$( document ).ready(function() {
$("#filter").submit(function(event) {
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
$.ajax({
url: "tracks_content.php",
type: "get",
data: values,
success: function(data){
$('#result').html(data);
},
});
});
$(this).mouseup(function() {
document.getElementById('result').style.display='none';
});
$("#result").mouseup(function(){
return false;
});
$("#filter").bind('input',(function(event){
var query = document.getElementById('search_bar').value;
if(query!=""){
$("#filter").submit();
document.getElementById('result').style.display='block';
}
else{
$('#result').html('');
document.getElementById('result').style.display='none';
}
}));
});
FYI, why are you uisng document.getElementById() when you have jQuery available to you and are already using it?
If you put that before the HTML, then you are trying to add a submit event to a form which doesn't exist at the time the JavaScript runs.
Wrap the script in a function, then use that function as an event handler for the ready or load event.
Passing a function (instead of a selector, DOM element or strong of HTML) as the argument to jQuery will bind as the ready handler.
jQuery(bind_form_event_handler);
function bind_form_event_handler() {
$("#filter").submit(function(event) {
// etc etc
}
Change you javascript to this
wrap with $(function(){}
like this
$(function(){
$("#filter").submit(function(event) {
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
$.ajax({
url: "tracks_content.php",
type: "get",
data: values,
success: function(data){
$('#result').html(data);
},
});
});
$(this).mouseup(function() {
document.getElementById('result').style.display='none';
});
$("#result").mouseup(function(){
return false;
});
$("#filter").bind('input',(function(event){
var query = document.getElementById('search_bar').value;
if(query!=""){
$("#filter").submit();
document.getElementById('result').style.display='block';
}
else{
$('#result').html('');
document.getElementById('result').style.display='none';
}
}));
})
Related
I have a form that I'm trying to submit via ajax and I'm having some issues that I don't understand.
So I have the following function defined at the top of my main.js:
function formSubmit() {
var valid = true;
$(this).find('input, select, textarea').each(function(index, el) {
if(valid)
{
if($(el).is(':hidden'))
{
$(el).removeAttr('required');
}
if(!el.checkValidity())
{
valid = false;
//el.focus();
}
}
});
if (!valid)
return; // not ready to submit
var options = {
url: document.location.origin + 'update.php',
type: 'post',
dataType: 'json',
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
error: showError // post-submit callback
};
// bind form using 'ajaxForm'
$(this).ajaxSubmit(options);
};
Later in my main.js I have the following line that is run when I click a button:
$('#contact-form').formSubmit();
Also in my main.js I have:
$('body').on('change', '#contact-form', formSubmit);
In my HTML:
<form name="contact" id="contact-form">
<input type="text" name="name" value="" required>
<input type="hidden" name="page" value="contact">
</form>
When I run the $('#contact-form').formSubmit(); line, I get the error:
Uncaught TypeError: $(...).formSubmit is not a function
However, when I simply edit the name field (triggering the "on change" line) it updates and runs the function just fine.
What am I missing?
EDIT: It looks like the outcome I'm looking for is not apparent, probably because I'm not super familiar with javascript.
What I was trying to do was have a button that ran the formSubmit() function such that the $(this) element in that function was the form element.
I thought I could just run $('#contact-form').formSubmit() to do that but apparently not?
How would I go about running the formSubmit() function such that $(this) in that function refers to the element with an id of '#contact-form'?
Replace
$('#contact-form').formSubmit();
With
$('#contact-form').submit();
https://api.jquery.com/submit/
Try on submit.
$('#contact-form').submit(function(){
}
Since you are using jQuery, try something like this:
+function ($) {
$.fn.formSubmit = function() {
var valid = true;
$(this).find('input, select, textarea').each(function(index, el) {
if(valid)
{
if($(el).is(':hidden'))
{
$(el).removeAttr('required');
}
if(!el.checkValidity())
{
valid = false;
//el.focus();
}
}
});
if (!valid)
return this; // not ready to submit
var options = {
url: document.location.origin + 'update.php',
type: 'post',
dataType: 'json',
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
error: showError // post-submit callback
};
// bind form using 'ajaxForm'
$(this).ajaxSubmit(options);
return this;
}
}(jQuery);
That way, you should be able to use it like this: $("#contact-form").formSubmit();
So I'm trying to send the form info to php with ajax form every second, but for some reason it doesn't want to.
Here is my latest attempt, I tried every other similar combination(like put everything in the function or just put everything into the setInterval).
$(document).ready(function() {
var ajaxCall=function() {
$("#myForm").ajaxForm(function(e) {
$.ajax({
type:'post',
url:'php1.php',
data:$("#myForm").serialize(),
success:function(data) {
document.getElementById("result").innerHTML=data;
}
});
});
}
setInterval(ajaxCall,1000);
});
EDIT
Solved with M.M answer, thank you for the help!
Simply change ajaxForm to ajaxSubmit
See this (question) and this (documentation) for more information on AjaxForm vs AjaxSubmit
Essentially AjaxForm submits when the user clicks the button and AjaxSubmit does it immediately so your code should be:
$(document).ready(function()
{
var ajaxCall=function()
{
$("#myForm").ajaxSubmit(function(e)
{
$.ajax(
{
type:'post',
url:'php1.php',
data:$("#myForm").serialize(),
success:function(data)
{
document.getElementById("result").innerHTML=data;
}
});
});
}
setInterval(ajaxCall,1000);
});
Update after comment explanation
$(document).ready(function(){
//live feed
var ajaxCall=function(){
$("#myForm").ajaxSubmit(function(e){
ajax_submit();
});
}
setInterval(ajaxCall,1000);
//real submit
$("#myForm").ajaxForm(function(e){
ajax_submit();
});
function ajax_submit(){//ajax_code
$.ajax({
type:'post',
url:'php1.php',
data:$("#myForm").serialize(),
success:function(data) {
document.getElementById("result").innerHTML=data;
}
});
}
});
If you wish to differentiate the feed from the submit you can pass a parameter to the ajax_submit function
Getting rid of the ajaxForm() call seems to accomplish what you are trying to do:
$(document).ready(function() {
var ajaxCall = function() {
$.ajax({
type: 'post',
url: 'php1.php',
data: $("#myForm").serialize(),
success: function(data) {
document.getElementById("result").innerHTML = data;
}
});
}
setInterval(ajaxCall, 1000);
});
I want to do is when a user type an email to the inputbox ajax will pass the value automatically to php.
My problem is the result only show if I try to refresh the page
html:
<input type="text" id="email" name="email" />
script:
$(document).ready(function(){
var countTimerEmailName = setInterval(
function ()
{
emailName();
}, 500);
var data = {};
data.email = $('#email').val();
function emailName(){
$.ajax({
type: "POST",
url:"Oppa/view/emailName.php",
data: data,
cache: false,
dataType:"JSON",
success: function (result) {
$("#imageLink").val(result.user_image);
$("#profileImage").attr('src', result.user_image);
$("#emailNameResult").html(result.user_lname);
$("#emailCodeResult").val(result.user_code);
}
});
};
});
You can try with:
Because you dont need declare function in ready() and you need yo get the email value after any change. Now you only get the value when the page is ready.
function emailName( email ){
$.ajax({
type: "POST",
url:"Oppa/view/emailName.php",
data: 'email=,+email,
cache: false,
dataType:"JSON",
success: function (result) {
$("#imageLink").val(result.user_image);
$("#profileImage").attr('src', result.user_image);
$("#emailNameResult").html(result.user_lname);
$("#emailCodeResult").val(result.user_code);
}
});
};
$(document).ready(function(){
$('#email').change(function(e) {
emailName( this.val());
});
});
You're handling it wrong. jQuery has particular events to do these things.
Take this for example:
$(document).ready(function(){
$(document).on('keyup', '#email', function(e) {
e.preventDefault();
val = $(this).val();
console.log("Value: " + val);
});
});
It will look what is in the below input field as the user types. (which is what I presume you're trying to do?)
<input type="text" id="email" name="email" />
Example
You could simply remove that console.log() and replace it with your ajax request. (The above example will run as the user types.)
Alternatively you could use change() like this:
$(document).ready(function(){
$(document).on('change', '#email', function(e) {
e.preventDefault();
val = $(this).val();
console.log("Value: " + val);
});
});
Which will run after the value of the text box has changed. (When the user clicks out of the text box or moves somewhere else on the page.)
Example
I'm making hover card on click for every users so i did for one and its working but i want this to work on every user like i have given them unique title and based on that the server will get the data of that particular users but the problem is this is working on only 1 links not for all the links...maybe its because var data is kept store (please correct me if i'm wrong) so i tried to do this on ajax cache: false but didn't help then i tried return false;, return data; still not use.
So, here is the users links example :
<a class="hover" title="user101" href="#">John</a>
<a class="hover" title="user102" href="#">Tonya</a>
Ajax :
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
$('.hover').click(function () {
var get_val = $('.hover').attr('title');
var data = 'vall=' + get_val + '';
$.ajax({
type: 'POST',
url: 'xx.php',
data: data,
success: function (data) {
box.dialog({
message: data
});
return false;
}
});
});
});
I would do it this way.
HTML
<div class='links'>
<a title="user101" href="#">John</a>
<a title="user102" href="#">Tonya</a>
</div>
JS
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
$('.links').on('click', 'a', function (event) {
event.preventDefault();
var get_val = $(this).prop('title');
$.ajax({
type: 'POST',
url: 'xx.php',
data: {vall: get_val},
success: function (data) {
box.dialog({
message: data
});
}
});
});
});
the problem is this is working on only 1 links not for all the links...maybe its because var data is kept store (please correct me if i'm wrong)
you are wrong.. only 1 links is working beacuse you have same id for multiple elements.. each elements should have unique id.
use class instead
<a class="hover" title="user101" href="#">John</a>
<a class="hover" title="user102" href="#">Tonya</a>
and a class selector and return false after ajax success callback function , at the end
$('.hover').click(function () {
var get_val = $('.hover').attr('title');
....
$.ajax({
....
success:function(){
....
}
});
return false;
..
or simply use preventDefault() instead of return false
$('.hover').click(function (e) {
e.preventDefault();
var get_val = $('.hover').attr('title');
.....
i have a problem in a dynamic table, adding new line work perfectly but remove line not.
this is my code:
<script type="text/javascript">
$(document).ready(function(){
$(document).on("click", ".trash", function(e){
e.preventDefault();
var $ligneParent = $(this).parent().parent();
trash($ligneParent);
});
});
function trash(aLigneToTrash) {
if (confirm("Vous allez supprimer définitivement cette ligne !")) {
var maincourante = $('table td.textemc').html();
var data = 'maincourante=' + maincourante;
console.log(maincourante);
$.ajax({
type: "POST",
url: "form/delete/deletemc.php",
data: data,
cache: false,
success: function() {
aLigneToTrash.fadeOut('slow', function() {
aLigneToTrash.remove();
});
}
});
return false;
}
}
</script>
my problem is the variable "maincourante" who return the first entry all the time.
this variable should return the value of the line i want to delete.
this is my new line code:
var nouvelle_ligne = $('<tr><td class="thtime">'+hours+'h'+minutes+'</td><td class="textemc">'+texte+'</td><td class="button"><button><i class="icon-pencil"></i></button></td><td class="button"><button class="trash"><i class="icon-trash"></i></button></td></tr>').fadeIn('fast');
$('#tablemc').append(nouvelle_ligne);
It's a bit hard to tell without seeing the actual DOM, but you don't ever actually remove this:
aLigneToTrash
I think you probably want to do:
var data = 'maincourante=' + aLigneToTrash.html();
$('table td.textemc').html() will always select the first td.textemc in the DOM (this is just how jQuery works).
thanks for your help.
i try this:
function trash(aLigneToTrash) {
if (confirm("Vous allez supprimer définitivement cette ligne !")) {
var data = 'maincourante=' + aLigneToTrash.html();
console.log(data);
$.ajax({
type: "POST",
url: "form/delete/deletemc.php",
data: data,
cache: false,
success: function() {
aLigneToTrash.fadeOut('slow', function() {
aLigneToTrash.remove();
});
}
});
return false;
}
}
and console.log return to me :
maincourante=<td class="thtime">09h28</td><td class="textemc">ryhjzreyjryjryjr54654</td><td class="button"><button><i class="icon-pencil"></i></button></td><td class="button"><button class="trash"><i class="icon-trash"></i></button></td>
i want the value of the "td class="textemc" like this maincourante=ryhjzreyjryjryjr54654
i will do this and this work perfectly
var data = 'maincourante=' + aLigneToTrash.children('.textemc').html();
thanks again for your help
try updating your ajax call to this:
....
$.ajax({
type: "POST",
url: "form/delete/deletemc.php",
data: data,
cache: false,
success: function() {
aLigneToTrash.fadeOut('slow', function() {
aLigneToTrash.remove();
$('#tablemc').append(' ');/*add a space to let browser know that there is a change*/
});
}
});
return false;
}
}
</script>
I had similar issue so it seems browsers (esp. IE ) dont detect much of changes on tables so; this hack worked for me. I hope it does to you. (assuming #tablemc is the base table)