Albin N
Albin N

Reputation: 1401

Saving to database via AJAX/jQuery, sending two variables

I have this problem that I have multiple fields that updates a database via an AJAX-call. The AJAX call looks like this:

$(".fresheditable").fresheditor("save", function (id, parsedHtml) {
    $.ajax({
        url: 'save.php',
        type: 'POST',
        data: {
            id: id,
            parsedHtml: parsedHtml
        }
    });
});

The ID value changes depending on what element is being edited. The problem is when the update gets sent to the save.php document. How do I only run the update with the specific ID?

See my save.php:

if($_POST['id']='link') 
{
    $link = $_POST['parsedHtml']; //get posted data

    // query
    $sql = "UPDATE buttons SET linkname=? WHERE id=?";
    $q = $conn->prepare($sql);

    if ($q->execute(array($link,$_SESSION['button'])))
    {
        echo 1;
    }
}

//The next if-statement could look like this:

if($_POST['id']='contactperson') 
{
    $contactperson = $_POST['parsedHtml']; //get posted data

    // query
    $sql = "UPDATE buttons SET contactperson=? WHERE id=?";
    $q = $conn->prepare($sql);

    if ($q->execute(array($contactperson,$_SESSION['button'])))
    {
        echo 1;
    }
}

If more than one ID is sent to the save.php say link and contactperson both if-statements are true and the update sets the same values because the parsedHtml variable.

Is there anything I can do in save.php that can prevent this? Somehow I need to associate the correct parsedHtml with the corresponding id.

Upvotes: 0

Views: 2119

Answers (4)

sync
sync

Reputation: 5620

Is it because you're using single equals in your IF tests, which assigns and returns true as a value exists? Not double-equals for comparison?

E.g.

if($_POST['id']=='link') 

not

if($_POST['id']='link') 

Upvotes: 1

devnull69
devnull69

Reputation: 16544

The comparison operator in PHP (as well as in Javascript) is == and not =

if($_POST["id"]=="link")

Upvotes: 2

chirag
chirag

Reputation: 27

One thing you can use is data attribute i mean

<span item-data="some_id">data</span> now you can select in jquery, the specific item-data from your html to update.

Upvotes: 0

Kalpesh Patel
Kalpesh Patel

Reputation: 2822

Use else-if structure.

if($_POST['id']='link') {

}
else if($_POST['id']='contactperson') {

}

Upvotes: -1

Related Questions