I am working on a project where for example field number 3 on the webpage should be updated with values from a database when a user enters data into field number 1. This already works fine without any problems.
But if the user modifies field number 3 first and field number 1 at a later time, just the DOM gets updated (as I can tell from Firebug) but there isn't any visible change on field number 3 to the user.
I created a very basic version of this problem and still I am not able to tell what's wrong here.
HTML
<div id="container1">
<textarea id="container1.1">Entry 1.1</textarea>
<textarea id="container1.2">Entry 1.2</textarea>
<textarea id="container1.3">Entry 1.3</textarea>
</div>
jQuery
$(document).ready(function() {
$('textarea').change(function() {
var clickedObject = $(this);
var id = $(this).attr('id').substr(9);
var value = $(this).val();
var dataString = "id=" + id + "&value=" + value;
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
cache: false,
success: function(Result)
{
if(Result == '-')
{
console.log('Nothing to do');
} else {
clickedObject.next().next().html(Result);
}
}
});
});
});
PHP
<?php
if ($_POST['id'] == '1.1') {
echo 'Modified string';
} else {
echo '-';
}
?>
You must set values of textarea by .val() method, instead of html().
And maybe it will be more descriptive if you will use only one id of textarea that should call request on changes.
Related
How to pass a variable value from html page using javascript to php?
i created this code in my index.php
$amount = $_GET['pricenumb'];
echo $amount;
and this is my javascript code to call on click of button and send the data to the PHP file.
<script type="text/javascript">
$(".cell").on("click", "input:checkbox", function () {
var thiss = $(this);
var total = $("#price");
var target = $("label[for='" + thiss.attr("id") + "']");
var item_value = +(target.html().replace(/[^0-9\.]/g, "") || 0);
var cur_total = +(total.html().replace("$", "") || 0);
if (thiss.prop("checked") === true) {
cur_total += item_value;
} else {
cur_total -= item_value;
};
total.text("$" + cur_total);
});
</script>
<script type="text/javascript">
$("#pay_btn").on("click", function () {
var price = $("#price").text();
var pricenumb = price.replace(/[^0-9\.]/g, "");
$.ajax({
type: "POST",
url: "forumdisplay.php?fid=2",
data: "price=" + price + "pricenumb="+ pricenumb,
cache:false,
success: function(){
}
});
});
</script>
and this is the checkbox,
<div class="cell">
<div class="form-check"><label for="check-a" class="form-check-label"><input id="check-a" class="form-check-input" type="checkbox">$166<span class="form-check-sign"></span></label>
<div class="mask visible-on-sidebar-regular">Buy Product</div>
</div>
</div>
the work code is, when I check the checkbox, it will update the div content, and I want when I click on pay button, get the div value via javascript and send the value to my index.php
You are using POST in your ajax and GET in php, chage your ajax to GET. Also, In your ajax change
type: "POST",
url: "forumdisplay.php?fid=2",
data: "price=" + price + "pricenumb="+ pricenumb,
to
type: "GET",
url: "forumdisplay.php",
data: {
price: price,
pricenumb: pricenumb,
fid: 2
}
That's not how you pass data in ajax. The correct format is to use curly braces and define props name and then value
data:{propName1: value1,propsName2: value2,propsName3: "Some string value"}
Which can be used in the file like this in case of POST request.
$_POST['propName1'] which will give value1 variable data as a result
$_POST['propName3'] which will give output as Some string value string
The value can be in quotes if it's a string or not in quotes if it's a variable. So you need to redefine your ajax data props to
$.ajax({
type: "POST",
url: "forumdisplay.php?fid=2",
data: {price: price ,pricenumb: pricenumb},
cache:false,
success: function(response){
// Things to do on success
},
error: function(error){
// Error handling in case of error
}
});
These values you passed can be used in the file forumdisplay.php with $_POST['price'] and $_POST['pricenumb']. The name inside the $_POST is the propsName inside data props in ajax function.
I have dropdown list of country suggestions and input above. When i click on one of them - AJAX should work(and it does) and add value to #msg_native. HTML:
echo '<div class="search_native"><input type="text" name="native_input" id="native"/>';
echo "<div id='output'></div></div>";
All JQUERY :
<script type="text/javascript">
$(document).ready(function() {
$("input").keyup(function(){
$array = ['usa','france','germany'];
$input_val = $("input[name='native_input']").val();
$('#output').text('')
r = new RegExp($input_val)
for (i = 0; i < $array.length; i++) {
if ($array[i].match(r)) {
$('#output').append('<p class="match">' + $array[i] + '</p>')
}
}
});
$(document).on('click', '.match', function(){
$value = $(this).text();
$('#native').val($value);
});
});
</script>
<script type="text/javascript">
$(function() {
$('#native').change(function() {
alert('cl');
$.ajax({
type: "POST",
url: "home.php",
dataType: 'json',
encode: true,
data: {native_input: $("input[name='native_input']").val()},
cache: false,
success: function(data){
alert(data);
$("#msg_native").after(data);
}});
return false;
});
});
</script>
The problem is that the value that gets posted is only what Ive typed myself, regardless on clicked element. But I want complete value- not only typed letters...so it firstly posts value and then 'finishes' the input (if clicked)
What can you practically advice to me?
data: {native_input: $value},
returns empty string
Some of this might be debatable but I put those in place for maintainability of the code and/or to match the most recent jQuery.
Only use one document ready handler (if possible)
Remove all the global objects (put var in front of them)
Use the native id when possible as fastest selector (not $("input[name='native_input']") for instance)
use this in the event handler, not the full selector (see next item)
If I enter "France" not "france" match does not work so need to case that input to equality var $input_val = $(this).val().toLowerCase();
You start with an empty field, might be good to show the match for that - simply trigger the keyup on startup to show all the array: }).trigger('keyup'); Now they are available for your clicking.
Attach the click handler on the wrapper for the "match" elements: $('#output').on('click', '.match', function() {
Use the promise form of the ajax .done(
Create a new custom event instead of the "change" on the native. We can then trigger that event as/when needed (the real issue you describe) Example: $('#native').trigger('myMatch'); and as I use it here:
trigger the event on a full match:
if (jQuery.inArray($input_val, $array) !== -1) {
$(this).trigger('myMatch');
}
Revised code:
$(document).ready(function() {
$("#native").on('keyup', function() {
var $array = ['usa', 'france', 'germany'];
var $input_val = $(this).val().toLowerCase();
$('#output').html('');
var r = new RegExp($input_val);
for (var i = 0; i < $array.length; i++) {
if ($array[i].match(r)) {
$('#output').append('<p class="match">' + $array[i] + '</p>');
}
}
// full match entered, trigger the match
if (jQuery.inArray($input_val, $array) !== -1) {
$(this).trigger('myMatch');
}
}).on('myMatch', function() {
alert('cl');
var nativeMatch = {
native_input: $("#native").val()
};
$.ajax({
type: "POST",
url: "home.php",
dataType: 'json',
encode: true,
data: nativeMatch,
cache: false
}).done(function(data) {
alert(data);
$("#msg_native").after(data);
});
return false;
}).trigger('keyup');
$('#output').on('click', '.match', function() {
var $value = $(this).text();
$('#native').val($value).trigger('myMatch');
});
});
Assume I have 2 textbox, that's serial_no10 and serial_no12. That 2 textbox appear not simultaneously depends on case
1 PHP file for checking the SN.
1 DIV status to display the data.
jQuery Ajax
var serial_no10 = $("#serial_no10").val();
var serial_no12 = $("#serial_no12").val();
$.ajax(
{
type: "POST",
url: "chk_dvd_part_no.php",
data: 'serial_no10='+ serial_no10 +'&serial_no12='+ serial_no12,
success: function(msg)
{
$("#status").ajaxComplete(function(event, request, settings)
{
}
}
}
HTML
<div id="status"></div>
PHP File
if(!empty($_POST['serial_no12']))
{
echo "Serial No 12";
}
else if(!empty($_POST['serial_no10']))
{
echo "Serial No 10";
}
Now I'm facing the problem when get POST from textbox serial_no_12, the value is undefined. But if get POST from textbox serial_no_10, I got the value.
Is that something wrong with that PHP code? Or I do something that should not be.
You have to just empty the variables before filling up. As if value is not reset then last value computed would remain in variavar
serial_no10 = $("#serial_no10").val();
var serial_no12 = $("#serial_no12").val();ble
change it with
var serial_no10='';
var serial_no12='';
serial_no10 = $("#serial_no10").val();
serial_no12 = $("#serial_no12").val();
Noww do things it will all good
Give your form tag an id if it has no anyone. and than do something like this.
var form = $("#form_id").serialize();
$.ajax({
type: "POST",
url: "chk_dvd_part_no.php",
data: form,
success:function(msg)
{
$("#status").ajaxComplete(function(event, request, settings)
{
//do your stuff
});
}
});
and in php file get your post variable by its name, suppose you have 2 inputs name serial_no10 and serial_no12
now do your php code like this.
if( isset($_POST['serial_no10']) && $_POST['serial_no10'] != '' ){
echo 'Serial No 10';
}
if( isset($_POST['serial_no12']) && $_POST['serial_no12'] != '' ){
echo 'Serial No 12';
}
I have two ajax calls on a page. There are text inputs for searching or for returning a result.
The page has several non ajax inputs and the ajax text input is within this . Whenever I hit enter -- to return the ajax call the form submits and refreshes the page prematurely. How do I prevent the ajax from submitting the form when enter is pressed on these inputs? It should just get the results.
However, I cannot do the jquery key press because it needs to run the ajax even if the user tabs to another field. Basically I need this to not submit the full form on the page before the user can even get the ajax results. I read return false would fix this but it has not.
Here is the javascript:
<script type="text/javascript">
$(function() {
$("[id^='product-search']").change(function() {
var myClass = $(this).attr("class");
// getting the value that user typed
var searchString = $("#product-search" + myClass).val();
// forming the queryString
var data = 'productSearch='+ searchString + '&formID=' + myClass;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "<?php echo $path ?>ajax/product_search.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results" + myClass).html('');
$("#searchresults" + myClass).show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results" + myClass).show();
$("#results" + myClass).append(html);
}
});
}
return false;
});
$("[id^='inventory-ESN-']").change(function() {
var arr = [<?php
$j = 1;
foreach($checkESNArray as $value){
echo "'$value'";
if(count($checkESNArray) != $j)
echo ", ";
$j++;
}
?>];
var carrier = $(this).attr("class");
var idVersion = $(this).attr("id");
if($.inArray(carrier,arr) > -1) {
// getting the value that user typed
var checkESN = $("#inventory-ESN-" + idVersion).val();
// forming the queryString
var data = 'checkESN='+ checkESN + '&carrier=' + carrier;
// if checkESN is not empty
if(checkESN) {
// ajax call
$.ajax({
type: "POST",
url: "<?php echo $path ?>ajax/checkESN.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#esnResults" + idVersion).html('');
},
success: function(html){ // this happens after we get results
$("#esnResults" + idVersion).show();
$("#esnResults" + idVersion).append(html);
}
});
}
}
return false;
});
});
</script>
I would suggest you to bind that ajax call to the submit event of the form and return false at the end, this will prevent triggering default submit function by the browser and only your ajax call will be executed.
UPDATE
I don't know the structure of your HTML, so I will add just a dummy example to make it clear. Let's say we have some form (I guess you have such a form, which submission you tries to prevent)
HTML:
<form id="myForm">
<input id="searchQuery" name="search" />
</form>
JavaScript:
$("#myForm").submit({
// this will preform necessary ajax call and other stuff
productSearch(); // I would suggest also to remove that functionality from
// change event listener and make a separate function to avoid duplicating code
return false;
});
this code will run every time when the form is trying to be submitted (especially when user hits Enter key in the input), will perform necessary ajax call and will return false preventing in that way the for submission.
I'm hoping someone can help, I'm a relative newbie to javascript and have the following issue. I have a select box with id "mySelect"
that is populated with the following code -
$(document).ready(function(artists){
$.ajax({
type: "GET",
url: "bookinglist.xml",
dataType: "xml",
success: function(artists_list) {
var select = $('#mySelect');
var artistsArr = [];
$(artists_list).find('vw_ADM_BookingListNull[strArtistName]').each(function(){
var artists = $(this).attr('strArtistName');
if ($.inArray(artists, artistsArr) == -1) {
select.append('<option value="'+artists+'">'+artists+'</option>');
artistsArr.push(artists);
}
});
select.children(":first").text("please make a selection").attr("selected",true);
}
});
});
I need to use the selected value as a variable to insert into another piece of code. How do I make a variable from this?
The variable will be used in place of
'vw_ADM_BookingListNull[strArtistName="James Zabiela"]'
in the following code which populates a table from an xml list.
$(document).ready(function(unavailable){
$.ajax({
type: "GET",
url: "bookinglist.xml",
dataType: "xml",
success:(function(unavail){
$(unavail).find('vw_ADM_BookingListNull[strArtistName="James Zabiela"]').each(function() {
var venue = $(this).attr('strVenueName');
var artist = $(this).attr('strArtistName');
var booking_date = $(this).attr('dteEventDate').substr(0,10); //subtr strips date down
if(!(booking_date >= $nowformat && booking_date <= $advformat)){
$('<tr style="display:none;"></tr>')
}
else {
$('<tr></tr>').html('<th>'+booking_date+'</th><td>'+artist+'</td>').appendTo('#unavail');
}
});
})
});
});
I need to handle the possible event that a value has not been selected and so the value of the select box will be "please make a selection", which is set as the default value.
So I guess I need to wrap some kind of if statement around the code that creates the table, so as to not display anything if nothing has yet been selected.
Any help would be massively appreciated as deadlines are looming.
Thanks again.
You appear to be using jQuery, so from the jQuery Documentation
var dropdownValue = $('#mySelect').val();