Careless Careless - 7 months ago 12
Javascript Question

Why am I getting array how to get string

If I have textarea with

id leavepost
and hidden div
id display

After # I got hidden div and word with # in var name
But when I want to sent itvia ajax to sul file it sends array.
What is wrong?

$("#leavepost").keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 35) {
$('#display').show();
$('#leavepost').on('keyup', function() {
var name = $(this).val().match(/(^|\s)(#[a-z\d-]+)/ig);
$.ajax({
type: "POST",
url: "d/sul.php",
data: { su: name },
success: function(sss)
{
$('#display').html(sss);

}
});
}).keyup();
}
});


Inside sul.php I have:

echo $_POST['su'];
$u = mysqli_real_escape_string($con, $_POST['su']);


error:


Warning: mysqli_real_escape_string() expects parameter 2 to be string,
array given

Answer

.match() returns an array of matching tests.

// for example:
"xzxzxz".match(/z/gi)    // => [z,z,z]
"xzxzxz".match(/z/gi)[0] // => "z"

Either use .match(/(^|\s)(#[a-z\d-]+)/ig)[0] to get the first match.

or you can .match(/(^|\s)(#[a-z\d-]+)/ig).join(",") to send all the test matches in a string.

// for example
"xzxzxz".match(/z/gi).join(",") // => "z,z,z"
"xzxzxz".match(/z/gi).join("")  // => "zzz"