jquery function runs repeatedly instead of once when button pressed "onclick"

Hi,
This sounds like a strange problem which I shall describe the best I can.

I have the following Jquery which runs an sms-process.php script when the "Send Message" button is clicked. The script passes the mobile number and message values from a form to the sms-process page which then sends a text message.

It works well the first time I click the button, I receive a single text. If I leave the form open and enter a new number, when I click the button it sends 2 text messages (not one) and the 3rd time I send a text it sends 3  copies of the text message (not one).

Its as if it remember the number of previous button presses and sends this number of texts.
ie. if I send a text to Mr A first he receives 1 message
If I then send a different text to Mr B he received 2 copies of his message.
If I then send a different text to Mr C he received 3 copies of his message.   and so on...

The number of text messages received on mobile for each press = number of previous messages sent + 1

Can anyone explain why this happens?

echo '<script type="text/javascript" src="../includes/jquery-1.10.2.min.js"></script>
<script>
function process(){
$(document).ready(function(){
    $("#signal").click(function(){
      indata1 = $("#xinput").val();
      indata2 = $("#yinput").val();
        $.get("sms-process.php", {myNo:indata1 , myMes:indata2}, function(response){
            response = jQuery.parseJSON(response);
            document.getElementById("outMessage1").innerHTML = response;
            document.getElementById("sendsms").reset();
          }); 
     }); 
  });

}
</script>';

Open in new window

<input type="button" name="post_data" value="Send Message" id="signal" onclick="process()"/>

Open in new window


If I close the form and reopen it, the process starts again.
EICTAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Marco GasiFreelancerCommented:
You don't have to use $(document).ready within a function. Try this:
echo '<script type="text/javascript" src="../includes/jquery-1.10.2.min.js"></script>
<script>
function process(){
    $("#signal").click(function(){
      indata1 = $("#xinput").val();
      indata2 = $("#yinput").val();
        $.get("sms-process.php", {myNo:indata1 , myMes:indata2}, function(response){
            response = jQuery.parseJSON(response);
            document.getElementById("outMessage1").innerHTML = response;
            document.getElementById("sendsms").reset();
          }); 
  });

}
</script>';

Open in new window

0
Prakash SamariyaIT ProfessionalCommented:
It is executing twice because you have mentioned it two times
1. Inside the input tag => onclick="process()"/>
2. Inside the script =>  $("#signal").click(function(){

You can use any one either or to execute at once!!!

Hope this helps you!
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Mukesh YadavFull Stack DeveloperCommented:
Try this code:

<script>
function process(){
  indata1 = $("#xinput").val();
  indata2 = $("#yinput").val();
  $.get("sms-process.php", {myNo:indata1 , myMes:indata2}, function(response){
    response = jQuery.parseJSON(response);
    document.getElementById("outMessage1").innerHTML = response;
    document.getElementById("sendsms").reset();
  }); 
}
</script>';

Open in new window

0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

EICTAuthor Commented:
Thanks Marco. It still send multiple text message unless I close and reopen the form.
Not sure where to look for fix/test this.

I've included the sms-process.php script below.

<?php
session_start();
$staffid = $_SESSION['userid'];
$id = $_SESSION['client_id'];
$page_title = 'SMS Messenger';
require_once ('../../mysql_connect.php');  // Connect to the db.
  
require 'clockwork/class-Clockwork.php';

	  $number = $_GET['myNo'];
	  $locnumber = $number;
	  $intnumber = preg_replace('~^[0\D]++|\D++~', '', $number);
          $intnumber = '44'.$intnumber;	
	  $messageorig = $_GET['myMes'];		
	  $output = 'Failure - No Message Sent';
	   
          
    try
    {

    $API_KEY = '0342267b78b94440da6d8f06490883db8391d267';

        // Create a Clockwork object using your API key
       $clockwork = new Clockwork( $API_KEY );

       // Setup and send a message
       $message = array( 'to' => $intnumber, 'message' => $messageorig );
       $result = $clockwork->send( $message );

       // Check if the send was successful
        if($result['success']) 
        {
          $output = 'Message sent - ID: ' . $result['id'];
          
          $querylog = "INSERT INTO sms_log (clientcode, mobile, message, type, date, staffid) VALUES ('$id', '$locnumber', '$messageorig', 'Manual', NOW(), '$staffid')";
    $resultlog = mysqli_query($dbci,$querylog); //Run the 	   
            
          } else {
        $output = 'Message failed - Error: ' . $result['error_message'];
         }
    }
          catch (ClockworkException $e)
          {
         $output = 'Exception sending SMS: ' . $e->getMessage();
          }

   
echo json_encode($output,JSON_FORCE_OBJECT);
?>

Open in new window

0
Julian HansenCommented:
Further to the comments above - rather remove the onclick from your your input and instead just use the .click event handler in a document ready block like this

HTML
<input type="button" name="post_data" value="Send Message" id="signal" />

Open in new window

JQuery
// Analogous to $(document).ready(
$(function() {
    // Attach event handler to click on input
    $("#signal").click(function(e){
        // Disable default behaviour of button
        e.preventDefault();
        indata1 = $("#xinput").val();
        indata2 = $("#yinput").val();
        $.get("sms-process.php", {myNo:indata1 , myMes:indata2}, function(response){
            response = jQuery.parseJSON(response);
            document.getElementById("outMessage1").innerHTML = response;
            document.getElementById("sendsms").reset();
        }); 
    }); 
});

Open in new window

0
EICTAuthor Commented:
Thanks Prakash.
Spot on. That fixed it.
0
Julian HansenCommented:
Can you check your Console at the results of the GET - you need to look at the request headers in terms of what is being sent to the server.

Assumes FireFox + Firebug

1. Open the console with right click + Inspect Element
2. Trigger an action by clicking the button changing the input and clicking again
3. Open console tab
4. Click on GET request to see details
5. Click on Request tab to see what was sent to the server

If there are no duplicates there the problem is on the server.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JScript

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.