1

I need help of some advanced users of JSON and AJAX, because I need to use different content of messages in PHPMailer, so this work very well without JSON and AJAX, but I need to display successfull message to user when a form is submitted and can not understand why I get error "Requested JSON parse"?! So, this is part of php code with json.

    $sql_m = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM visitneum.owners_email INNER JOIN visitneum.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='rooms' AND `pages_id` = ?";
        
    $dbstmt = $pdo->prepare($sql_m);
    $dbstmt->bindParam(1,$pages_id);
    $dbstmt->execute();
    //get emails from db via pdo
    $emails_room_m = $dbstmt->fetchAll(PDO::FETCH_ASSOC);
    if(is_array($emails_room_m) && count($emails_room_m) > 0) {
        foreach ($emails_room_m as $email_room_m){
            $mailOwner->addAddress($email_room_m['email_address']);
                $body_room_m = "<p>Poštovani {$email_room_m['owner_name']}, <br>" . "Upravo ste primili poruku sa sajta <a href='https://www.visit-neum.com'>visit-neum.com</a><br>Detalji Vaše poruke se nalaze ispod:</p><p><strong>Od: </strong>" . ucwords($fname) . "<br><strong>Telefon: </strong>" . $tel . "<br><strong>Datum dolaska: </strong>" . $txtFrom . "<br><strong>Datum odlaska: </strong>" . $txtTo . "<br><strong>E-mail: </strong>" .strtolower($userMail)."<br><strong>Poruka: </strong>" . $userMessage . "<br><br><strong>Napomena: </strong>Molimo Vas da na ovu poruku ne odgovarate. Vaš odgovor pošaljite na: " . strtoupper($userMail) . "</p>";
                        $mailOwner->Body = $body_room_m;
 
    if($mailOwner->send()){
        $mailOwner = "INSERT INTO visitneum.contact_owner (fname, tel, txtFrom, txtTo, userMail, userMessage, email_address_id) VALUES (:fname, :tel, :txtFrom, :txtTo, :userMail, :userMessage, :email_address_id)";
        $stmt = $pdo->prepare($mailOwner);
        $stmt->execute(['fname' => $fname, 'tel' => $tel, 'txtFrom' => $txtFrom, 'txtTo' => $txtTo, 'userMail' => $userMail, 'userMessage' => $userMessage, 'email_address_id' => $email_room_m['email_address_id']]);
        if($error==false){
            $data["response"] = "success";
            $data["content"] = "Hvala Vam " . ucwords($fname) . "! Vaša poruka je uspješno poslata vlasniku objekta {$email_room_m['owner_property']}! Odgovor ćete dobiti ubrzo!";
        }//end if $error==false
    }//end if mail send

    }//end foreach for email addresses  (man owners of rooms)

    }//end if for array of emails

    // SELECT email values from database for woman owners of rooms
    $sql_f="SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM visitneum.owners_email INNER JOIN visitneum.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='F' AND `owner_type`='rooms' AND `pages_id` = ?";
    
    $dbstmt = $pdo->prepare($sql_f);
    $dbstmt->bindParam(1,$pages_id);
    $dbstmt->execute();
    //var_dump($dbstmt);
    //get emails from db via pdo
    $emails_room_f = $dbstmt->fetchAll(PDO::FETCH_ASSOC);
    if(is_array($emails_room_f) && count($emails_room_f) > 0) {
        foreach ($emails_room_f as $email_room_f){
            //var_dump($email_room_f['email_address']);
            $mailOwner->addAddress($email_room_f['email_address']);

                $body_room_f = "<p>Poštovana {$email_room_f['owner_name']}, <br>" . "Upravo ste primili poruku sa sajta <a href='https://www.visit-neum.com'>visit-neum.com</a><br>Detalji Vaše poruke se nalaze ispod:</p><p><strong>Od: </strong>" . ucwords($fname) . "<br><strong>Telefon: </strong>" . $tel . "<br><strong>Datum dolaska: </strong>" . $txtFrom . "<br><strong>Datum odlaska: </strong>" . $txtTo . "<br><strong>E-mail: </strong>" .strtolower($userMail)."<br><strong>Poruka: </strong>" . $userMessage . "<br><br><strong>Napomena: </strong>Molimo Vas da na ovu poruku ne odgovarate. Vaš odgovor pošaljite na: " . strtoupper($userMail) . "</p>";
                        $mailOwner->Body = $body_room_f;
 
    if($mailOwner->send()){
        $mailOwner = "INSERT INTO visitneum.contact_owner (fname, tel, txtFrom, txtTo, userMail, userMessage, email_address_id) VALUES (:fname, :tel, :txtFrom, :txtTo, :userMail, :userMessage, :email_address_id)";
        $stmt = $pdo->prepare($mailOwner);
        $stmt->execute(['fname' => $fname, 'tel' => $tel, 'txtFrom' => $txtFrom, 'txtTo' => $txtTo, 'userMail' => $userMail, 'userMessage' => $userMessage, 'email_address_id' => $email_room_f['email_address_id']]);
        if($error==false){
            $data["response"] = "success";
            $data["content"] = "Hvala Vam " . ucwords($fname) . "! Vaša poruka je uspješno poslata vlasniku objekta {$email_room_f['owner_property']}! Odgovor ćete dobiti ubrzo!";
        }//end if $error==false
    }//end if mail send
    }//end foreach for email addresses  (woman owners of rooms)
    }//end if for array of emails
    
    // SELECT email values from database for man owners of others property(restaurants, ships, etc)
    $query_m = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM visitneum.owners_email INNER JOIN visitneum.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
        
    $dbstmt = $pdo->prepare($query_m);
    $dbstmt->bindParam(1,$pages_id);
    $dbstmt->execute();
    //get emails from db via pdo
    $emails_other = $dbstmt->fetchAll(PDO::FETCH_ASSOC);
    if(is_array($emails_other) && count($emails_other) > 0) {
        foreach ($emails_other as $email_other){
            $mailOwner->addAddress($email_other['email_address']);
                $body_other = "<p>Poštovani {$email_other['owner_name']}, <br>" . "Upravo ste primili poruku sa sajta <a href='https://www.visit-neum.com'>visit-neum.com</a><br>Detalji Vaše poruke se nalaze ispod:</p><p><strong>Od: </strong>" . ucwords($fname) . "<br><strong>Telefon: </strong>" . $tel . "<br><strong>E-mail: </strong>" .strtolower($userMail)."<br><strong>Poruka: </strong>" . $userMessage . "<br><br><strong>Napomena: </strong>Molimo Vas da na ovu poruku ne odgovarate. Vaš odgovor pošaljite na: " . strtoupper($userMail) . "</p>";
                $mailOwner->Body = $body_other;
 
    if($mailOwner->send()){
        $mailOwner = "INSERT INTO visitneum.contact_owner (fname, tel, userMail, userMessage, email_address_id) VALUES (:fname, :tel, :userMail, :userMessage, :email_address_id)";
        $stmt = $pdo->prepare($mailOwner);
        $stmt->execute(['fname' => $fname, 'tel' => $tel, 'userMail' => $userMail, 'userMessage' => $userMessage, 'email_address_id' => $email_other['email_address_id']]);
        if($error==false){
            $data["response"] = "success";
            $data["content"] = "Hvala Vam " . ucwords($fname) . "! Vaša poruka je uspješno poslata vlasniku objekta {$email_other['owner_property']}! Odgovor ćete dobiti ubrzo!";
            }//end if $error==false
    }//end if mail send
    }//end foreach for email addresses  (man owners of other properties(restaurants, ships etc.))

}//end if for array of emails
else {
    $data['response'] = "error";
    $data['content'] = "Došlo je do greške! Pokušajte ponovo..." . $mailOwner->ErrorInfo;
    }
    echo json_encode($data);

And this is jQuery code with AJAX.

submitHandler: function(form) {
  //Your code for AJAX starts    
  var formData = jQuery("#contactOwner").serialize();
  console.log(formData);
  /*var data;
  if (typeof(data) == 'undefined') {
      JSON.parse(data);
    }*/
  jQuery.ajax({
    url: "./inc/mail_process.php",
    type: "post",
    dataType: ".json",
    contentType: "application/json",
    data: formData,
    cache: true,
    success: function(data) {
      //alert("success");
      jQuery("#responseOwner").text(data.content);
      //console.log(JSON.stringify(data));
      console.dir("Response: " + data.content);
    },
    /*error: function(data){
        //alert("error");
        jQuery("#responseOwner").text("An error occurred");
         console.dir("Response: "+data.content);
        //console.log(JSON.stringify(data));
        //console.log(xhr);
    }*/
    error: function(jqXHR, exception) {
      if (jqXHR.status === 0) {
        console.log('Not connect.\n Verify Network.');
      } else if (jqXHR.status == 404) {
        console.log('Requested page not found. [404]');
      } else if (jqXHR.status == 500) {
        console.log('Internal Server Error [500].');
      } else if (exception === 'parsererror') {
        console.log('Requested JSON parse failed.');
      } else if (exception === 'timeout') {
        console.log('Time out error.');
      } else if (exception === 'abort') {
        console.log('Ajax request aborted.');
      } else {
        console.log('Uncaught Error.\n' + jqXHR.responseText);
      }
    }


  }); //Code for AJAX Ends
  // Clear all data after submit
  var form = document.getElementById('contactOwner').reset();
  return false;
} //submitHandler
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Hi , why you have `.` here : `..: ".json"` ? Remove that dot and see if that works . – Swati May 03 '21 at 05:35
  • I was allready try, but after looking some video on youtube by Brad Traversy I was add dot, because he told that need use type with .json. However, thanks Swati for try to help me. Tell me please can I have multiple times $data['content'] with different content, how in my case, because when try to get error message this display me correctly error msg, and so make me confuse... – Mirnes Glamočić May 03 '21 at 05:51
  • You can create json array check [this](https://stackoverflow.com/questions/6739871/how-to-create-an-array-for-json-using-php) post should be helpful. – Swati May 03 '21 at 06:19

0 Answers0