Tom Tom - 1 year ago 82
Ajax Question

Checking a condition through Ajax

I have following code in jquery for my webpage http://localhost/currentpage

$('body').on('click', '.checkid', function(e) {
var url = 'http://localhost/newpage';
var id = $(this).attr('data-id');

type: 'GET',
url: url,
success: function (data) { }


What I want need to do is I need to check whether there is an ID exists with same name in page http://localhost/newpage .Suppose the ID is myId , I need to check whether there is a ID with same name in http://localhost/newpage.

Can anybody help me how to execute it in jquery through ajax request for the above coding ?

Answer Source

Assuming data in the AJAX response is a HTML string, you could check for the presence of your ID checking with a RegExp on the tags:

if (data.match(/<.*id="myId".*\/?>/gi)) {
  // a tag with ID "myId" has been found

The above code needs to be executed inside your function success(data) {} callback.

You can also achieve the same using jQuery, by doing $(data).find('#myId').length > 0

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download