2

I'm trying to redirect a user to an existing URL (stored in a MySQL database) if the value they input already exists in the database. I've got most of it working, but I've run into some issues.

I'm using AJAX to check the database. It sends the input value to another PHP file & checks the database to see if it already exists.

if($row) {
    echo ".$row["itemNum"].";
} else {

}

It's within the AJAX code that I'm having issues, in particular this:

success: function (response) {
    if (response == <?php ".$row["itemNum"]." ?>) {
        window.location.href = "http://www.example.com/" <?php echo "+"; if (".$row["itemNum"].") { echo ".$row["itemNum"]." } else {""}
    } else {
        // do other stuff
    }
}

$row["itemNum"] doesn't always exist, so it's in a conditional statement to prevent a syntax error.

The above doesn't work regardless of how I do it.

I have a feeling the main issue is with the if (response == <?php ".$row["itemNum"]." ?>) line?

3
  • try to remove your echo "+"; line like : window.location.href = "http://www.example.com/ <?php if ($row["itemNum"]) { echo $row["itemNum"]; }; Commented Mar 20, 2017 at 11:30
  • You might also want to change if (response == <?php ".$row["itemNum"]." ?>) to if (response == '<?php ".$row["itemNum"]." ?>'), i.e. add apostrophes around the echoed value. Commented Mar 20, 2017 at 11:33
  • You can't mixing php (server side) and js (client side) like that Commented Mar 20, 2017 at 11:33

2 Answers 2

3

Based on this code:-

if($row) {
    echo $row["itemNum"]; // check the change here
} else {

}

You have to do like this:-

success: function (response) {
    if (response !== '') { // if response have some value
        window.location.href = "http://www.example.com/"+response;
    } else {
        // do other stuff
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

As you suspected you have problem with following line.

if (response == <?php ".$row["itemNum"]." ?>) {

The Problem is your use of (") and (.) characters

Following syntax will give you what you want.

if (response == <?=$row["itemNum"]?>) {

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.