2

So I was looking on some SO questions and the jQuery area to try to use the similar feature in PHP using explode which will just explode a string given into it's pieces from a type of substring.

This is the code I used:

var users = // AJAX CALL TO GET USERS
var usersArr = users.split();

I looked at the w3 tutorial for splitting strings and this was the JavaScript type, and even that didn't work.

Error message:

index.js:45 Uncaught TypeError: users.split is not a function

10
  • 4
    split() should be split(',') or the delimiter of your choice Commented May 18, 2016 at 10:07
  • 4
    AJAX is asynchronous!. Commented May 18, 2016 at 10:07
  • What output did you get and where there any errors in the console? Commented May 18, 2016 at 10:07
  • It should be .split('') (empty string). But make sure that your ajax request has returned from server (common pit fall) Commented May 18, 2016 at 10:08
  • 2
    Could you post a full code sample. If you're doing var users = $.ajax(); then users will be a deferred object, not a string, hence the error you get. You should use the callback of the AJAX request. Also split() requires a parameter to break the string by. Commented May 18, 2016 at 10:08

2 Answers 2

7

just like PHP you can do but with different method.

var str = "How are you doing today?"
var res =  str.split(" ");

access this way : "String :" + res[0]+" "+res[1]+" "+res[4]+" "

output : How are today?

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

Comments

2

Since Ajax is asynchronous, you have to set users variable inside the success callback of the Ajax call and then split the string.

It can be don like this.

$.ajax({
    url: "url-to-the-page",
    success: function(data) {
        var users = data;
        var usersArr = users.split(";"); // if semicolon is the separator.
    }
});

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.