Vereonix
Vereonix

Reputation: 1413

Link to a page and trigger ajax via the same button

I'm trying to make a div button which triggers ajax and links to a page which the ajax is posting data to. I have the ajax working on click, but can't seem to get the link to work at all with it, all the ways I've tried to get the link working do nothing.

I have a div button:

<div class="cman shadow1" id="search_button" value="carSearch"/>
    Start Search
</div>

Which triggers:

function carSearch() 
{
    $.ajax({
        type: "POST",
        url: 'searchpost.php',
        data: 
        {
            mpg : $('.mpg').val()
        },
        success: function(data)
        {
            alert("success! "+$('.mpg').val());
        }
    });
}

Edit:

Feel I should mention that the page I wish to link to is atm:

<?php
session_start();

$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('cdb', $conn);

if(isset($_POST['mpg']))
{
    $mpg = (int)($_POST["mpg"]);        

header("Location: home.php");
exit;
}
?>

I wish to use this to gather all of the search fields the user enters to then load the search results page. The above code for it is just for testing right now.

I mention this as user @Doge suggested doing document.location.href = "searchpost.php" in the success handler of the ajax, this did cause the page to change but the page didn't run the isset and the redirect, so the js variable wasn't posted, or it was but this instance of the page didn't get it.

The isset and redirect do work as using the XHR Network tab on my page the page it is to redirect to appears.

Upvotes: 0

Views: 171

Answers (1)

Steve
Steve

Reputation: 20469

If you must do this via js then create a hidden form, populate it and submit it:

html:

<form method="post" id="hiddenform" action="searchpost.php">
    <input type="hidden" name="mpg" id="mpg"/>
</form>

js:

function carSearch() 
{ 
    $('#mpg').val(yourjsvariable);
    $('#hiddenform').submit();
}

Upvotes: 1

Related Questions