1

I have a function for getting records from database on keyup event. Here is my code:

function displaySearch(key) {
$.ajax({
    type:"POST",
    url:"searchprofile.php",
    data:{
        k:key
    },
    success:function(data){
       var details_arr=data.split("+");
        $('.searchresult').empty();
        for(var i=0;i<details_arr.length-1;i++){
            $('.searchresult').append("<div class='profile' id='searchprofile'><img class='profilepic' src='images/profile.jpg'/><div class='doctorname'><div class='pname' onclick='saveName("+details_arr[i]+")'>"+details_arr[i]+"</div></div></div>");
            $('.searchresult').show();
            $('.searchresult .profile').show();
        }
        details_arr.length=0;
    }
});
}

But i am getting javascript error here saying "Unexpected token ILLEGAL". How do i give the onclick function with the value of details_arr[i]? Please help.

6
  • 2
    "unexpected token ILLEGAL" means you have a syntax error in your code. Commented Dec 14, 2012 at 9:01
  • Perhaps you have a syntax error in your previous code? The code you have posted is correct, syntactically. Commented Dec 14, 2012 at 9:04
  • $('.searchresult') could be cached for performance. Commented Dec 14, 2012 at 9:06
  • Using onclick='saveName("+details_arr[i]+")' is ugly, especially in dynamically generated code. It would be much cleaner if you attached the handler with jQuery. Commented Dec 14, 2012 at 9:10
  • @Jan Dvorak This error is at line 1 i.e at the <html> tag. I have php code before that. Commented Dec 14, 2012 at 9:11

5 Answers 5

4

As you have jQuery, you really shouldn't inline code. As you see it makes it more difficult to handle quotes inside quoted strings (yes, you're missing quotes around your argument to saveName).

You may do this :

  (function(i){
      $('.searchresult').append(
        "<div class='profile' id='searchprofile'>"
        + "<img class='profilepic' src='images/profile.jpg'/>"
        + "<div class='doctorname'>"
        + "<div id=someId class='pname'>"+details_arr[i] // <- give some Id
        +"</div></div></div>"
      );
      $('#someId').click(function(){saveName(details_arr[i])});
  })(i);
  $('.searchresult').show();

Note that I used a closure to ensure that i has the needed value in the callback (not the value at end of iteration).

Be careful with the split: on most browsers "+aaa".split('+') makes ["", "aaa"] and as you don't iterate up to the end of the array, this sample string would made you iterate on nothing.

Sign up to request clarification or add additional context in comments.

4 Comments

@ChetanaKestikar and still there is one less bug in the code. Upvoting.
@ChetanaKestikar Why don't you loop over the whole array ? Is that a bug ?
@dystroy Hey i tried your code again, this time i just added an alert before 'saveName(details_arr[i])'. The value of details_arr[i] i am getting is 'undefined'. And i did not understand the loop over idea. Can u please explain?
@dystroy To avoid getting the blank record, in for loop i gave the condition 'i<details_arr-1'. I think that overcomes the empty record problem.
1
function openNow(x)
{
    var pageUrl = '<%=ResolveUrl("~/OnFriends.php")%>'
    $.ajax({
        type: "POST",
        url: pageUrl + '/CreateNew',
        data: '{k: "'+ x +'"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success:function(data)
        {
            <---Now Do Your Code Hear--->
        }
        });
}

CreateNew is my web service what i created in .php file

8 Comments

now this AJAX request will execute the 'CreateNew' function of OnFriends.php file and return the result as 'data'
So CreateNew is a function in the php file called? I did not know we could give the function name in url.
Thanks for the info. But i am getting the data from the php page. The issue is i am not able to get the onclick function result on div.
not just a function... that must be a Static Function (WebService)
if you never created a web service theGoogle it "How to create a web service in php"
|
1

I would use something like that bare in mind ID must be unique inside a document (HTML Page) because the content is generated on the fly; it's better to use the JQuery "on"

   $(".pname").on("click", function (event) {
       saveName($(this).text());
   });

event handler to bind the click event

function displaySearch(key){
    $.ajax({
        type: "POST",
        url: "searchprofile.php",
        data: {
            k: key
        },

        success: function(data) {
            var details_arr = data.split("+");

            var searchResults = "";
            for (var i = 0; i < details_arr.length - 1; i++) {
                searchResults += "<div class='profile'>" +
                    "<img class='profilepic' src='images/profile.jpg'/>" +
                    "<div class='doctorname'>" +
                    "<div class='pname'>" + details_arr[i] +
                    "</div></div></div>";

            }
            $('.searchresult').html(searchResults).show();
        }
    });
}

$(".pname").on("click", function (event) {
    saveName($(this).text());
});

use the Jquery html to replace everything inside searchresult outside the loop that way it will be called once not details_arr.length - 1 times

3 Comments

Hey thanks for the help. But this is not working. The onclick event on $(".pname") is not working.
can you give us the website address to debug it for you or you can use jsfiddle.com
Okay... But this will take me sometime.
0

you should tell the line at which you are getting error

i think you did not specified you web service in ajax call at... "url:"searchprofile.php"

6 Comments

@Pankaj I don't understand your point. Maybe you could make it clearer ?
first you have to create a web service in searchprofile.php the write like this... url:"searchprofile.php/<--your service name-->"
It depends on how your page is made. It's fine to have a page directly answering searchprofile.php?data=33.
@dystroy you are suggesting him to send data as Querystring that's not the right way... data may be confidential
If it's confidential, then use SSL, don't try to hide the data in a post body. And please don't try to say it's always wrong to use parameters in an URL...
|
0

Finally got the onclick function working. :)

Instead of appending the div everytime, i just editted my php page by adding the html i needed in the data that is returned in ajax.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.