AJAX Search results are appending to existing results

After entering the keyword in search box, click on search icon need to get the results, everytime entering the keyword and clicking instead of refreshing the results are appending to the exisitng results, can anyone check the below where I am doing wrong.

function makeRequest()
{
	$.ajax({
	    url:"cnc/cncstorelocator",
	    type:'GET',
	    cache:false,
	    data: {searchCriteria : $('#cnc-searchcriteria').val()},
	    dataType: 'json',
	    success : function(cncStoreLocatorData)
		{
	    	 var store=null;
	    	for (var i = 0; i < cncStoreLocatorData.length; i++) {
	          var loc = cncStoreLocatorData[i];
	         store = $('<div/>').addClass('pane');
	          var store_hours = loc.hrsOfOperation;
	         var str1 =  $('<p/>').addClass('stores-timing');
	         var store_timings=null;
	          for (var j = 0; j < store_hours.length; j++) {
	                 var storetime = store_hours[j];
	               	store_timings = str1.append($('<span/>').html('<strong>' + storetime.days_short));
					store_timings.appendTo(store);
				 }
	          $("#cncstorepane").append(store);

	           }
	    },
	    error: function(cncStoreLocatorData) {
	    		alert("can't make req");
	    	}
	     
	  });

}
1 Like

here: str1.append(...)

I didn’t get you could you please explain clearly?

there you append the search results to the existing results.

correction, it’s the next line that does it: $("#cncstorepane").append(store);

Oh ok, How can i rectify that any solution?

replace instead of append.

1 Like

If I use replace instead of append in the below code no results are showing.

$(“#cncstorepane”).replace(store);//append

Is it you want to say?

@Dormilich: At function start I am making main div empty to which i am appendning the results, it’s working fine. Part from this I need one more help if my search keyword is same )Ex: I entered ‘abc’ clicked got the results again i clicked no need to call the ajax because already resluts are there so…how can I stop the ajax request at that time.

$(“#cncstorepane”).html(‘’);

you could use a cache or you could simply check if the last lookup key (which you have to store somewhere for that) is identical to the current one.

a nice example for caching is https://datatables.net/examples/server_side/pipeline.html, with pretty much the same intention as yours.

In addition to this, you should have a condition to check whether results have already appended or else there would be nothing to replace.

Check the w3c schools site for ajax search implementation www.w3schools.com/php/php_ajax_livesearch.asp?

of course you don’t need all of the code from that antiquated example as no one uses IE6 or earlier any more.

Just remember that the JavaScript section of the w3schools site is on average about 15 years out of date.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.