-1

I need to get a JSON response for each successfully sent message. I can send the SMS successfully but I can't get a success message from send_sms.php

<!-- index.php --->
<div id="responce"></div> <!-- respond sms sending -->
<form method="POST" onclick="return false">
<div class="form-group">
    <label>Your Message</label>
<textarea class="form-control" rows="4" cols="100" id="message"
name="message" maxlength="70" required></textarea>
</div>
<button class="btn btn-primary" type="submit" name="submit"
onmousedown="start_sendig();" class="btn">Send</button>
</form>

enter image description here

//sendsms_button.js

function start_sendig() {
  $("#responce").html("Please wait sending on process");
  var message = $("#message").val();
  var path_uri = "sms/send_sms.php";

  $.ajax({
    type: "POST",
    url: path_uri,
    data: {
      message: message,
    },
    success: function (data) {
      var json = $.parseJSON(data);

      if (json.response == "success") {
        $("#responce").html(
          "Message Sent Successfully to " + json.current + " !!"
        );
      } else {
        $("#responce").html("Error to Sent " + json.current + " !!");
      }
    },
  });
}

Ajax shows this error

 caught SyntaxError: Unexpected end of JSON input
    at Function.parse [as parseJSON] (<anonymous>)
    at Object.success (sendsms_button.js:13:20)
    at i (jquery-3.2.1.min.js:2:28017)
    at Object.fireWith [as resolveWith] (jquery-3.2.1.min.js:2:28783)
    at A (jquery-3.2.1.min.js:4:14035)
    at XMLHttpRequest.<anonymous> (jquery-3.2.1.min.js:4:16323)

<?php
//send_sms.php
   
include ("vendor/autoload.php");
include ("../config.php");

//insert record
$msg_sms = $_POST['message'];
mysqli_query ($con, "insert into sent_sms (message) values ('$msg_sms')");
if (isset($_POST['submit'])){
//select numbers
$result = mysqli_query($con, "SELECT mphone FROM members");
while ($row = mysqli_fetch_array($result)){
$numbers = $row['mphone'];

    foreach (explode("+", $numbers) as $phone) {
    $basic  = new \Vonage\Client\Credentials\Basic("fxxxxx", "xxxxxxxxxxxxx");
    $client = new \Vonage\Client($basic);

    $response = $client->sms()->send(
    new \Vonage\SMS\Message\SMS($phone, 'Hotel', $msg_sms)
    );

    $message = $response->current();

        if ($message->getStatus() == 0) {
            $data = array(
                    "response" => "success",
                    "current" => '+' . $phone
                );

                echo json_encode($data);
        } else {
        echo "<script>alert('The message failed with status: " . $message->getStatus() . "');</script>";
        }
    }
}

}
   
 
?>

my goal is to show each success message like Sending to +125332626 success

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 2
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman Apr 23 '23 at 00:05

1 Answers1

0
  • echoing echo json_encode($data); in loop it makes problems .. saving it in an array then echo the whole array out after the loop
  • return <script> its not a good idea .. the good way is to return the error as an encode json then check for it on ajax success function

-First We'll assume that your php code and mysql connection working fine..

-Second in your ajax you'll need to add dataType : "json"..

-Third Also you need to check for isset($_POST['message']) instead of isset($_POST['submit'])

function start_sendig() {
  $("#responce").html("Please wait sending on process");
  var message = $("#message").val();
  var path_uri = "sms/send_sms.php";

  $.ajax({
    type: "POST",
    url: path_uri,
    dataType : "json",  // <<<<<<<<<<<<<<<
    data: {
      message: message,
    },
    success: function (data) {
      if(data.error){   // <<<<<<<<<<<<<<<
         console.log(data.error);
      }else{
         console.log(data);
      }
    },
  });
}

In php

<?php
   include ("vendor/autoload.php");
   include ("../config.php");
   if (isset($_POST['message'])){
     //insert record
     $msg_sms = $_POST['message'];
     mysqli_query ($con, "insert into sent_sms (message) values ('$msg_sms')");
    //select numbers
    $result = mysqli_query($con, "SELECT mphone FROM members");
    $returned_JSON = []; //<<<<<<<<<<<<<<<<<<<<<<<
    while ($row = mysqli_fetch_array($result)){
    $numbers = $row['mphone'];
        foreach (explode("+", $numbers) as $phone) {
        $basic  = new \Vonage\Client\Credentials\Basic("fxxxxx", "xxxxxxxxxxxxx");
        $client = new \Vonage\Client($basic);
    
        $response = $client->sms()->send(
        new \Vonage\SMS\Message\SMS($phone, 'Hotel', $msg_sms)
        );
    
        $message = $response->current();
    
            if ($message->getStatus() == 0) {
                $data = array(
                        "response" => "success",
                        "current" => '+' . $phone
                    );
    
                    $returned_JSON[] = $data; //<<<<<<<<<<<<<<<<<<<<<<<
            } else {
                $returned_JSON['error'] = $message->getStatus(); //<<<<<<<<<
            }
        }
    }
    echo json_encode($returned_JSON); //<<<<<<<<<<<<<<<<<<<<<
    }
       
     
    ?>

Note: There're alot of reasons can make an errors while using ajax .. I gave you some code for guide and to let you know how to thinking and coding about it .. But you've to check ajax/php connection step by step to know exactly what is working and what is not.

Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
  • First of all thank you very much, I try like you said but still, I did not get "success" response from $data. PHP, MySqli, and SMS work fine I just need which number is a fail and success above form – dagemawi alemayhu Apr 23 '23 at 22:04