简体   繁体   中英

changing the href of anchor inside ajax return but then it is overwritten

Hello all i have a problem i have a table with a link in one of the columns on the click of that link i send it to a function that uses ajax to get a different link for it to direct to. inside the ajax function it is being changed correctly but then after it finishes the ajax it still redirects to the original page. if i change it outside of the ajax return it works correctly and redirects to a different site

this is my code:

the php function for building the table

function populate()
{
$link = connectToDB();
$query = 'Select value1, value2
         from table1';
$data = read($query, $link);
$table = '<div id="table"><table id="links">
            <tr>
            <th>value1</th>
            <th>value2</th>   
          </tr>';

$num =0;
while ($row = $data->fetch_assoc()) {
    $table .= '<tr>';
    $table .= '<td>' . $row['value1'] . '</td>';
    $table .= '<td><a id="redirection'.$num.'" onclick="redirect('.$num.')" href=”/?redirection.php?' . $row['value2'] . '>' . $row['value1'] .'</td>';
    $table .= '</tr>';
    $num++;
}
$table .= '</table></div>';
mysqli_close($link);
return $table;
}

the javascript to change the href

function redirect(num){
    var url = $("#redirection"+num).attr("href");
    var sub = url.split('?');
    var val1= sub[2];
    var test = "";
    $.ajax({
        url: 'getNewUrl.php',
        type:'POST',
        dataType: 'json',
        data: { name: val1},
        success: function(table){
            alert(table.val2);
            $("#redirection"+num).attr("href",table.val2);
            var check =$("#redirection"+num);
        },
        error: function () {
            alert("No value with that name");
        }
    });
}

when i am alerting the value retured it is the correct one, and when i am checking the href value of check in debugger it is being changed correctly but then i am still redirected to the wrong site

thanks for the help

i think the problem is in href=”/? and wrong doublequote and miss close quote and remove "?" after =/

onclick="redirect('.$num.')" href=”/?redirection.php?' . $row['value2'] . '

it's sould be like this.

onclick="redirect('.$num.')" href="/redirection.php?' . $row['value2'] .'"

hope this help.

Okay so i as going about this all wrong and just figured it out instead of changing the href and then having it redirect me to a page i just used window.location to redirect me from inside the ajax and the href change was redundent

Thanks to all who tried to help me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM