简体   繁体   中英

PHP Script Does not Receive jQuery POST

First off, I'm a bit of a jQuery noob and a total PHP noob so I'm sorry if this is a stupid question (although I have searched the Internet and, specifically, this site up and down could not figure out what I'm doing wrong). Also, if you see any other mistakes/messy code, etc., don't hesitate to tell me :).

I'm trying to create a gallery where I have a previous and a next button. When you click previous, the src-attribute of the img-tag gets changed to the previous image via jquery and the same with the next buton and the next image. However, I want it to return to the last image when you press on the previous button and the current image is the first image. I need this to happen dynamically as I have several of these galleries with a different total number of pictures in them. Now, my current approach is (roughly):

  • Send a direction parameter from the clicked button to my image-toggle function (either "backward" or "forward")

  • Extract the image source's file path and post it to an external PHP script which then counts the number of files in that directory.

  • Check whether the direction parameter is forward. If yes, increment the number at the end of the current image's file name by one. If not, substract one (resulting in a non-existent file name). This new file name is assigned to the nextImage variable.

  • Check whether nextImage exists. If yes, assign it as the of the img src-attribute. If not, get the file count from the external PHP script, implement it into nextImage as the file number and then assign that to the src-attribute.

Most of this works. However, getting the last image when clicking previous on the first image doesn't. I have done some debugging and narrowed it down to the point where it seems to stop working. Firebug tells me that the jQuery POST function works (and I also got the success alert) and that it posts the data I want to the PHP file. However, inside the PHP script, the if (isset($_POST["id1"])) branch is never entered. It always goes straight to the else branch, even though I have basically copy-and-pasted the whole script from accepted answers on this site.

Here's the jQuery code:

var nextImageLength = " ";
var nextImage = " ";
var imageString = " ";
var nextImageStr = " ";
var nextImageNmb = 0;

var countImageLength = function($countimagelength) {
    nextImageLength = nextImageStr.length;
    if (nextImageLength < 3) {
        if (nextImageLength < 2) {
            nextImage = imageString + '00' + nextImageStr + '.jpg';
        }
        else {
            nextImage = imageString + '0' + nextImageStr + '.jpg';
        }
    }
    else {
        nextImage = imageString + nextImageStr + '.jpg';
    }
}

function multiPageToggle(direction) {
    var currentImage = $(".viewport_img_high").attr("src");
    imageString = currentImage.slice( 0, 35 );
    $.ajax(
            {
            type: "POST",
                url: "countImages.php",

                data: { id1: imageString},
                success: function (count) {
                    //alert('success');

            }
    });     
    var currentImageNmb = currentImage.slice(-7, -4);
    if (direction == "forward") {
        nextImageNmb = (parseInt(currentImageNmb)) + 1;
    }
    else {
        nextImageNmb = (parseInt(currentImageNmb)) - 1;
    }
    nextImageStr = nextImageNmb.toString();
    countImageLength();
    $.get(nextImage)
            .done(function() { 
                $(".viewport_img_high").attr("src", nextImage);
         }).fail(function() { 
                 if (nextImageNmb < 1) {
                $.get('countImages.php', function(count) {
                    nextImageStr = count;
                });
                countImageLength();
                $(".viewport_img_high").attr("src", nextImage);
            }
            else {
                nextImageStr = "1";
                countImageLength();
                $(".viewport_img_high").attr("src", nextImage);
            }
         });
}   

And this is my PHP script:

<?php
if (isset($_POST["id1"])) 
{
  $imgStr = $id1;
} 
else 
{
  $imgStr = "1";
  echo "Oops. Something went really wrong here.";
}
$imagePath = "c:/xampp/htdocs/portfolio/images2/" + $imgStr + "/";
$count = iterator_count(new DirectoryIterator($imagePath));
echo $count;
?>

EDIT: I'll add some Firebug data below. Maybe that can help make sense of this. Response Header:

Connection  Keep-Alive
Content-Length  77
Content-Type    text/html
Date    Tue, 15 Jul 2014 04:26:24 GMT
Keep-Alive  timeout=5, max=100
Server  Apache/2.4.7 (Win32) OpenSSL/1.0.1e PHP/5.5.9
X-Powered-By    PHP/5.5.9

Request Header:

Accept  */*
Accept-Encoding gzip, deflate
Accept-Language de,en-US;q=0.7,en;q=0.3
Cache-Control   no-cache
Connection  keep-alive
Content-Length  43
Content-Type    application/x-www-form-urlencoded; charset=UTF-8
Host    localhost
Pragma  no-cache
Referer http://localhost/portfolio/index_b.php
User-Agent  Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0
X-Requested-With    XMLHttpRequest

Response:

array(1) {
  ["id1"]=>
  string(35) "images2/des004_large_/des004_large_"
}
0

The line:

$imgStr = $id1;

should be:

$imgStr = $_POST['id1'];

vardump($_POST) to check all values on the array. If there's only a empty array your page isn't posting anything, else it will output all the contents of your post. Then start working around that: check all the indexes that are present and replace them in your code ;)

Okay, so I still don't know what was wrong but I simply rewrote the POST/GET parts of my jQuery script, as well as the PHP script from scratch and now it's working. Here's my new code in case anyone stumbles on this again in the future and has a similar problem. I replaced the POST-$.ajax function with this (also changed some the variables in the rest of my jQuery in the meantime so don't let that confuse you):

$.post( "test3.php", {a: imageStringSlice}, function(data) {
            //alert(data);
    count = data - 2;
});

The $.get with this:

nextImageStr = count.toString();
countImageLength();
$(".viewport_img_high").attr("src", nextImage);

And the PHP script with this:

<?php
if( $_REQUEST["a"] )
{
    $imgstr = $_REQUEST['a'];
    settype($imgstr, "string");
    $count = iterator_count(new DirectoryIterator($imgstr));
    echo $count;
}
else {
    echo "1";
}
?>

Thanks to Barmar and especially to gcarvalho97 for helping me out :)!

I am super late to this one, however I struggled with the same issue recently and could not find any help anywhere.

The simple answer is that PHP does not populate the $_POST if it does not recognize a form, however the input is still available.

when I post (in my case json data) through javascript, I get it back from php by using this:

$postbody = file_get_contents("php://input");

note that it is not equivalent of a post as it is not processed, so you may need to work a lot on this.

more information on stream wrappers is available here: [php manual on php input][ http://php.net/manual/en/wrappers.php ]

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