Ajax - reload previus data in div after search field is emptied - javascript

I have a small ajax script with which i'm searching and loading results without reloading or redirecting the page:
$(document).ready(function(){
$('#db-search').keyup(function(){
var txt = $(this).val();
if(txt != ''){
$('#db-search-results').html('');
$.ajax({
url: 'search.php',
method: 'post',
data:{search:txt},
dataType: 'text',
success:function(data){
$('#db-search-results').html(data);
}
});
} else{
//reload previus data
}
});
});
It works but there is a problem. Before entering anything in #db-search field I'm already displaying all the results from the database inside #db-search-results. Now when I'm searching for something all that previous data is replaced with those new results but if I clear the search field my results are gone(which is ok) but my previous data isn't coming back.
Is there a way to keep previous data after clearing that search field?
P.S: currently i'm just performing a SELECT * query and then i'm loading it using $('#db-search-results').html('search.php'); but that's an extra query and I would rather search for another way of doing this :D

You could store it in a variable once the page is loaded and display it when you need like :
$(document).ready(function(){
var default_data = $('#db-search-results').html();
$('#db-search').keyup(function(){
var txt = $(this).val();
if(txt != ''){
$('#db-search-results').html('');
$.ajax({
url: 'search.php',
method: 'post',
data:{search:txt},
dataType: 'text',
success:function(data){
$('#db-search-results').html(data);
}
});
} else{
$('#db-search-results').html(default_data);
}
});
});

I hope this helps
$(document).ready(function(){
var previousData='';
$('#db-search').keyup(function(){
var txt = $(this).val();
if(txt != ''){
$('#db-search-results').html('');
$.ajax({
url: 'search.php',
method: 'post',
data:{search:txt},
dataType: 'text',
success:function(data){
previousData=data;
$('#db-search-results').html(data);
}
});
} else{
//reload previus data
$('#db-search-results').html(previousData);
}
});
});

Related

Ajax/PHP/JavaScript form submit with local storage value

I am trying to submit data and also a local storage value into my mysql database from the one ajax post. I can do one or the other but not both at the same time.
var dataString = 'title=' + title + '&level=' + level + '&dateTo=' + dateTo + '&dateFrom=' + dateFrom + '&description=' + description ;
if (title == '' || level == '' || dateFrom == '' || dateTo == '' || description == '')
{
alert("Please Fill All Fields");
}
else
{
//AJAX code to submit form.
$.ajax({
type: "POST",
url: "http://localhost:8888/EduSubOct/jobpost.php",
data: dataString,
cache: false,
success: function(html) {
alert("Information Entered Successfully");
}
});
}
return false;
}
in the above code, I am using data: dataString and below you will see I am using the local storage value object. I want to post both of these data strings/objects into one row in my database on one click button. You can see my code below that shows the local storage submission from Ajax.
function myFunctionjob() {
// Returns successful data submission message when the entered
information is stored in database.
//AJAX code to submit form.
$.ajax({
type: "POST",
url: "http://localhost:8888/EduSubOct/jobpost.php",
data: { storageValue: localStorage.getItem("email"); }
cache: false,
success: function(html) {
alert("Information Entered Successfully");
}
});
}
My php works fine when done as two separate ajax posts. Ideally I would like in one Ajax post to the database. Any help on how I can sumbit both the dataString and the local storage value at the one time. Thanks!
Just Include both datastring and value from local storage in the data section of ajax request.
$.ajax({
type: "POST",
url: "http://localhost:8888/EduSubOct/jobpost.php",
data: { storageValue: localStorage.getItem("email"), dataString: dataString}
cache: false,
success: function(html) {
alert("Information Entered Successfully");
}
});
here on the server, you can access localstorage value as $_POST['storageValue'] and data string object as $_POST['dataString']

Saving data with ajax to a database

How can I save info that I have in a div named '#time' to a database?
<div id="time" style="float:right;font-size:15px;">0:00:00</div>
The code above is a jq count up timer.
What I'm trying is to save every tick in the database.
How can I do this?
$.ajax({
type: "POST",
url: "setupcounter.php",
data: {action: 'save',
field: $("#time").val(),},
success: function(msg){
}
error: function(){
alert('error');
}
});
Actually you want to get text of div. So do this..
Just replace
$("#time").val()
with
$("#time").text()
var time = $('#time').val();
//Just add whatever params you need to the datastring variable.
var dataString = 'time='+time+'&action=save';
//Check console that you are sending the right data
console.log(dataString)
$.ajax({
type: "POST",
url: "setupcounter.php",
data: dataString,
success: function(msg){
console.log(msg);
}
});
In php you would do:
$time = $_POST['time'];
$action = $_POST['action'];
//Db stuff
Fiddle

Using jQuery or Javascript redirect to given page with a value

I have a dropdown, on its change it should redirect to a page with the dropdown's value say as a POST
I tried something like this:
$(document).ready(function() {
$('some_dropdown').change(function() {
var id = $(this).val();
var datastring = 'id=' + id;
$.ajax({
type: "POST",
url: "xyz.php",
data: datastring,
cache: false,
success: function(html) {
window.location.href("xyz.php");
}
});
});
});
On the xyz.php page:
if ($_POST['id']) {
Blah Blah..
}
It's not recognizing that id value on the xyz page. I want it's value on the redirected page.
Edited - To make things more clear, I tried out to print the xyz.php's contents on my original page (instead of redirecting) like this -
$.ajax({
type: "POST",
url: "xyz.php",
data: datastring,
cache: false,
success: function(html) {
$(".somediv").html(html);
}
FYI, "somediv" was <div class="somediv"></div> in my original page(no-redirecting) and it worked!! It could identify the id. Some how can't work it out with redirecting. It can't identify the id.
Edited --
Last thing, if I don't redirect and use
$.ajax({
type: "POST",
url: "xyz.php",
data: datastring,
cache: false,
success: function(html) {
$(".somediv").html(html);
}
The data loads perfect, my question is can I make some changes in the dynamically loaded textboxes and insert them in the database
If you have to make a post request can make it by appending a virtual form.
Here is the code for that.
$(document).ready(function() {
$('[name="some_dropdown"]').change(function() {
var mval = $(this).val(); //takes the value from dropdown
var url = 'xyz.php'; //the page on which value is to be sent
//the virtual form with input text, value and name to be submitted
var form = $('<form action="' + url + '" method="post">'+
'<input type="text" name="id" value="' + mval + '" />'+
'</form>');
$('body').append(form); //append to the body
form.submit(); //submit the form and the page redirects
});
});
and on PHP
if(isset($_POST['id'])){
echo $_POST['id'];
}
Your datastring should be key value pair. Like this.
var datastring = {'id':id};
you have few mistakes in your code so your correct code will be like this
$('.some_dropdown').change(function(){
var id = $(this).val();
var datastring = 'id='+id;
$.ajax({
type: "POST",
url: "xyz.php",
data: datastring,
cache: false,
success: function(html){
window.location.href= "xyz.php?"+datastring+"";
}
});
});
});
and php code
if(isset($_GET['id'])){
Blah Blah..
}

pass data to lable in same page using jquery

i have this working code with this code i can pass data to div within same page
but insted of passing data to div i want to pass this to label or textbox so that i can post it to the server. i am new in ajax,jquery . please suggest me best answer
<script type="text/javascript">
//send clicker data to div
$(function() {
$(".clicker").mouseover(function(){
var data = $(this).attr('id');
$.ajax({
type: "POST",
data: "db_data=" + data,
success: function(){
//alert(data);
$('.responseDiv').text(data);
}
});
});
});
</script>
<script type="text/javascript">
i think i need to change this line only
$('.responseDiv').text(data);
but dont know how to do that. didnt find any solution on net also
take any name like propertyId
Let's say the text field has id="propertyID"
Use the val() method to assign this new value to your text field.
$('#proertyID').val(data);
Like:
$(function() {
$(".clicker").mouseover(function(){
var data = $(this).attr('id');
$.ajax({
type: "POST",
data: "db_data=" + data,
success: function(){
//alert(data);
// $('.responseDiv').text(data);
$('#proertyID').val(data);
}
});
});
});
In the below line change selector .responseDiv with id/name or class of input/label $('.responseDiv').val(data);
<script type="text/javascript"> //send clicker data to div
$(function() {
$(".clicker").mouseover(function(){
var data = $(this).attr('id');
$.ajax({
type: "POST",
data: "db_data=" + data,
success: function(data2){
//alert(data);
$('.responseDiv').text(data2);
}
});
});
});
success return in data2 and use this..

using ajax how to show the value after success without refreshing the page

i am adding the value to database by using ajax after adding i want to display the value in front end but now after success i am using window.location to show the data because of this the page getting refresh,i don't want to refresh the page to show the data ,anyone guide me how to do this.
below is my ajax
$(function() {
$(".supplierpriceexport_button").click(function() {
var pricefrom = $("#pricefrom").val();
var priceto = $("#priceto").val();
var tpm = $("#tpm").val();
var currency = $("#currency").val();
var dataString = 'pricefrom='+ pricefrom +'&priceto='+priceto+'&tpm='+tpm+'&currency='+currency;
if(pricefrom=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html;
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
window.location = "?action=suppliertargetpiceexport";
$("#flash").hide();
}
});
} return false;
});
});
The code that you are using to post the data needs to return some meaningful data, JSON is useful for this, but it can be HTML or other formats.
To return your response as JSON from PHP, you can use the json_encode() function:
$return_html = '<h1>Success!</h1>';
$success = "true";
json_encode("success" => $success, "html_to_show" => $return_html);
In this piece of code, you can set your dataType or JSON and return multiple values including the HTML that you want to inject into the page (DOM):
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
//Set the type of data we are expecing back
dataType: json
success: function(return_json){
// Check that the update was a success
if(return_json.success == "true")
{
// Show HTML on the page (no reload required)
$("#display").after(return_json.html_to_show);
}
else
{
// Failed to update
alert("Not a success, no update made");
}
});
You can strip out the window.location altogether, else you won't see the DOM update.
Just try to return the values that you need from the ajax function.Something like this might do.
In your insert.php
echo or return the data at the end of the function that needs to be populated into the page
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(data){
//Now you have obtained the data that was was returned from the function
//if u wish to insert the value into an input field try
$('#input_field').val(data); //now the data is pupolated in the input field
}
});
Don't use window.location = "?action=suppliertargetpiceexport";
This will redirect to the page suppliertargetpiceexport
$.ajax({
type: "POST",
url: "supplierpriceexport/insert.php",
data: dataString,
cache: false,
success: function(html){
$('#your_success_element_id').html(html); // your_success_element_id is your element id where the html to be populated
$("#flash").hide();
}
});
your_success_element_id is your element id where the html to be populated

Categories

Resources