1

I am quite new to JS and PHP here. I am trying to teach myself.

I have been following the answer posted here however I can't get it to work in my project. Perhaps somebody could take a look at my code and give me some tips.

I have two pages;

  • chart.php (contains my datepicker)
  • eventsIn.php (contains my query)

In chart.php there is a date picker with startDate and endDate. These values should populate a query in my eventsIn.php page which in turn will send back some results.

However when I use console.log(response) in chart.php and var_dump($_POST) in eventsIn.php, I can see the following codes in the console:

Hooray, it worked!
ChartJson.php:119 
array(2) {
  ["startDate"]=>
  string(10) "2015-01-01"
  ["endDate"]=>
  string(10) "2015-03-01"
}
[] 

Looks like the data is being sent from the first page (chart.php), but nothing received from the second page (eventsIn.php) - would that be correct?

I presume the error lies in my code (perhaps the array?), which I have included below. I'd appreciate any help.

chart.php

<form method="post" id="search">
    <input type="text" placeholder="start" id="startDate" name="startDate">
    <input type="text" placeholder="end" id="endDate" name="endDate">
    <input type="submit" value="submit">
</form>

<script> 
$(document).ready(function () {

    var request;

    $("#search").submit(function (event) {

        // Abort any pending request  
        if (request) {
            request.abort();
        }
        // setup some local variables
        var $form = $(this);

        // Let's select and cache all the fields
        var $inputs = $form.find("input, select, button, textarea");

        // Serialize the data in the form
        var serializedData = $form.serialize();

        // Let's disable the inputs for the duration of the Ajax request.
        // Note: we disable elements AFTER the form data has been serialized.
        // Disabled form elements will not be serialized.
        $inputs.prop("disabled", true);

        request = $.ajax({
            url: "eventsIn.php",
            type: "post",
            data: serializedData
        });

        // Callback handler that will be called on success
        request.done(function (response, textStatus, jqXHR) {
            // Log a message to the console
            console.log("Hooray, it worked!");
            console.log(response);

            // Callback handler that will be called on failure
            request.fail(function (jqXHR, textStatus, errorThrown) {
                // Log the error to the console
                console.error(
                    "The following error occurred: " + textStatus, errorThrown);

                // Callback handler that will be called regardless
                // if the request failed or succeeded
                request.always(function () {
                    // Reenable the inputs
                    $inputs.prop("disabled", false);
                });

                // Prevent default posting of form
                event.preventDefault();
            });
        });
    });
}); //end dom ready
</script>

eventsIn.php

<?php 

var_dump($_POST);// for testing

if (isset($_POST['startDate'])) {
    $startDate = $_POST['startDate'];
    $endDate = $_POST['endDate'];
}

$stmt = $conn -> prepare("
    SELECT 
        MONTHNAME(TimeStamp), COUNT(*)
    FROM
        transactions
    WHERE
        TimeStamp BETWEEN (?) AND (?) 
    GROUP BY EXTRACT(MONTH FROM TIMESTAMP)");

$stmt->bind_param('ii', $startDate, $endDate);

$stmt -> execute();

$stmt -> store_result();

$stmt -> bind_result($month, $number);

$data = array();

while ($stmt -> fetch()) {
       $data[] = array(
        'month'  => $month,
        'number'  => $number
    );
}

echo json_encode($data);

$stmt->close();

?> 

If I change my query from TimeStamp BETWEEN (?) AND (?) to TimeStamp BETWEEN '2014-01-01' AND '2014-12-01' my eventsIn.php page produces an array (with a warning);

Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in C:\xampp\htdocs\sentryAdminV1\pages\eventsIn.php on line 23
array(12) { [0]=> array(2) { ["month"]=> string(7) "January" ["number"]=> int(323537) } [1]=> array(2) { ["month"]=> string(8) "February" ["number"]=> int(217304) } [2]=> array(2) { ["month"]=> string(5) "March" ["number"]=> int(289510) } [3]=> array(2) { ["month"]=> string(5) "April" ["number"]=> int(233258) } [4]=> array(2) { ["month"]=> string(3) "May" ["number"]=> int(505657) } [5]=> arra... ... etc

Would this indicate it has something do do with the prepared statement?

Community
  • 1
  • 1
jonboy
  • 2,729
  • 6
  • 37
  • 77
  • What if you `var_dump($data)` just before json_encode? Are you sure you don't have any sql error? –  Aug 25 '15 at 10:56
  • hi, best way to do this is to use good old firebug: Use Net tab so see exactly what response you are getting. Use Script tab to trace you js step by step and see what variables are populated. – Auris Aug 25 '15 at 10:57
  • just a question im not sure this might also be the answer arn't you passing a time stamp with "-" as a integer ? doesn't the posted data need to me converted to a unix time or something for it to be integer ? – Buddhi741 Aug 25 '15 at 10:58
  • Are you sure you don't have any sql error? That your query is working? You have to debug `eventsIn.php`. The issue comes from this part. –  Aug 25 '15 at 11:03
  • 1
    The warning comes from `$stmt->bind_param(...);`. As you wrote the dates directly in the query, you don't have any parameters to bind. It doesn't affect original code though. But in your test, you used these dates: `'2014-01-01' AND '2014-12-01'`, those are not the same as the one you are sending by post. You should test with the same data. –  Aug 25 '15 at 11:14
  • Either there is no bug (it is normal that your query return no result with these dates), either your query is wrong (in that case, please precise what you want it to do). ;) –  Aug 25 '15 at 11:21
  • Still not receiving a response in the console when I use different dates. In the console I see `Hooray, it worked! chart.php:119 array(0) { } []` – jonboy Aug 25 '15 at 11:22
  • in that case, please precise what you want the query to do –  Aug 25 '15 at 12:02
  • I want the query to return an array containing `month` and `number` based on the `startDate` and `endDate` provided. – jonboy Aug 25 '15 at 12:06
  • Think I've solved it, I was binding the params (ii) whereas they should have been (ss) - doh! I thought the date should have been integers and not string. – jonboy Aug 25 '15 at 14:25

3 Answers3

0

Hey @johnny_s you code looks good and working fine i got the below response

Hooray, it worked!
chart.php (line 42)

<pre>Array
(
    [startDate] => 2015-01-01
    [endDate] => 2015-03-01
)
</pre>

Its seems that there is not any prob with your code, try to check the php code by error_reporting and also check for the console log error that way I can help you. Check for the url's and the other variables.

Ashish Ranade
  • 595
  • 2
  • 14
  • please provide to the reason for downgrading the answer(whoever done this) else please do not rate if you don't know the answer, this is a kind of demoralizing the peoples. – Ashish Ranade Aug 25 '15 at 11:33
  • Thanks Ashish, I can also see that. However I need to pass these values into my query and echo them into the `echo json_encode($data);` part. I agree no reason for downvote. – jonboy Aug 25 '15 at 13:43
-1

you should use

var input = $("#search").serialize();

instead of

 var $inputs = $form.find("input, select, button, textarea");
 var serializedData = $form.serialize();
Drop Shadow
  • 845
  • 3
  • 12
  • 28
  • Thanks Drop Shadow for the tip, but unfortunately that doesn't resolve the issue. Will the way I have it not work? – jonboy Aug 25 '15 at 11:04
-1

write your form

<form name="myform" id="myform" method="get" action="">
 <input type="submit" onclick="return generateReport(this);" value="Submitt" />

And in your script

var generateReport = function(dom)
{
    var formData = $("#myform").serialize();
    $.ajax({
        url:'your_url',
        type:'post',
        data:formData,
        dataType:'json',
        success:function(data){

        },
        error:function(data){
        }
    });
    return false;
};
Drop Shadow
  • 845
  • 3
  • 12
  • 28