I use an Ajax form (with JQuery Validation Plugin) on my site. It works except for the following problem: if I enter something in a text field and then click on the send button, the value is updated. With each next update, however, the old value is always used. I already understand that I may have to work with .on or .keyup, but I understand how to properly integrate it into the code, after the click or outside ...
Update:
I have several fields in the form. Here is simplified code. I also noticed that after the first update of the form, no fields can be updated with newly entered values. All values remain old.
HTML:
<form id="org-684" class="org">
<input class="org-name" type="text" name="name" value="" required>
<button type="submit" class="updateOrg">Update</button>
</form>
JS:
$(document).ready(function(){
$('.updateOrg').click(function() {
var id = $(this).closest(".org").attr("id");
id = id.split('-');
id = id[1];
var org_id_attr = "#org-"+id;
var org_name = $(org_id_attr).find(".org-name").val();
$(org_id_attr).validate({
submitHandler: function() {
$.ajax({
type: "POST",
url: "update.php",
data: ({
id: id,
org_name: org_name
}),
success: function(response){
var result = jQuery.parseJSON(response);
$(org_id_attr).find(".org-name").val(result.name);
},
error: function() {
},
cache: false
});
return false;
}
});
});
})
PHP:
<?php
$orgId = $_POST['id'];
$orgName = $_POST['org_name'];
$select = "
SELECT
name
FROM
org
WHERE
id = $orgId
";
$result = $mysqli->query($select);
$row = $result->fetch_row();
$res = array(
'name' => $row[0]
);
echo json_encode($res);
I solved the problem. You just have to put the variables from the form behind the "SubmitHandler".
$(org_id_attr).validate({
submitHandler: function() {
var org_name = $(org_id_attr).find(".org-name").val();
$.ajax({
type: "POST",
Related
I am creating a update form. In this when i click on update button i got same values every time that's why update functionality is not working. I already tried to get values using ID attribute of input box but not working. I am new in this field and this task take lots of time. Thanks in advance.
$(document).ready(function() {
$(".update").click(function() {
var id = $(this).data('id');
var uname = $(".name1").val();
var email = $(".email1").val();
$.post("operation.php", {
ID: id,
operation: 'update',
name: 'uname',
email: 'uemail'
}, function(data) {
$("#result").html(data);
});
});
});
for($i = 0; $i < $num_of_records; $i++)
{
echo "<tr><td>";
echo "<input type='text' value=".mysql_result($all_records, $i,"name")." class='name1' id='name' placeholder='Name'><input type='text' value=".mysql_result($all_records, $i,"email")." class='email1' id='email' placeholder='Email'><input type='submit' data-id=".mysql_result($all_records, $i,"id")." class='delete' name='delete' id='delete' value='Delete'><input type='submit' data-id=".mysql_result($all_records, $i,"id")." class='update' name='update' id='update' value='Update'>";echo "</td></tr>";
}
The Javascript needs to select the inputs from the same row as the button that was clicked.
$(document).ready(function() {
$(".update").click(function() {
var row = $(this).closest("tr");
var id = $(this).data('id');
var uname = row.find(".name1").val();
var email = row.find(".email1").val();
$.post("operation.php", {
ID: id,
operation: 'update',
name: 'uname',
email: 'uemail'
}, function(data) {
$("#result").html(data);
});
});
});
A better solution do it like this,
I am giving you a small example as your code is bit tidy.
<?php
foreach($answers as $a)
{
?>
<a href="javascript:void(0)" data-answerid="<?php echo $a->id;?>" class="upvote_link" />Edit</a>
<?php
}
?>
jquery Onclick to get clicked value
$('.upvote_link').click(function(){
var unique_id = $(this).data('answerid');
console.log(unique_id);
});
Shoot a comment if you have any issue executing this.You should always write unique id in html elements. Javascript should be knowing that particular link is been clicked.
That's because your ids are same, so jQuery stops searching as soon as it matches the first element with that ID.
To prevent this from happening, use the .siblings() function, like so:
$(document).ready(function() {
$(".update").click(function() {
var id = $(this).data('id');
var uname = $(this).siblings(".name1").val();
var email = $(this).siblings(".email1").val();
$.post("operation.php", {
ID: id,
operation: 'update',
name: 'uname',
email: 'uemail'
}, function(data) {
$("#result").html(data);
});
});
});
I have a website where the log ins are screen names. On the create user form I want to be able to have ajax check if a screen name exists already as it is typed into the form.
This is the HTML form input field
<label for="screenName">Screen Name:
<input type="text" class="form-control" name="screenName" id="screenName" size="28" required>
<div class="screenNameError"></div>
A message should be displayed in the <div class="screenNameError"></div>line if the username matches the database.
This is my Jquery code for this.
$(document).ready(function(){
if ($('#screenName').length > 0){
var screenName = $("input").keyup(function(){
var value = $(this).val();
return value;
})
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
This is the PHP file that gets called to make the DB query
$screenName = $_POST['Screen_Name'];
$screenNameSQL = "SELECT Screen_Name FROM Users WHERE Screen_Name = '$screenName'";
$result = $my_dbhandle->query($screenNameSQL); //Query database
$numResults = $result->num_rows; //Count number of results
$resultCount = intval($numResults);
if($resultCount > 0){
echo "The username entered already exists. Please a different user name.";
}
For some reason my Jquery is not firing when I type the username in the form :/
Thanks in advance
Try changing your jQuery to this -
$(document).ready(function() {
$('#screenName').keyup(function() {
var value = $(this).val();
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
});
});
However you probably want to minimise the number of ajax requests being made so I would advise putting your ajax request into a setTimeout functon and clearing it with each subsequent keypress. -
$(document).ready(function() {
var ajaxRequest;
$('#screenName').keyup(function() {
var value = $(this).val();
clearTimeout(ajaxRequest);
ajaxRequest = setTimeout(function(sn) {
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
}, 500, value);
});
});
if ($('#screenName').length > 0){
You should change it with
if ($('#screenName').val().length > 0){
OR
var name = $('#screenName').val();
if(name.length >0) {...
not sure about the syntax...
Add an event on keyup like this :
Edit
$("#screenName").on("keyup",function(){
var screenName=$(this).val();
if(screenName!='')
{
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
JsFiddle
Your ajax call should be inside the keyup handler.
I know stackoverflow tends to shy away from "wall of text" posts, but I've been at this for about 4 hours and I can't figure it out, so I wanted to give as much information as possible.
I have a page with two input forms on it. Whenever I add text into the first one, the javascript function attached to the second input button runs, and I can't figure out why.
In my header I have two scripts:
<script type="text/javascript" src="/autocomplete/js/script.js"></script>
which contains:
function autocomplet() {
var min_length = 0; // min caracters to display the autocomplete
var keyword = $('#country_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'capoInstantSearch.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#country_list_id').show();
$('#country_list_id').html(data);
}
});
} else {
$('#country_list_id').hide();
}
}
// set_item : this function will be executed when we select an item
function set_item(item) {
// change input value
$('#country_id').val(item);
// hide proposition list
$('#country_list_id').hide();
$("#capoInfo").load("capoSingleReturn.php?q="+encodeURIComponent(item));
}
capoInstantSearch.php looks like this:
<?php
function connect() {
return new PDO('code here to connect'}
$pdo = connect();
$keyword = '%'.$_POST['keyword'].'%';
$sql = "SELECT statement is here....";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
// put in bold the written text
$country_name = str_replace(strtoupper($_POST['keyword']), '<b>'.$_POST['keyword'].'</b>', $rs['quotePartNumber']);
// add new option
echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['quotePartNumber']).'\')">'.$country_name.'</li>';
}
?>
and
<script type="text/javascript" src="/autocomplete/js/script2.js"></script>
which contains:
function compCheck() {
var min_length = 0; // min caracters to display the autocomplete
var bootyTime = $('#comp_id').val();
if (bootyTime.length >= min_length) {
$.ajax({
url: 'capoInstantCompSearch.php',
type: 'POST',
data: {bootyTime:bootyTime},
success:function(data){
$('#comp_list_id').show();
$('#comp_list_id').html(data);
}
});
} else {
$('#comp_list_id').hide();
}
}
// set_item : this function will be executed when we select an item
function set_item(item) {
// change input value
$('#comp_id').val(item);
// hide proposition list
$('#comp_list_id').hide();
$("#compReturn").load("capoCompReturn.php?w="+encodeURIComponent(item));
}
Input Box 1:
<input id="country_id" type="text" placeholder="Enter a Part Number"
onsubmit="this.value=this.value.toUpperCase()" autocomplete="off" onkeyup="autocomplet()">
<ul id="country_list_id"></ul>
Input Box 2:
<input id="comp_id" type="text" onkeypress="this.value=this.value.toUpperCase()"
placeholder="Part Number 2" onkeyup="compCheck()"></h2>
<ul id="comp_list_id"></ul>
Ultimately, the contents of autocomplet() should be placed into this div
<div id="capoInfo" class="capoData"></div>
while the contents of compCheck() should be placed into
<div id="compReturn" class="blueBorder"></div>
When I type text into the first input box, it populates the <ul> country_list_id, and when I make a selection, it populates that answer into second input box on my page, then executes that code. I cannot figure out WHY it is doing this and it's driving me crazy....
It's because you have two functions that are in the global scope called "set_item"
You are defining your functions in the global scope, and the second is overwriting the first. You could solve this by namespacing (for lack of a better term) your functions by sticking them into an object.
For example,
script.js
var country = {
autocomplete: function() {
var min_length = 0; // min caracters to display the autocomplete
var keyword = $('#country_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'capoInstantSearch.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#country_list_id').show();
$('#country_list_id').html(data);
}
});
} else {
$('#country_list_id').hide();
}
},
// set_item : this function will be executed when we select an item
set_item: function(item) {
// change input value
$('#country_id').val(item);
// hide proposition list
$('#country_list_id').hide();
$("#capoInfo").load("capoSingleReturn.php?q="+encodeURIComponent(item));
}
}
script2.js
var comp = {
compCheck: function() {
var min_length = 0; // min caracters to display the autocomplete
var bootyTime = $('#comp_id').val();
if (bootyTime.length >= min_length) {
$.ajax({
url: 'capoInstantCompSearch.php',
type: 'POST',
data: {bootyTime:bootyTime},
success:function(data){
$('#comp_list_id').show();
$('#comp_list_id').html(data);
}
});
} else {
$('#comp_list_id').hide();
}
},
// set_item : this function will be executed when we select an item
set_item: function(item) {
// change input value
$('#comp_id').val(item);
// hide proposition list
$('#comp_list_id').hide();
$("#compReturn").load("capoCompReturn.php?w="+encodeURIComponent(item));
}
}
and then change the references in your HTML to include the namespace, e.g.
input box 1 (note the onkeyup)
<input id="country_id" type="text" placeholder="Enter a Part Number"
onsubmit="this.value=this.value.toUpperCase()" autocomplete="off" onkeyup="country.autocomplete()">
<ul id="country_list_id"></ul>
and then repeat for all the other references, including the one in the PHP code.
You may also want to check out Browserify which brings Node's require module syntax to the browser. Additionally, you might read up on closures and IIFE's in JS.
I've edited this question from the original OP to better represent my issue.
How can I pass the variable data-uid with AJAX ?
Right now the variable doesnt get passed.
var uid = $(this).data("uid"); doesn't work = undefined
var uid = '199'; gets passed. works.
is it possible to have something like : var uid = $uid; ?
HTML
<form>
<fieldset>
<textarea id="post_form" type="text" data-uid="<?php echo $uid ?>"/></textarea>
<button type="submit" id="add" value="Update" name="submit" />OK</button>
</fieldset>
</form>
JS
$(function() {
$("#add").click(function() {
var boxval = $("#post_form").val();
var uid = $(this).data("uid"); // this needs to be changed
var dataString = 'post_form=' + boxval + '&uid=' + uid;
if (boxval == '') {
return false;
} else {
$.ajax({
type: "POST",
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
cache: false,
success: function(html) {
parent.html(html);
}
});
return false;
});
});
problem in your code in:
var uid = $(this).data("uid");
you're trying to wrap this into jquery object, but it is button object in this context, then you're trying to obtain something unassigned from it
you shoud use:
var uid = $('#post_form').attr('data-uid');
or, you can add <input type="hidden" name=... value=... and get id from it, this is more general way
Looks like your issue is with the data attribute that should be data-uid="somevalue" Like.
Check this fiddle to see if this solves your main problem
I have a collapsible part of my jQuery Mobile page that are generated from PHP output from a MS Sql databas and content render as I like it to so that part is ok.
in each section I create a form with 3 buttons and they are supposed to have unique Id:s.
All forms are also created to have a unique id created in runtime.
actions.php (renders out my elements into mobilepage i a DIV)
$counter=0; reset counter for ID:s
while (odbc_fetch_row($rs)){
// data output from Db to make like 10 collapsible with different data
$html = "";
$html = "<div data-role='collapsible-set' data-mini='true'>";
$html.="<div data-role='collapsible' data-mini='true'>";
$html.="<h3><span style=float:left;><img src='../_pic/$image' alt='$imageText' /> ".substr($Time,0,16)." $Area</span><span style='float:right;' class='ui-btn-up-c ui-btn-corner-all' cnt> $data </span></h3>";
$html.="<p>ID: $ID $Id $Status<br />$Status $Description)</p>";
$html.="<form method='post' action=''>";
$html.="<button value='action1' id='action1$counter' data-mini='true' type='Submit'>Take Action1</button>";
$html.="<button value='action2' id='action2$counter' data-mini='true' type='Submit'>Take Action1</button>";
$html.="<button value='action3' id='action3$counter' data-mini='true' type='Submit'>Take Action1</button>";
$html.="<input type='hidden' id='id$counter' name='id' value='$dataName' />";
$html.="</form>";
$html.="</div>";
$html.="</div>";
echo utf8_encode($html);
$counter++; //upcount to make Id:s unique
} //end While
Then I have this function that listens for a button that submit:
$(':submit').live('click', function() {
var button = $(this).val();
if (button == 'action1') {
$.ajax({
url: '../_php/Functions.php',
data: 'button=' + $(this).val()+'&id='+$('#id').val(),
async: true,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
error: function (request,error) {
alert('error');
}
});
}
return false;
});
I cant seem to get another id than the first one since i need to make all ID:s unique in my forms and all I do now is to check: &id='+$('#id').val(). what I would like to have done is to link the button pressed-id number to my hidden field id-number so i get the right data out from it. As of now I only get the first form:s id evaluated...
If someone could point me in the right direction how to make that happen i´d be greatful.
functions.php (a switch statement is pre-testing for submit:ed action
function actions1(){
try {
if(isset($_GET['id'])){
do stuff with 'id'
}else{
do other stuff with 'id'
}
} catch(Exception $e) {
show error
}
}
If some part is unclear or if you feel I missed posting somepart - let me know. /thanks
Within event handlers this referes to the element
$(':submit').live('click', function(){
var id= this.id;
var button = $(this).val();
/* traverse within form to set hidden input, no need to worry about using ID's for them*/
$(this).closest('form').find('input[name=id]').val(id);
/* then in ajax */
data: 'button=' +button+'&id='+id,
})
Not full code....I left some of your code out for simplicity
You can use jQuery .attr() function to get an id or any other attribute value of an element.
$(':submit').live('click', function() {
var button = $(this).val();
var id = $(this).attr("id");
if (button == 'action1') {
$.ajax({
url: '../_php/Functions.php',
data: 'button=' + $(this).val()+'&id='+ id,
async: true,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
error: function (request,error) {
alert('error');
}
});
}
return false;
});
The solution was to go by attributes name of my hidden input.
var id = $(this).closest("form").find(':hidden').val();