short description
I'm using jquery, jqueryUI and ajax.
I use val() to get value from a field the first time it does it perfectly
but if I change the value in the field the value stay the same.
Long descriptionn
I'm developing a big project I have ~2 years on this project
My head is pumping! ;)
I have something like this :
this is the html for the div :
<div id="add_task_diag" style="display: none">
<label for="task">Task : </label><input id="taskfrm" label="Task" value="task" name="taskval" placeholder="e.g fill in tax form" />
<button value="submit" class="btn btn-large add_task_frm">Add task</button> <button class="btn btn-large cancel_add_task">Cancel</button>
</div>
<button class="btn btn-primary" id="add_task"><i class="icon-file icon-white"></i> Add Todo</button>
this is the script :
<script>
$(".add_task_frm").click(function() {
function taskgen() {
var data = "task=" + $("#taskfrm").val();
alert(data); // only for debuging
var task_data = data;
alert(task_data); // only for debuging
$.post("whereitneedtogo.php?task=action80", task_data), //this is the ajax part
$("#add_task_diag").dialog("destroy"); // I had here close I changed it to "destroy"
task_data = undefined; //I tried to unset the variable
}
taskgen();
});
</script>
When I run it everything work fine! when I resend with another value the variable stays the same. e.g if I put test123 in the field in the seccond test it will stay test123
I need to reload the page to reset the variable.
I don't want to use location.reload()
this file is 1700+ lines long but this is the part where the problem is.
I tried alot of things like :
- setting my script after Dom is ready
- setting my variables to undefined or null
- destroy the jquery tabs
- the only part seems to be working for me is location.reload but my application is full ajax.
Thank for helping I hope this is stupid or easy one .
Why are you trying to declare and call the function every time you click.. Try moving it outside the click event handler..
<script>
$(".add_task_frm").click(function() {
taskgen();
});
function taskgen() {
var data = "task=" + $("#taskfrm").val();
alert(data); // only for debuging
var task_data = data;
alert(task_data); // only for debuging
$.post("whereitneedtogo.php?task=action80", task_data), //this is the ajax part
$("#add_task_diag").dialog("destroy"); // I had here close I changed it to "destroy"
task_data = undefined; //I tried to unset the variable
}
</script>
You might also encounter scoping issues when you want to call the taskgen() from some other place..
It's because you define your closure inside the click handler. Move the taskgen function outside of the click handler, wrap everything in $(document).ready() and you should be good to go! See below:
$(document).ready(function() {
$(".add_task_frm").click(function() {
taskgen();
});
function taskgen() {
var data = "task=" + $("#taskfrm").val();
alert(data); // only for debuging
var task_data = data;
alert(task_data); // only for debuging
$.post("whereitneedtogo.php?task=action80", task_data), //this is the ajax part
$("#add_task_diag").dialog("close").dialog("destroy"); // I usually chain 'close' and 'destroy'
}
});
Related
I am working on the Jquery A href (used as Button) with button name Install. I've wrote the code for the calling Jquery AJAX file , Ajax file name is update.php.
Once ajax successfully executed , I'm changing a href label using.
$(.install-blue).text('Stop Installing');
Now , I am trying to call updateStop.php. When i click on the Stop Installing (a href).
Issue is both are sharing same class name, so that it calling update.php
Is there any unique way to execute this operation ?
You could use HTML 5 data attribute to save the state like for example : jsfiddle
Html
<a class="install-blue" data-state="stopped">Start Installing</a>
<div id="msg">
</div>
Jquery
$(document).ready(function(){
$(".install-blue").click(function(){
if($(".install-blue").data("state") == "stopped"){
$(".install-blue").text("Stop Installing");
$(".install-blue").data("state", "started");
}
else{
$(".install-blue").text("Start Installing");
$(".install-blue").data("state", "stopped");
}
});
});
Use:
$('.install-blue').addClass('fistClass');
When the user clicks on install.
Then use:
$('.firstClass').text('Stop Installing');
When the user click on stop installing.
Fiddle
HTML
<input type="button" href="update.php" value="Install" class="install-blue" />
jQuery
$('.install-blue').click(function(){
var url=$(this).attr('href');
alert(url); ///call this ajax url
$(this).val('Stop Installing'); // add this on ajax success
$(this).attr('href','updateStop.php'); // add this on ajax success
});
I am not sure if this example is what you want to do.
$(document).ready(function(){
$('.selector').click(function(e){
e.preventDefault();
if($(this).text() == 'Stop Installing'){
//DO STOP ISTALLING STUFF
}else{
//DO INSTALL STUFF
$(this).text('Stop Installing');
}
});
});
Ok, so I've gotten most of this thing done.. Now comes, for me, the hard part. This is untreaded territory for me.
How do I update my mysql database, with form data, without having the page refresh? I presume you use AJAX and\or Jquery to do this- but I don't quite grasp the examples being given.
Can anybody please tell me how to perform this task within this context?
So this is my form:
<form name="checklist" id="checklist" class="checklist">
<?php // Loop through query results
while($row = mysql_fetch_array($result))
{
$entry = $row['Entry'];
$CID = $row['CID'];
$checked =$row['Checked'];
// echo $CID;
echo "<input type=\"text\" value=\"$entry\" name=\"textfield$CID;\" id=\"textfield$CID;\" onchange=\"showUser(this.value)\" />";
echo "<input type=\"checkbox\" value=\"\" name=\"checkbox$CID;\" id=\"checkbox$CID;\" value=\"$checked\"".(($checked == '1')? ' checked="checked"' : '')." />";
echo "<br>";
}
?>
<div id="dynamicInput"></div>
<input type="submit" id="checklistSubmit" name="checklistSubmit" class="checklist-submit"> <input type="button" id="CompleteAll" name="CompleteAll" value="Check All" onclick="javascript:checkAll('checklist', true);"><input type="button" id="UncheckAll" name="UncheckAll" value="Uncheck All" onclick="javascript:checkAll('checklist', false);">
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');"></form>
It is populated from the database based on the users session_id, however if the user wants to create a new list item (or is a new visitor period) he can click the button "Add another text input" and a new form element will generate.
All updates to the database need to be done through AJAX\JQUERY and not through a post which will refresh the page.
I really need help on this one. Getting my head around this kind of... Updating method kind of hurts!
Thanks.
You will need to catch the click of the button. And make sure you stop propagation.
$('checklistSubmit').click(function(e) {
$(e).stopPropagation();
$.post({
url: 'checklist.php'
data: $('#checklist').serialize(),
dataType: 'html'
success: function(data, status, jqXHR) {
$('div.successmessage').html(data);
//your success callback function
}
error: function() {
//your error callback function
}
});
});
That's just something I worked up off the top of my head. Should give you the basic idea. I'd be happy to elaborate more if need be.
Check out jQuery's documentation of $.post for all the nitty gritty details.
http://api.jquery.com/jQuery.post/
Edit:
I changed it to use jquery's serialize method. Forgot about it originally.
More Elaboration:
Basically when the submit button is clicked it will call the function specified. You want to do a stop propagation so that the form will not submit by bubbling up the DOM and doing a normal submit.
The $.post is a shorthand version of $.ajax({ type: 'post'});
So all you do is specify the url you want to post to, pass the form data and in php it will come in just like any other request. So then you process the POST data, save your changes in the database or whatever else and send back JSON data as I have it specified. You could also send back HTML or XML. jQuery's documentation shows the possible datatypes.
In your success function will get back data as the first parameter. So whatever you specified as the data type coming back you simply use it how you need to. So let's say you wanted to return some html as a success message. All you would need to do is take the data in the success function and place it where you wanted to in the DOM with .append() or something like that.
Clear as mud?
You need two scripts here: one that runs the AJAX (better to use a framework, jQuery is one of the easiest for me) and a PHP script that gets the Post data and does the database update.
I'm not going to give you a full source (because this is not the place for that), but a guide. In jQuery you can do something like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { // DOM is ready
$("form#checklist").submit(function(evt) {
evt.preventDefault(); // Avoid the "submit" to work, we'll do this manually
var data = new Array();
var dynamicInputs = $("input,select", $(this)); // All inputs and selects in the scope of "$(this)" (the form)
dynamicInputs.each(function() {
// Here "$(this)" is every input and select
var object_name = $(this).attr('name');
var object_value = $(this).attr('value');
data[object_name] = object_value; // Add to an associative array
});
// Now data is fully populated, now we can send it to the PHP
// Documentation: http://api.jquery.com/jQuery.post/
$.post("http://localhost/script.php", data, function(response) {
alert('The PHP returned: ' + response);
});
});
});
</script>
Then take the values from $_POST in PHP (or any other webserver scripting engine) and do your thing to update the DB. Change the URL and the data array to your needs.
Remember that data can be like this: { input1 : value1, input2 : value2 } and the PHP will get something like $_POST['input1'] = value1 and $_POST['input2'] = value2.
This is how i post form data using jquery
$.ajax({
url: 'http://example.com',
type: 'GET',
data: $('#checklist').serialize(),
cache: false,
}).done(function (response) {
/* It worked */
}).fail(function () {
/* It didnt worked */
});
Hope this helps, let me know how you get on!
I have very limited knowledge with scripts so I hope you guys can help me with a simple solution to a small problem that I have...
I'm using the following jquery function to refresh a div with new content when a link is clicked
<script>
$(function() {
$("#myButton").click(function() {
$("#loaddiv").fadeOut('slow').load("reload.php").fadeIn("slow");
});
});
</script>
My problem is, I need to send 2 variables to the reload.php page to use in a mysql query (I have no idea how to accomplish that), also I need to make multiple links work with this function, at the moment I have multiples links with the same id and only the first link works so I guess I must associate different ids to the function in order for this to work, how can I do that?
here's the page where i'm using this: http://www.emulegion.info/teste/games/game.php
You may want to use document ready instead of function on your first line as this will make sure the code is not executed until the full page (and all elements) have loaded.
You can then use the callback functions of the fade and load to perform actions in a timely manner.
additional variables you can add after the .php, these can then be read in your reload.php file as $var1 = $_GET['var1'];
Do make sure to sanitize these though for security.
<script type="text/javascript">
// execute when document is ready
$(document).ready(function() {
// add click handler to your button
$("#myButton").click(function() {
// fade div out
$("#loaddiv").fadeOut('slow',function(){
// load new content
$("#loaddiv").load("reload.php?var1=foo&var2=bar",function(){
// content has finished loading, fade div in.
$("#loaddiv").fadeIn('slow');
}); // end load content
}); // end fade div out
}); // end add click to button
}); // end document ready
</script>
For different variables you could add a HTML5 style variable to your button.
<input type="button" id="myButton" data-var1="foo" data-var2="bar" />
You can retrieve this when the button is clicked:
// add click handler to your button
$("#myButton").click(function() {
// get vars to use
var var1 = $(this).data('var1');
var var2 = $(this).data('var2');
...
load("reload.php?var1="+var1+"&var2="+var2
if you have multiple buttons/links I would use class instead of id "myButton". that way you can apply the function to all buttons with the above script. Just replace "#myButton" for ".myButton"
First, you should use .on('click', function() or .live('click', function() to resolve your one click issue.
You'll want to do something like:
<script>
$(function() {
$("#myButton").on('click', function() {
var a = 'somthing';
var b = 'something_else';
$.post('url.php', {param1: a, param2: b}, function(data) {
//data = url.php response
if(data != '') {
$("#loaddiv").fadeOut('slow').html(data).fadeIn("slow");
}
});
});
});
</script>
Then you can just put var_dump($_POST); in url.php to find out what data is being sent.
Try creating a function that would accept parameters that you want.
Like:
$(document).ready(function(){
$('.link').click(function(){
reload(p1,p2);
});
});
function reload(param1, param2){
$("#loaddiv").fadeOut('slow').load("reload.php?param1="+param1+"¶m2="+param2).fadeIn("slow");
}
But by doing the above code your reload.php should be using $GET. Also you need to use class names for your links instead of id.
<script type="text/javascript">
// execute when document is ready
**$(document).ready(function() {**
**$("#myButton").click(function() {**
**$("#loaddiv").fadeOut('slow',function(){**
**$("#loaddiv").load("reload.php?var1=foo&var2=bar",function(){**
// content has finished loading, fade div in.
$("#loaddiv").fadeIn('slow');
});
});
});
});
</script>
$("#myButton").click(function() {
// get vars to use
var var1 = $(this).data('var1');
var var2 = $(this).data('var2');
so i have a php loop, i am using jquery slide toggle to hide/show a table with sql results. currently the table is loaded using php only, but as there is a lot going on its causing some loading problems i need to fire the ajax with the slide toggle btn, so it only requests the current items details when the button is pressed. i can get it to call the php file from the jquery but im having difficulty passing the value for each item across, so it can perform the request on the database. here is what the php foreach loop content looks like;
<span class="searchitem">
// some visible content here
<span value="item name" class="btn">button</span>
<span class="slide_area">
// hidden slide content ajax needs to populate with php result
</span>
</span>
this html is repeated i use jquery slidetoggle to hide the slide_area, what i need to do is populate the slide_area with results from php, the php file needs the name to return the results the name is passed via get with the url, so i only need append the url with the actual name from btn's value, im sure this cant be that difficult but here i am.
here's the jquery:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function ()
{
$('.searchitem').each(function () {
$(this).find('.slide_area').hide();
$(this).find('.btn').click(function ()
{
var ajax_load = "<img src='images/spinner.gif' style='width:50px;' alt='loading...' />";
var loadUrl = "ajax/item.php?name=";
var loadName = $(".btn");
var Name = URLEncode(loadName);
var loadString = loadUrl + Name;
$(this).parent().find('.slide_area').slideToggle(1500).html(ajax_load).load(loadString);
});
});
});
//]]>
</script>
i need to get the value from btn and append the loadURL, im open to sending the data a different way like through post if needed, updated the jquery still not working what am i doing wrong here?
Thanks.
The easiest way would to use the Phery library http://phery-php-ajax.net/
the key here is the data-phery-remote="toggle" that will call the PHP function automatically on click, and can be reused everywhere
<span class="searchitem">
// some visible content here
<span value="item name" data-phery-remote="toggle" class="btn">button</span>
<span class="slide_area">
// hidden slide content ajax needs to populate with php result
</span>
</span>
The logic is reversed, the load will happen with only one AJAX call, instead of two.
Phery::instance()->set(array(
'toggle' => function($data){
$r = new PheryResponse;
/* do your code, fill $html_content */
$r->this()->siblings('.slide_area')->html($html_content)->toggle();
return $r;
}
))->process();
I Have a select button in php code which Passes the Dynamic generated Row value and How do i do this jquery?
PHP code
<input type ="button" onclick="select(add,'<?php echo $_POST['somevale=ue']?>')"
Javascript
function select (fnname, val){
//Val changes every time
}
How do i acheive the same in Jquery in Putting the click event to the button and passing the Dynamic value and Defining the Function in Jquery?
Use the click handler inside your document ready. Note that add must be a valid function for this to work available in the current scope.
$(function() {
$('input').click(function() {
select(add, 'value you need to pass');
});
function add() {
..
}
});
You can use HTML5 data-attributes here (they don't cause issues in HTML4), like this:
<input type="button" class="add" data-value="<?php echo $_POST['somevalue']?>" />
Then you can fetch it in your function using .attr(), like this:
$(function() {
$(".add").click(function() {
var value = $(this).attr("data-value");
select('add', value); //call original function
//or, put that function's content in here
});
});
Give it a try here