1

I have an ajax function which looks like this (basically, it's simplified):

function getPage(targetURL, targetID, dataMethod, dataStream) {
  $.ajax({
    type: dataMethod,
    data: { dataStream },
    url: '../' + targetURL,
    success:
        function(server_response)   { 
            $('#' + targetID).html(server_response).show();
        }
    });
  return false;
}

I then want to call the function like this:

onclick="getPage('myPage.php', 'content', 'GET', 'someAction: add');"

And that is very good... But right now function thinks add is a variable... But in some cases, I need to declare someAction with a value, from within the onClick, like this:

onclick="getPage('myPage.php', 'content', 'GET', 'someAction: "add"');"

However, that is ofcourse not working... Neither does ofcourse:

onclick="getPage('myPage.php', 'content', 'GET', 'someAction: \"add\"');"

So what will a wise man do?

4
  • 2
    Well, for starters, a wise man wouldn't use onclick inline event handlers! Commented Oct 15, 2012 at 14:02
  • One option is: data: dataStream, and onclick="getPage('myPage.php', 'content', 'GET', 'someAction=add');". Commented Oct 15, 2012 at 14:02
  • 1
    LOL @BenM I was about to write the same thing. Commented Oct 15, 2012 at 14:02
  • Sure I will use $('#someid').click(function() { // Do somthing }); I'm still a newb, trying to figure things out :) Commented Oct 15, 2012 at 14:36

3 Answers 3

1

This is because you are mixing strings and objects. In order to do what I think you want to do, you should call the function like this:

onclick="getPage('myPage.php', 'content', 'GET', { someAction: 'add' });"

i.e., you are passing an object as the fourth parameter, and not a string, then, in your function, you should treat that object as it is, i.e.

$.ajax({
  type: dataMethod,
  data: dataStream,
  url: '../' + targetURL,
  // ...
Sign up to request clarification or add additional context in comments.

Comments

1

You're passing dataStream as a string, you shouldn't - it should be an object literal:

function getPage(targetURL, targetID, dataMethod, dataStream) {
  $.ajax({
    type: dataMethod,
    data:  dataStream ,
    url: '../' + targetURL,
    success:
        function(server_response)   { 
            $('#' + targetID).html(server_response).show();
        }
    });
  return false;
}

and then:

onclick="getPage('myPage.php', 'content', 'GET', {someAction: add});"

or

onclick="getPage('myPage.php', 'content', 'GET', {someAction: \"add\"});"

Comments

1

It's expecting an object, so give it one:

onclick="getPage('myPage.php', 'content', 'GET', {someAction: add});"

Then inside the function:

    data: dataStream,

without the braces

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.