Solved

query not executing when call by ajax

Posted on 2013-01-18
32
327 Views
Last Modified: 2013-01-19
I have a query that works fine when included in a php file but it does not trigger when call by the $.ajax method. The codes are as follows:

<script>

$( document ).ready(function() {

    $(".button").click(function() {

        var d=$("input#datepicker").val();
        var a=$("select#fldWithdrawingAccount").val();
        datastring="fldate=" + d + "&fldWithdrawingAccount=" + a;

                document.getElementById('test').innerHTML = datastring;

        $.ajax({

            type:"POST",
            url : "scripts/newTransaction.php",
            data: datastring,

            success: function() {
                alert ("Gatch Ya");
            },

            error : function() {
                alert("Sorry, there was a problem!");

            },

            complete : function() {
                alert("The request is complete!");
            }
        });

        return false;
    });

});

</script>

Open in new window


the php file is as follows:

<?php

if (isset ($_GET['send'])) {
    $Date = $_GET['flddate'];
    $WithdrawingAccount = $_GET['fldWithdrawingAccount'];

    $sql = "INSERT INTO `tbTransactions` (`fldDate`, `fldWithdrawingAccount`) VALUES (STR_TO_DATE('" . $Date . "', '%d %b %Y')," . $WithdrawingAccount . ")";
    mysqli_query($cnn, $sql) or die(mysqli_error($cnn));

}

?>

Open in new window


The form is as follows:

<?php

 	echo "<div id='newexpenses' class='mainformheader'>";
 	echo "<form class='mainform' method='' action=''>";
 	echo "<input type='hidden' name='navbutton' value='New Expenses'>";
 	echo "<div>Date:</div><input name='flddate'  id='datepicker'><br/>";
 	echo "<div>Type:</div><input id='fldtype' name='fldType'><br/>";
 	include "scripts/accountoptions.php";
 	echo "<div>Withdrawing Account:</div><select id='fldWithdrawingAccount' name='fldWithdrawingAccount'>" . $AccountsOption . "</select><br/>";
 	echo "<input type='submit' name='send' class='button' id='send' value='send' />";
    echo "<p id='test'></p>";
 	echo "</form>";
	echo "</div>";
 	mysqli_close($cnn);

 ?>

Open in new window


You can view the page at:

http://www.wowislandcharter.com/wowaccounts/index.php?navbutton=New+Expenses
0
Comment
Question by:Sheils
  • 13
  • 11
  • 8
32 Comments
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 38795218
Your php reads $_GET but your ajax call uses type:"POST".
0
 
LVL 82

Assisted Solution

by:leakim971
leakim971 earned 250 total points
ID: 38795237
replace line 9 :
datastring="fldate=" + d + "&fldWithdrawingAccount=" + a;

Open in new window

by:
datastring="send=&fldate=" + encodeURIComponent(d) + "&fldWithdrawingAccount=" + encodeURIComponent(a);

Open in new window

0
 
LVL 16

Author Comment

by:Sheils
ID: 38795255
Hi Guys

Done both changes still no go
0
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

 
LVL 16

Author Comment

by:Sheils
ID: 38795269
Guys

Data string does not include the send variable. So where would the send be coming from for the isset method? Could that be the problem
0
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 38795331
I gathered @leakim971 already caught that problem by including it in the datastring. Have you tried combining his fix with changing the ajax call type to "GET"?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38795332
you have a typo error
please do a new copy/past of the line I asked you to replace
0
 
LVL 16

Author Comment

by:Sheils
ID: 38795354
leakim971

fixed the typo, still no go

robert_schutt,

Yes I have fixed the GET. I intend to have it as post once it is working but change it to get when I was running the php test so I could see what it was return. Then forgot to change the ajax.
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38795362
could you try this new newTransaction.php :
<?php

if (isset ($_GET['send'])) {
    $Date = $_GET['flddate'];
    $WithdrawingAccount = $_GET['fldWithdrawingAccount'];

    $sql = "INSERT INTO `tbTransactions` (`fldDate`, `fldWithdrawingAccount`) VALUES (STR_TO_DATE('" . $Date . "', '%d %b %Y')," . $WithdrawingAccount . ")";
    mysqli_query($cnn, $sql) or die(mysqli_error($cnn));
echo $sql;

}

?>

Open in new window

0
 
LVL 16

Author Comment

by:Sheils
ID: 38795370
I have paste the new newTransaction.php  and no change observed. The echo $sql is not triggering
0
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 38795373
there is another inconsistency: fldate / flddate
0
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 38795380
to see the output from the ajax call you can use:
            complete : function(jqXHR, textStatus) {
                alert("The request is complete! " + jqXHR.responseText);
            }

Open in new window

instead of your current 'complete' event.
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38795388
Where is the part initializing the connexion with the database?
add this on the first line of your script : error_reporting(E_ALL);

<?php
error_reporting(E_ALL);

if (isset ($_GET['send'])) {
    $Date = $_GET['flddate'];
    $WithdrawingAccount = $_GET['fldWithdrawingAccount'];

    $sql = "INSERT INTO `tbTransactions` (`fldDate`, `fldWithdrawingAccount`) VALUES (STR_TO_DATE('" . $Date . "', '%d %b %Y')," . $WithdrawingAccount . ")";
    mysqli_query($cnn, $sql) or die(mysqli_error($cnn));
echo $sql;

}

?>

Open in new window

0
 
LVL 16

Author Comment

by:Sheils
ID: 38795398
robert I have made the change. No new observation

leakem

my connection is

<?php

$cnn = mysqli_connect("localhost","username","password","wowisla1_wowaccounts");
//mysqli_select_db("wowisla1_wowaccounts",$cnn);

 if (!$cnn)
  {
  die('Could not connect: ' . mysqli_error());

  echo "not connected";

  }

?>

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 38795401
this is a new script?
0
 
LVL 16

Author Comment

by:Sheils
ID: 38795404
No This is the connection to the db. I doubt if it is the problem because I am using this connection for all other forms and they are working fine
0
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 38795405
maybe try some more debugging in "newTransaction.php", before the "if(isset" part:
echo "1 - " . isset ($_GET['send']) . "\n";
echo "2 - " . $_GET['flddate'] . "\n";
echo "3 - " . $_GET['fldWithdrawingAccount'] . "\n";

Open in new window

0
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 38795418
So, I see those results on your page now. There's no sql error. If you still have no record, I'm not sure what's going on...
0
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 38795423
Hmm, strange by the way that the sql wasn't printed, maybe it dies after all.

One other option would be to echo the sql one line earlier and see if it works when you execute that exact sql manually in mysql?
0
 
LVL 16

Author Comment

by:Sheils
ID: 38795424
robert the echo still not working. Is it supposed to work noting that we are not opening the newTransaction.php page?

Guys,

I am now displaying the complete message. If you try entering something you may find the problem
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38795427
ID: 38795388 we don't get the "echo $sql"

wahta about :
<?php
error_reporting(E_ALL);

if (isset ($_GET['send'])) {
    $Date = $_GET['flddate'];
    $WithdrawingAccount = $_GET['fldWithdrawingAccount'];

    $sql = "INSERT INTO `tbTransactions` (`fldDate`, `fldWithdrawingAccount`) VALUES (STR_TO_DATE('" . $Date . "', '%d %b %Y')," . $WithdrawingAccount . ")";
echo $sql;
    mysqli_query($cnn, $sql) or die(mysqli_error($cnn));

}

?>

Open in new window

0
 
LVL 16

Author Comment

by:Sheils
ID: 38795456
Bingo,

$sql now echo. I have seen the problem, an extra value field. Not sure where it is coming from.

$sql is

INSERT INTO `tbTransactions` (`fldDate`, `fldWithdrawingAccount`) VALUES (STR_TO_DATE('09 Jan 2013', '%d %b %Y'),3)

I am having a look for the source of the number 3
0
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 38795457
we are not opening the newTransaction.php page
but we are: with the ajax call.

seems to show what we want but strange that it still doesn't work and doesn't show an error either.

If I forget for a moment that you stated that this worked when directly using the form submit, there seem a few likely candidates:
- table name tbTransactions still exists with these columns?
- date format
- field types
- constraints like foreign key on account type or unique indexes?

Actually that's why I asked if the exact sql as it is now reported, works when you execute that directly in mysql?
INSERT INTO `tbTransactions` (`fldDate`, `fldWithdrawingAccount`) VALUES (STR_TO_DATE('20 Jan 2013', '%d %b %Y'),1)

Open in new window

0
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 38795467
The 3 goes into fldWithdrawingAccount, doesn't it?
0
 
LVL 16

Author Comment

by:Sheils
ID: 38795468
Guy's

Looks like there is no problem with the sql. I cut and paste the sql that was echod into phpMyAdmin and it worked fine. This means that there must be some problem with my connection
0
 
LVL 16

Author Comment

by:Sheils
ID: 38795501
Guys,

I think that the problem is with the connection.

I will show you the codes for my page again maybe your shape tech eyes can spot something obvious.

Index page in the root folder

<?

require_once "scripts/toppart.php";

require_once "scripts/mainsidebar.php"; ?>

<div id='maindiv'><? include $formname?></div>

<? require_once "scripts/bottompart.php" ?>

Open in new window


toppart.php

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">

<html>
<head>
  <link rel="stylesheet" href="style/style.css" type="text/css">
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" type="text/css">
  <link rel="stylesheet" href="/resources/demos/style.css" type="text/css">
  <link rel="stylesheet" href="themes/jquery-ui-1.9.2.custom/jquery-ui-1.9.2.custom/css/custom-theme/jquery-ui-1.9.2.custom.css" type="text/css">
  <script src="http://code.jquery.com/jquery.js" type="text/javascript"></script>
  <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js" type="text/javascript"></script>
  <script type="text/javascript">
  $(function()

        {
            $("#datepicker").datepicker({dateFormat: "dd M yy", changeMonth: true, changeYear: true});

            $("#datepicker").attr('readOnly', 'true');

        }
    );
  </script>

  <title></title>
</head>

<body>

  <?php

      require "scripts/connect.php";
      include "scripts/switchpage.php";
      include "scripts/datainput.js";

  ?>

  <div id='headerdiv'>

    <p id='headertitle'><?echo $headertitle ?></p>

  </div>

Open in new window


$formname:frmNewTransaction.php
<?php

 	echo "<div id='newexpenses' class='mainformheader'>";
 	echo "<form class='mainform' method='' action=''>";
 	echo "<input type='hidden' name='navbutton' value='New Expenses'>";
 	echo "<div>Date:</div><input name='flddate'  id='datepicker'><br/>";
 	echo "<div>Type:</div><input id='fldtype' name='fldType'><br/>";
 	include "scripts/accountoptions.php";
 	echo "<div>Withdrawing Account:</div><select id='fldWithdrawingAccount' name='fldWithdrawingAccount'>" . $AccountsOption . "</select><br/>";
 	echo "<input type='submit' name='send' class='button' id='send' value='send' />";
    echo "<p id='test'></p>";
    echo "<p id='test2'></p>";
 	echo "</div>";
   
 	echo "</form>";
    
 	mysqli_close($cnn);

 ?>

Open in new window


datainput.js
<script>

$( document ).ready(function() {

    $(".button").click(function() {

        var d=$("input#datepicker").val();
        var a=$("select#fldWithdrawingAccount").val();
        datastring="send=&flddate=" + encodeURIComponent(d) + "&fldWithdrawingAccount=" + encodeURIComponent(a);
                document.getElementById('test').innerHTML = datastring;

        $.ajax({

            type:"GET",
            url : "scripts/newTransaction.php",
            data: datastring,

            success: function() {
                alert ("Gatch Ya");
            },

            error : function() {
                alert("Sorry, there was a problem!");

            },

            complete : function(jqXHR, textStatus) {
                document.getElementById('test2').innerHTML ="The request is complete! " + jqXHR.responseText;
            }
        });

        return false;
    });

});

</script>

Open in new window


NewTransaction.php
<?php

error_reporting(E_ALL);
echo "1 - " . isset ($_GET['send']) . "\n";
echo "2 - " . $_GET['flddate'] . "\n";
echo "3 - " . $_GET['fldWithdrawingAccount'] . "\n";

if (isset ($_GET['send'])) {
    $Date = $_GET['flddate'];
    $WithdrawingAccount = $_GET['fldWithdrawingAccount'];

    $sql = "INSERT INTO `tbTransactions` (`fldDate`, `fldWithdrawingAccount`) VALUES (STR_TO_DATE('" . $Date . "', '%d %b %Y')," . $WithdrawingAccount . ")";
echo $sql;
    mysqli_query($cnn, $sql) or die(mysqli_error($cnn));


}

?>

Open in new window



Should I include connect.php in NewTransaction.php or not close mysql in frmNewTransaction.php.
0
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 38795506
The weird thing of course still being no error shown, we might all be overlooking something wrong with that "sql() or die" part...?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38795507
Should I include connect.php in NewTransaction.php or not close mysql in frmNewTransaction.php.

yes you need to add/include the connection inside NewTransaction.php
0
 
LVL 35

Accepted Solution

by:
Robert Schutt earned 250 total points
ID: 38795513
The ajax call is a completely separate request. It can't use the connection from the request that generated the page it is on.
0
 
LVL 16

Author Comment

by:Sheils
ID: 38795524
Bingo, It's WORKING. Thanks guys
0
 
LVL 16

Author Closing Comment

by:Sheils
ID: 38795530
Thanks Guys
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38795535
check back : ID: 38795388

:)
0
 
LVL 16

Author Comment

by:Sheils
ID: 38795558
Sorry mate I did not figure out what you meant at the time. Yes could have saved a lot of stuffing around.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

791 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question