Solved

query not executing when call by ajax

Posted on 2013-01-18
32
321 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
Comment Utility
Your php reads $_GET but your ajax call uses type:"POST".
0
 
LVL 82

Assisted Solution

by:leakim971
leakim971 earned 250 total points
Comment Utility
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
Comment Utility
Hi Guys

Done both changes still no go
0
 
LVL 16

Author Comment

by:Sheils
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
there is another inconsistency: fldate / flddate
0
 
LVL 35

Expert Comment

by:Robert Schutt
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
this is a new script?
0
 
LVL 16

Author Comment

by:Sheils
Comment Utility
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
Comment Utility
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 35

Expert Comment

by:Robert Schutt
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
The 3 goes into fldWithdrawingAccount, doesn't it?
0
 
LVL 16

Author Comment

by:Sheils
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Bingo, It's WORKING. Thanks guys
0
 
LVL 16

Author Closing Comment

by:Sheils
Comment Utility
Thanks Guys
0
 
LVL 82

Expert Comment

by:leakim971
Comment Utility
check back : ID: 38795388

:)
0
 
LVL 16

Author Comment

by:Sheils
Comment Utility
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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

763 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now