KyelJmD
KyelJmD

Reputation: 4732

Ajax Call with Post in PHP

<!doctype html>
<html>
<head>
  <title>jQuery Tagit Demo Page (HTML)</title>
  <script src="demo/js/jquery.1.7.2.min.js"></script>
  <script src="demo/js/jquery-ui.1.8.20.min.js"></script>
  <script src="js/tagit.js"></script>


  <link rel="stylesheet" type="text/css" href="css/tagit-stylish-yellow.css">

  <script>


    $(document).ready(function () {


    var list = new Array();
    var availableTags = [];

     $('#demo2').tagit({tagSource:availableTags});


     $('#demo2GetTags').click(function () {
        showTags($('#demo2').tagit('tags'))
      });

     /*
    $('li[data-value]').each(function(){
        alert($(this).data("value"));
    });*/

    $('#demo2').click(function(){
        $.ajax({
            url: "demo3.php",
            type: "POST",
            data: { items:list.join("::") },
            success: alert("OK")
        });
    });

    function showTags(tags) {


        console.log(tags);
        var string = "";
        for (var i in tags){
          string += tags[i].value+" ";
         }
          var list = string.split(" ");
          //The last element of the array contains " "
          list.pop();   
        }
    });
  </script>
</head>
<body>

<div id="wrap">
    <?php 

        $lis = $_POST['items'];
        $liarray = explode("::", $lis);
        print_r($liarray);

    ?>
<div class="box">
  <div class="note">
    You can manually specify tags in your markup by adding <em>list items</em> to the unordered list!
  </div>

    <ul id="demo2" data-name="demo2">
        <li data-value="here">here</li>
        <li data-value="are">are</li>
        <li data-value="some...">some</li>
        <!-- notice that this tag is setting a different value :) -->
        <li data-value="initial">initial</li>
        <li data-value="tags">tags</li>
    </ul>

  <div class="buttons">
    <button id="demo2GetTags" value="Get Tags">Get Tags</button>
    <button id="demo2ResetTags" value="Reset Tags">Reset Tags</button>
    <button id="view-tags">View Tags on the console </button>
  </div>
</div>

</div>
<script>
</script>
</body>
</html>

This code will just transfer the list of items in the dostuff.php but when I try to print_r it on PHP nothing won't come out. why is that?

I am doing an ajax request on this line

$('#demo2').click(function(){
            $.ajax({
                url: "demo3.php",
                type: "POST",
                data: { items:list.join("::") },
                success: alert("OK")
            });
        });

and the code in PHP

<?php 

        $lis = $_POST['items'];
        $liarray = explode("::", $lis);
        print_r($liarray);

    ?>

Upvotes: 1

Views: 479

Answers (4)

Richard de Wit
Richard de Wit

Reputation: 7452

3 things:

Set your AJAX's success to show the echos/prints given in your PHP script

success: function(result)
{
    $("#somecontainer").html(result);
}

That way ANYTHING that gets printed in a PHP script otherwise, will be put in i.e.

<div id="somecontainer">
    Result of PHPcode here
</div>

Second, instead of

var string = "";
for (var i in tags)
{
    string += tags[i].value+" ";
}

var list = string.split(" ");
//The last element of the array contains " "
list.pop();   

use push(). This adds the value at the next unoccupied index in the array:

var string = "";
for (var i in tags)
{
    list.push(tags[i].value);
}

That way you don't have to pop the last element off.


Third point: put your PHP code in a separate file (and your JavaScript/jQuery as well). Have like:

/root/index.html
/root/script/dostuff.php
/root/script/myscript.js

then let your AJAX call to url: "/script/dostuff.php"

Upvotes: 0

Daedalus
Daedalus

Reputation: 7722

This is just a shot in the dark, given the limited information, but it would appear that you're expecting something to happen with the data sent back from the server.. but you literally do nothing with it. On success, you have it display an alert... and nothing else.

Try changing your success entry to the following:

success: function(data) {
    $("#wrap").html(data);
}

This will fill the div with the data from the POST request. The reason it shows up as nothing as it is..., you aren't loading the currently executing page with the data needed for the print_r to actually echo anything.

Edit: How to insert values into database;

Database interaction now-a-days is done with either custom wrappers, or the php Data Object, also referred to as PDO, as opposed to the deprecated mysql_* functions.

First, you prepare your database object, similar to how a connection is done in the aforementioned deprecated functions:

$dbh = new PDO("mysql:host=hostname;dbname=database", $username, $password);

Then, you can begin interaction, preparing a query statement..

$stmt = $dbh->prepare("UPDATE table_name SET column1 = :column1 WHERE id = :id");

Binding a parameter in said statement..

$stmt->bindParam(':column1', $column1);
$stmt->bindParam(':id', $id);
$id = $_POST['id'];

And finally executing the query:

try {
    $stmt->execute();
}
catch (Exception $e) {
    echo $e;
}

PDO auto-escapes any strings bound in the prior statements, making it save from SQL-injection attacks, and it speeds up the process of multiple executions. Take the following example:

foreach ($_POST as $id) {
    $stmt->execute();
}

Since the id parameter is already bound to $id, all you have to do is change $id and execute the query.

Upvotes: 2

Marcel Kalveram
Marcel Kalveram

Reputation: 1305

Try to add encodeURI for the jQuery part,

$.ajax({
  url: "demo3.php",
  type: "POST",
  data: { items: encodeURIComponent (list.join("::")) },
  success: function(response) {
            console.log(response);
  }
});

And urldecode for the PHP part:

$lis = $_POST['items'];
$liarray = explode("::", urldecode($lis));
print_r($liarray);

Upvotes: 0

Jonathan Wilson
Jonathan Wilson

Reputation: 4295

Where where you expecting the PHP result of print_r to "come out"?

Try changing your AJAX call to this (only the value of success is different):

$.ajax({
    url: "demo3.php",
    type: "POST",
    data: { items:list.join("::") },
    success: function(data, textStatus, jqXHR){
        alert(data);
    }
});

With this, the output of your PHP template, which you would normally see if you posted to it the old fashioned way (ie. with a form and a full page reload), will display in an alert.

Hope that helps.

Upvotes: 0

Related Questions