I'm developing a site (only for fun and learn programming with jquery)
and i'd like to know what's wrong with this :
$(window).unload(function(){
var myid = $('input#v1').attr('value'); // hidden
var playauth = $('input#v2').attr('value'); // hidden
var srvid = $('input#v3').attr('value'); // hidden
var result = 'myid='+ myid +'&auth='+ playauth +'&srvid='+ srvid;
$.ajax({
type: "GET",
data: result,
url: "closing.php",
complete: function(data) {
alert(data.responseText);
}
});
});
I'm trying to update a database table. When i close the window nothing happens.
With a previous version of this function :
window.onunload = function () {
var xhReq = new XMLHttpRequest();
var n = document.getElementById("v1").InnerHTML;
var o = document.getElementById("v2").InnerHTML;
var p = document.getElementById("v3").InnerHTML;
xhReq.open("GET", ("closing.php?myid=" + n + "&auth=" + o + "&srvid=" + p) , false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
alert(serverResponse);
};
.. i saw the response alert but GET values were 'undefined'.
.... probably because the type of inputs is hidden..?
This is my form... maybe i miss something ?? I'm really new to jquery/ajax .. please help!!
<form method="get">
<input id="v1" type="hidden" name="val1" class="aget" value="<?php echo $_GET['myid']; ?>" />
<input id="v2" type="hidden" name="val2" class="bget" value="<?php echo $_GET['playauth']; ?>" />
<input id="v3" type="hidden" name="val3" class="cget" value="<?php echo $_SESSION['srvid']; ?>" />
</form>
change
var myid = $('input#v1').attr('value'); // hidden
var playauth = $('input#v2').attr('value'); // hidden
var srvid = $('input#v3').attr('value'); // hidden
to
var myid = $('input#v1').val(); // hidden
var playauth = $('input#v2').val(); // hidden
var srvid = $('input#v3').val(); // hidden
You must use
.val(); instead of .attr('value');
Related
I have list with several inputs
<input type="hidden" id="elevens_id_ea" value="<?php echo $_GET['elev_id']; ?>" />
<input type="hidden" id="arskursen_ea" value="<?php echo $arskursen; ?>" />
<?php
if ($extraanpassning_hamta['atgard'] == true){
?>
<input name="extraanpassning" id="knapp[<?php echo $amnets_id['amne_id']; ?>]" type="button" class="btn-u rounded btn-u-red btn-sm" value="Ja">
<?php } else { ?>
<input name="extraanpassning" id="knapp[<?php echo $amnets_id['amne_id']; ?>]" type="button" class="btn-u rounded btn-u-green btn-sm" value="Nej">
<?php } ?>
The main problem is how to "catch" the value in the two latest inputs with:
id="knapp[<?php echo $amnets_id['amne_id']; ?>]"
If knapp[4] -> how do I get the 4?
The code above is a part of a button that changes value when the user presses it (without refreshing the page).
The JS
<script>
$(document).ready(function(){
$('input[type="button"]').click(function(){
var extraanpassningVal = $(this).attr("value");
var amne_id_ea = $(this).attr("id");
var elevens_id_ea = $("#elevens_id_ea").val(); //värdet av elev_id
var arskursen_ea = $("#arskursen_ea").val(); //värdet av elev_id
$.ajax({
type: "POST",
url: "iup_extraanpassning_byta.php",
data: {extraanpassningType: extraanpassningVal, amne_id_ea: amne_id_ea, elevens_id_ea: elevens_id_ea, arskursen_ea: arskursen_ea},
success: function() {
location.reload();
}
})
});
});
</script>
EDIT:
The main problem is how to get the key from a input with an id like knapp[4].
How do get the key within knapp[]?
Update (thanks to user:SpYk3HH)
<script>
$(document).ready(function(){
$('input[type="button"]').click(function(){
var key = this.id.replace(/knapp|\[|\]/g, ''), // <---They key
extraanpassningVal = $(this).attr("value"),
amne_id_ea = $(this).attr("id"),
elevens_id_ea = $("#elevens_id_ea").val(),
arskursen_ea = $("#arskursen_ea").val();
if (this.ajax) this.ajax.abort(); // helps prevent multiple ajaxing (multiclicking)
this.ajax = $.ajax({
type: "POST",
url: "iup_extraanpassning_byta.php",
data: {extraanpassningType: extraanpassningVal, amne_id_ea: amne_id_ea, elevens_id_ea: elevens_id_ea, arskursen_ea: arskursen_ea},
success: function() {
location.reload();
}
})
})
});
</script>
I think I get it? You want the key when calling the button in JS? So like say: key = this.id.replace(/knapp|\[|\]/g, '')
Update, I didn't see the brackets before
$('input[type="button"]').click(function(){
var key = this.id.replace(/knapp|\[|\]/g, ''), // <---They key
extraanpassningVal = $(this).attr("value"),
amne_id_ea = $(this).attr("id"),
elevens_id_ea = $("#elevens_id_ea").val(),
arskursen_ea = $("#arskursen_ea").val();
if (this.ajx) this.ajx.abort(); // helps prevent multiple ajaxing (multiclicking)
this.ajx = $.ajax({/* options */});
})
Does that help?
FYI, $(this).attr("id") and this.id are the same thing
$('[name=test]').each(function(i) { $('#bob').text(this.id.replace(/knapp|\[|\]/g, '')) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="knapp4" name="test" value='my id is "knapp[4]"' />
<hr />
key: <span id="bob"></span>
Try this.
var amne_id_ea = "knapp[4]",
value = amne_id_ea.substring(amne_id_ea.lastIndexOf("[")+1,amne_id_ea.lastIndexOf("]"));
alert(value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Hope you are expecting this.
I am using the code below using jQuery and AJAX, to update my database.
Deletion works perfectly, but the edit function is not working. How is it possible to get the value from each input field?
<ol class="update">
<?php
$ss = mysql_query ("SELECT * FROM users_channels WHERE u_id='$uid'");
while ($chann = mysql_fetch_assoc($ss)) {
echo'
<li>
<input name="channelName" type="text" id="channelName" style="float:left; width:300px; border:1px solid #CCC;" value="'.$chann['channel_name'].'" />
<span id="rcolor">Delete</span>
<span id="gcolor">Save</span>
</li>';
}
?>
</ol>
Javascript code:
$(document).ready(function() {
$(function() {
$(".save_button").click(function() {
var id = $(this).attr("id");
var cvalue = $(this).attr("cvalue");
var dataStringe = 'id=' + id + '&cvalue=' + cvalue;
var parent = $(this).parent();
alert(cvalue);
$.ajax({
type: "POST",
url: "update_channel.php",
data: dataStringe,
cache: false,
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'}, 300).animate({ opacity: 0.35 }, "slow");
},
success: function() {
//parent.slideUp('slow', function() {$(this).remove();});
}
});
return false;
});
});
});
Add this in your java script function
$(document).ready(function() {
$(function() {
$(".save_button").click(function() {
var inputVal=$("#channelName").val();
//rest of your code
return false;
});
});
});
you'll get the value of an input field(as per your question) in inputVal variable.
In order to get the values of all input fields,give them a common class name instead of giving style there like this
<input class="myInput" type="text" value="red" id="one"/>
<input class="myInput" type="text" value="France" id="two" />
and then in your javascript add this
var inputValues= {};
$(".myInput").each(function() {
inputValues[$(this).attr("id")] = $(this).val();
});
alert(inputValues.one); // "red"
you'll get the value of all input fields in inputValues variable
can u be more explicit? What do you need to get? Value of all input elements? if yes .. use $('input[name=example]').each(function(){})
this will get all values of all input with specified name
I guess what you're trying to do is submit the value of your input field as cvalue? To do this, the best approach would be:
$(".save_button").click(function() {
var id = $(this).attr("id");
var parent = $(this).parent();
var cvalue = parent.find('input').val(); // this gets the value of the <input> field
var dataStringe = 'id='+ id + '&cvalue='+ cvalue;
// the rest of your code...
});
Hi i'm printing out a radio button list dynamically with php using the following code:
<form method="post">
<p>Name of list:
<label for="name"></label>
<input type="text" name="name" id="name">
</p>
<p>Name of item:
<input id="first_name" name="first_name" type="text" />
<br />
<?php echo $form;?>
<input name="myBtn" type="submit" value="Submit Data" onClick="javascript:ajax_post();"></form>
where $form is the variable in which the radio button list is saved.Now i need to pass the selected radio button to an another php file using an ajax function ajax_post().But since my form method is POST my ajax function gets overridden and doesnt get called.
heres my ajax function
function ajax_post(){
var hr = new XMLHttpRequest();
var id = '<?php echo $id; ?>';
var rd = '<?php echo $_POST['radio'];?>';
var url = "my_parse_file.php";
var fn = document.getElementById("first_name").value;
var nm = document.getElementById("name").value;
var vars = "todo="+fn+"&name="+nm+"&id="+id+"&rd="+rd;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars); // Actually execute the request
}
I need it to be POST because i want to extract what radio button i press and i also need the ajax function to work...any way around this?
You need to return false; from your function to avoid the form getting submitted the regular way.
I have following html form:
<form method="post" action="">
<input type="hidden" name="userid" id="user" value="<?php echo $user ?>"/>
<textarea name="comment" class="subcomment_form" id="ctextarea<?php echo $suggestid ?>"></textarea>
<input type="submit" value="Post" id="<?php echo $suggestid ?>" class="form_btn" style="margin-top: 5px"/>
</form>
following JS code:
$('.form_btn').live("click",function()
{
var ID = $(this).attr("id");
var user= $("input[name=userid]").val();
var comment= $("#ctextarea"+ID).val();
var dataString = 'comment='+ comment + '&suggestid=' + ID + 'user' + user;
if(comment=='')
{
alert("Please Enter Comment Text");
}
else
{
$.ajax({
type: "POST",
url: "action/subcomment.php",
data: dataString,
cache: false,
success: function(html){
$("#commentload"+ID).append("html");
$("#ctextarea"+ID).val('');
$("#ctextarea"+ID).focus();
}
});
}
return false;
});
and following php code for subcomment.php file:
if($_POST['comment'])
{
$comment=$_POST['comment'];
$suggestid=$_POST['suggestid'];
$user=$_POST['user'];
$sql = "INSERT INTO user_suggestions_comments (uvd_id, user_id, usc_comment) VALUES ('".$_POST['suggestid']."', '".$_POST['user']."','".$_POST['comment']."')";
mysql_query( $sql);
}
the problem I have is that value from <input type="hidden" name="userid" id="user" value="<?php echo $user ?>"/> is not passed on php file and textarea content is passed. What I need to change inside that JS code to make it work?
It looks like your dataString is not being built to what your PHP code is expecting.
Try this change.
var dataString = 'comment='+ comment + '&suggestid=' + ID + 'user' + user;
becomes
var dataString = 'comment='+ comment + '&suggestid=' + ID + '&user=' + user;
You are looking for three values from your $_POST and only passing 2
$comment=$_POST['comment'];
$suggestid=$_POST['suggestid'];
$user=$_POST['user'];
I want to add a comment system after my article,
php part code
<?php
...
while($result = mysql_fetch_array($resultset))
{
$article_title = $result['article_title'];
...
?>
<form id="postform" class="postform">
<input type="hidden" name="title" id="title" value="<?=$article_title;?>" />
<input type="text" name="content" id="content" />
<input type="button" value="Submit" class="Submit" />
</form>
...
<?php
}
?>
ajax part:
$(function($) {
$(document).ready(function(){
$(".Submit").click(function(){
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
var anyBlank = 0;
if(anyBlank == "0")
{
var title = $("#title").val();
var content = $("#content").val();
$.ajax({
type: "POST",
url: "ajax_post.php",
data: "title="+title+"&content="+content,
success: function(date_added){
if(date_added != 0)
{
structure = '<div class="comment_date_added">'+date_added+'</div><div id="comment_text"><div id="comment_content">'+content+'</div>';
$("#post_comment").prepend(structure);
}
});
});
ajax_post.php
echo $title;
echo $content;//get $title and $content and insert into database.
my question: <form id="postform" class="postform"> is written into a MYSQL_QUERY result circle. how to modify ajax part so that every div.submit can post its own value to ajax_post.php and then return the data into $("#post_comment").prepend(structure); Thanks to all.
You have to give the input fields a class instead of an ID. IDs have to be unique in an HTML document:
<form class="postform">
<input type="hidden" name="title" class="title" value="<?=$article_title;?>" />
<input type="text" name="content" class="content" />
<input type="button" value="Submit" class="Submit" />
</form>
Then you can make the data lookup relative to the clicked element:
var title = $(this).siblings('.title').val();
var content = $(this).siblings('.content').val();
I also suggest to pass an object to the data attribute for automatic URL encoding of the values:
data: {title: title, content: content}
Then, when you create a new entry for the #post_comment section, you have to give these elements also a class instead of an ID (and don't forget to use var!):
var structure = '<div class="comment_date_added">'+date_added+'</div><div class="comment_text"><div class="comment_content">'+content+'</div>';
or more jQuery like:
$('<div />', {class:'comment_data_added'})
.append($('<div />', {class: 'comment_date_added', text: date_added}))
.append($('<div />', {class: 'comment_content', text: content}))
.prependTo('#post_comment');
Further notes:
You have somehow a nested ready() handler:
$(function($) { // <--┐
$(document).ready(function(){ // <--┴- this is the same
//...
});
});
Either do:
jQuery.noConflict();
jQuery(function($) {
$('.Submit')...
)};
or
$(function() {
$('.Submit')...
)};
This part in the click handler:
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
var anyBlank = 0;
does not seem to do anything. Besides that, the submit button has no ID and no name.
Depending on the further structure of your PHP code, you should have a look at the alternative syntax for control structures. It makes easier to mix PHP and HTML without fiddling around with brackets.