This question already has answers here:
Jquery: How to clear an element before appending new content?
(4 answers)
Closed 2 years ago.
I've recently started using and learning JS and jquery. I'm sending a user email from a form to my PHP page to check if any user exists in DB via ajax, then I get a response from my PHP file if the user exists or not and display the text in a div. It's working fine, but because the page doesn't refresh when the button for sending form data is pressed, ajax just stacks the response from PHP.
I probably need to clear the response every time the button is clicked first and then append the response but I can't find the right command for it :/
JS
function sendnewpass() {
var email = document.getElementById("useremail").value;
$.ajax({
type : "POST",
url : "login.php", //my php page
data : { passemail : email }, //passing the email
success: function(res){ //to do if successful
$("#emailsentmsg").append(res); //the the div that i put the response in
}
});
}
Use empty() like:
$("#emailsentmsg").empty().append(res);
Use the following:
$("#emailsentmsg").html("");
$("#emailsentmsg").append(res);
Or shorter (thanks #Ivar):
$("#emailsentmsg").html(res);
Related
This question already has answers here:
How do I pass JavaScript values to Scriptlet in JSP?
(9 answers)
Closed 6 years ago.
I want to pass a java script var to script let in jsp.
i tried many things but not working anything.can anyone tell me a working solution.
i have tried How do I pass JavaScript values to Scriptlet in JSP?
the way this other post stays, is the correct one.
1- create an ajax call (in Javascript) in your webpage to send your desired params to another page.
2- create a page (in jsp) where you request the data sent by the #1.
That's the correct way to go.
#1 Here's an example on how to make an ajax call, you need this on step #1, if your using jquery is simple as:
String data1 = "myData1";
String data2 = "myData2";
String your_jsp_page_to_request = "myJspPage.jsp";
$.post(your_jsp_page_to_request,
{ param1: data1, param2: data2 },
function(data){
alert("Data Loaded: " + data);
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
#2 Then in your jsp you need to request the data sent, just using:
String data1 = request.getParameter("param1");
String data2 = request.getParameter("param2");
This question already has answers here:
Fire Greasemonkey script on AJAX request
(2 answers)
Closed 3 years ago.
I'm using greasemonkey with Firefox to alter what content is displayed when I visit a particular domain. One of the pages contains a dropdown with two elements, let's call them element0 and element1. Whenever it detects a switch from one to the other, it performs an ajax query that alters the page content depending on which one you've selected. So it looks something like this:
$(".dropdown").change(function(){
if($(this).val()=='element0'){
$.ajax({
// fetch some html
});
}
else{
$.ajax({
// fetch some other html entirely
});
I'm happy with what is displayed when element0 is selected - it's element1's associated content I want to alter. So I need a way to trigger my own userscript function only in the second case. I also somehow need it to execute only after the ajax query is complete of course. How do I do this?
I have some basic experience with programming, but know absolutely nothing about jquery, ajax, json etc etc. A friend helped me locate the above ajax for that page so that I could even post a meaningful question. Please bear my level of experience in mind, because I'd really really like to move forward with whatever knowledge/wisdom you guys can offer, but will only be able to do so if I understand it.
Many thanks!
EDIT: The above is javascript that the host is running. I accessed it by saving the page and looking around manually. I am writing userscripts on the client side to alter what my browser displays. So I want to write my own function that responds to their js in the way I described.
AJAX
In ajax you have a tow useful method,
success & compleate
success: with execute if ajax request are work truth
complete: are work when finished ajax function, so you can use this method
example:
complete: function(){
// call another ajax, hide somthing, do any somthing
},
another example:
var all_data = {'user':txtuser,'pass':txtpass};
$.ajax ({
url:"ajax.php",
type:"post",
data:all_data,
beforeSend:function(){
// do somting before send a data
},
statusCode:{
404:function(){
$("#ma").html("Page not found");
},
401:function(){
$("#ma").html(".....");
}
},
success:function (data) {
$("#ma").html(data);// if sucsess
},
complete:function(){ // when complete
$("#user").hide(2000);
$("#pass").hide(2000);
$(".q").hide(2000);
}
});
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Focus Input Box On Load
i need a HTML search form that allow input text immediately. Same as Google. we needn't click to input text into search form
What you are looking for can be achieved a few different ways. The easiest would be via a AJAX POST via jquery. I'll give you a little example:
Let's pretend your search input has a name attribute such as "keywords"
$(function(){
$("input[name='keywords']").keyup(function(){
$(".search_results").slideUp("normal", function(){
$.ajax({
type: "POST", url: "searchquery.php",
data: {keywords: $(this).val()},
success: function(response){
if(response != "error")
{
$(".search_results").html(response);
$(".search_results").slideDown();
}
else
{
alert("Error Searching. Please refresh the page and try again.");
}
}
});
});
});
});
Then you need to have searchquery.php handle searching the database and returning the data in html format. Maybe something like this:
if(trim($_POST["keywords"]) != "")
{
$keywords = mysql_real_escape_string($_POST["keywords"]);
//search the DB for maybe 5 top results and return them in something like a HTML list:
$results = '<ul><li>first</li><li>second</li></ul>';
die($results);
}
Your on your own for formatting the div or HTML object with the class "search_results" defined on it.
Also, I would advise adding a timer, so that each time the "keyup" function is hit, it records the time and make a minimum of _ amount of time before the next call to the file is allowed. That way the PHP file doesn't get 5 calls when someone writes 1 word.
Is it possible to run a MySQL query using jQuery? I'm trying to emulate the functionality of voting on SE sites.
The vote counter on SE automatically updates without the need to reload the page (which is what I currently have, a hidden form that re-submits to the current page but runs a small block on PHP that updates the score of a question in the database). I'm assuming that is being done using Javascript/jQuery seeing as it is dynamic.
How can I do this? Is there a library which makes it easy and simple (like PHP)?
You can use ajax to call a server page (PHP / ASP /ASP.NET/JSP ) and in that server page you can execute a query.
http://api.jquery.com/jQuery.ajax/
HTML
<input type='button' id='btnVote' value='Vote' />
Javascript
This code will be excuted when user clicks on the button with the id "btnVote". The below script is making use of the "ajax" function written in the jquery library.It will send a request to the page mentioned as the value of "url" property (ajaxserverpage.aspx). In this example, i am sending a querystring value 5 for the key called "answer".
$("#btnVote").click(function(){
$.ajax({
url: "ajaxserverpage.aspx?answer=5",
success: function(data){
alert(data)
}
});
});
and in your aspx page, you can read the querystring (in this example, answer=5) and
build a query and execute it againist a database. You can return data back by writing a Response.Write (in asp & asp.net )/ echo in PHP. Whatever you are returning will be coming back to the variable data. If your query execution was successful, you may return a message like "Vote captured" or whatever appropriate for your application. If there was an error caught in your try-catch block, Return a message for that.
Make sure you properly sanitize the input before building your query. I usually group my functionalities and put those into a single file. Ex : MY Ajax page which handles user related stuff will have methods for ValidateUser, RegisterUser etc...
EDIT : As per your comment,
jQuery support post also. Here is the format
$.post(url, function(data) {
alert("Do whatever you want if the call completed successfully")
);
which is equivalent to
$.ajax({
type: 'POST',
url: url,
success: function(data)
{
alert("Do whatever you want if the call completed successfully")
}
});
This should be a good reading : http://en.wikipedia.org/wiki/Same_origin_policy
It's just a few lines in your favorite language.
Javascript
$.post('script.php', { id: 12345 }, function(data) {
// Increment vote count, etc
});
PHP (simplified)
$id = intval($_POST['id']);
mysql_query("UPDATE votes SET num = num + 1 WHERE id = $id");
There are many different ways to accomplish this.
This question already has answers here:
Pass entire form as data in jQuery Ajax function
(7 answers)
Closed 5 years ago.
I would like to use jQuery.ajax to submit a form using POST without having to specify everything manually in the "data: " part.
This is what I don't want:
data: "username=" + document.getElementById("username").value +
"&email=" + document.getElementById("email").value,
Is there a way to just have it include alla elements with their values from an entire FORM field? This form is generated dynamically so it would save me a lot of time!
Use serialize method.
data : $("form").serialize()
Look at http://docs.jquery.com/Ajax/serialize.
That would make the following example:
$("#submit").click(function() {
$.ajax({
data: $("form").serialize(),
...rest
});
});
Use .serialize() method to send entire form data in jQuery Ajax.
data:$('#formID').serialize()
Example script can be found from here - How to send entire form data in jQuery Ajax