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.
Related
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",
I am trying to create an AJAX function to autocomplete the input field.
The user starts typing in location/city name, and it should trigger an AJAX call for lookup, presenting suggestions of matching city names list to the input field. Then the user selects one value and that is set to that input field. The below code doesn't even trigger events, I do not see request activity on the network. How to accomplish this?
$(function() {
$('#locationName').keyup(function() { //tried keyup, input
alert('Ok'); // to test event
$.ajax({
type: 'POST',
url: '/locationsearch',
data: {
'search_text': $('#locationName').val()
},
success: searchSuccess,
dataType: 'text'
});
});
});
function searchSuccess(data) {
locationName.val = 'data';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="locationName" id="locationName">
Your example does not seem complete. It's not clear where locationName is defined. Consider the following snippet.
$(function() {
function searchLoc(txt) {
var result = "";
$.post("/locationsarch", {
"search_text": txt
}, function(data) {
result = data;
});
return result;
}
$('#locationName').keyup(function() {
var q = $(this).val();
if (q.length >= 3) {
$(this).val(searchLoc(q));
}
});
});
It's not clear what the resulting data will be, I am assuming text or HTML.
I have a dropdown on my page,which selected value I take like this:
<select id="campaign" class="form-control">
<option>Choose campaign</option>
<option value="createCampaign">Create new campaign</option>
<?php while($row=$resultForCampaigns->fetch_assoc()){
$campaignName=$row['campaign_name'];
echo "<option value=$campaignName>$campaignName</option>";
}?>
</select>
var campaign = $('#campaign option:selected').val();
But when I'm passing that same campaign value as a argument of new function, and do console.log(campaign) it says:
Here is the whole code:
$(document).ready(function() {
$('#campaign').change(function() {
var campaign = $('#campaign option:selected').val();
console.log(campaign);
if (campaign != 'Choose campaign') {
console.log(campaign);
$('#deleteCampaign').click(function(campaign) {
console.log(campaign);
var r = confirm("Are you absolutely sure you want to delete selected campaign?");
if (r == true) {
var data = {};
data.action2 = "deleteCampaign";
data.campaign = campaign;
$.ajax({
url: "../includes/adapter.php",
type: "POST",
dataType: "JSON",
data: data,
async: true,
success: function() {
if (data) {
console.log(data);
$('#poruka').append('<div class="alert alert-success"><strong>Success!</strong> You have successfully deleted campaign!</div>');
} else {
$('#poruka').append('<div class="alert alert-danger"><strong>Failure!</strong> Something went wrong with deleting your campaign! Please try again</div>');
}
}
});
}
});
}
});
});
So, console.log(campaign) after click on $('#deleteCampaign') turns value of campaign from one that I've gave it, to one that picture represents. Really don't know what's going on, so If anyone could explain me how to get correct value inside function that is tiggered by click, I would be very thankful.
The variable campaign is redefined when you use the same name as a function argument in a lower scope.
Variables are scoped to functions, and function arguments are considered variables, it would be the same as doing
var something = 'stuff';
function go() {
something = 'other stuff';
console.log(something); // obviously "other stuff"
}
The first argument for the click function in jQuery is the event object, you can't pass in anything else.
All you have to do is just remove the argument.
var campaign = $('#campaign option:selected').val();
$('#deleteCampaign').click(function() {
console.log(campaign); // still the value
I have created a quiz page named quiz.php. It contains javascipt which calculates the correct answers of the user (amountCorrect variable). I want to insert this variable to mySql db via scorepage.php but my code doesn't work. Any help ???
Here is the part of javascript
function show_score() {
var amountCorrect = 0;
...
if(radio.value == "right" && radio.checked) {
amountCorrect++;
}
}
alert("Correct " + amountCorrect + " out of 6");
$.ajax({
type: "POST",
url: "http://localhost/Istoselida/scorepage.php",
data: "score1=" + amountCorrect,
success: function () {
$('ul#posts').prepend(wall_post);
}
});
}
And here is the part of the scorepage.php
include('db2.php');
$member_id=$_SESSION['member_id'];
$result=mysql_query("select * from studentstable where id='$member_id'")or die(mysql_error);
$row=mysql_fetch_array($result);
$score1 = mysql_real_escape_string($_POST['score1']);
$sql=mysql_query("UPDATE studentstable SET Varscore1 ='$score1' WHERE id= $row");
You're trying to pass $row in the UPDATE statement. $row is an array, not a value. Try:
$sql = mysql_query("UPDATE studentstable SET Varscore1 ='$score1' WHERE id= $row[id]");
put row id $row['filedname']
$sql=mysql_query("UPDATE studentstable SET Varscore1 ='$score1' WHERE id= ".$row['id']);
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();