Viewed   79 times

I keep getting the error alert. There is nothing wrong with the MYSQL part, the query gets executed and I can see the email addresses in the db.

The client side:

<script type="text/javascript">
  $(function() {
    $("form#subsribe_form").submit(function() {
      var email = $("#email").val();

      $.ajax({
        url: "subscribe.php",
        type: "POST",
        data: {email: email},
        dataType: "json",
        success: function() {
          alert("Thank you for subscribing!");
        },
        error: function() {
          alert("There was an error. Try again please!");
        }
      });
      return false;
    });
  });
</script>

The server side:

<?php 
$user="username";
$password="password";
$database="database";

mysql_connect(localhost,$user,$password);
mysql_select_db($database) or die( "Unable to select database");

$senderEmail = isset( $_POST['email'] ) ? preg_replace( "/[^.-_@a-zA-Z0-9]/", "", $_POST['email'] ) : "";

if($senderEmail != "")
    $query = "INSERT INTO participants(col1 , col2) VALUES (CURDATE(),'".$senderEmail."')";
mysql_query($query);
mysql_close();

$response_array['status'] = 'success';    

echo json_encode($response_array);
?>

 Answers

3

You need to provide the right content type if you're using JSON dataType. Before echo-ing the json, put the correct header.

<?php    
    header('Content-type: application/json');
    echo json_encode($response_array);
?>

Additional fix, you should check whether the query succeed or not.

if(mysql_query($query)){
    $response_array['status'] = 'success';  
}else {
    $response_array['status'] = 'error';  
}

On the client side:

success: function(data) {
    if(data.status == 'success'){
        alert("Thank you for subscribing!");
    }else if(data.status == 'error'){
        alert("Error on query!");
    }
},

Hope it helps.

Friday, August 12, 2022
5

Using the following code, I was able to upload the .obj file.

I had to increase my maximum upload size for it to work.

You may also think of increasing your maximum execution time as commented below, but I didn't have to.

For simplicity, I put everything in one file called form.php.

form.php

<?php
// good idea to turn on errors during development
error_reporting(E_ALL);
ini_set('display_errors', 1);

// ini_set('max_execution_time', 300);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
    echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
    echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
    echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
    echo "<b>Error:</b> " . $_FILES["file"]["error"] . "<br>";

    $sourcePath = $_FILES['file']['tmp_name'];          // Storing source path of the file in a variable
    $targetPath = "uploads/" . $_FILES['file']['name'];    // Target path where file is to be stored
    if (move_uploaded_file($sourcePath, $targetPath)) { // Moving Uploaded file
        echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
    } else {
        echo "<span id='success'>Image was not Uploaded</span><br/>";
    }
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>
<body>
    <form action="form.php" method="post" enctype="multipart/form-data">
        <label>File</label>
        <input type="file" name="file">
        <input type="submit" value="Upload"> 
    </form>
    <div></div>
</body>
<script>
$(function () {
    $('form').on('submit', function (e) {
        e.preventDefault();
        // logic
        $.ajax({
            url: this.action,
            type: this.method,
            data: new FormData(this), // important
            processData: false, // important
            contentType: false, // important
            success: function (res) {
                $('div').html(res);
            }
        });
    });
});
</script>
</html>

So, first test to see if you can upload the .obj file using the code above.

As you are testing it out, have your browser's developer tool open. Monitor your Network/XHR tab [Chrome, Firefox] to see the request that gets made when you click Upload.

If it works, try using the same logic in your original code.

var formData = new FormData();
formData.append('file', result);   

$.ajax({
    url: "ExecuteMaya.php",
    type: "post",
    data: formData, // important
    processData: false, // important
    contentType: false, // important!
    success: function (res) {
        console.log(res);
    }
});

Again, monitor the request made in your Network/XHR tab and look at what is being sent.

Wednesday, November 2, 2022
 
2

I have worked with translations in my CMS and many times i require specific strings to be used in an otherwise static plain text as a javascript file. What i do:

en.php

return array(
   "id1"=>"translation 1",
   "id2"=>"translation 2"
);

HTML

...
$trans = require("en.php");
...
<input type="hidden" id="trans" data-trans='<?php echo json_encode($trans); ?>' />
...

JS

$(document).ready(function() {
   var id1 = $("#trans").data("trans")["id1"];   // contains the 'id1' string
});

This way your javascript would not need changing, which results many times in history caching related problems for your clients, as they need refreshing.

Sunday, October 2, 2022
 
dawid
 
1

you can use following code :

var form = new FormData($('#form_step4')[0]);
form.append('view_type','addtemplate');
$.ajax({
    type: "POST",
    url: "savedata.php",
    data: form,
    cache: false,
    contentType: false,
    processData: false,
    success:  function(data){
        //alert("---"+data);
        alert("Settings has been updated successfully.");
        window.location.reload(true);
    }
});

where savedata.php is the file name in which you can do the the DB things

Friday, December 16, 2022
 
2

One way is to wrap m.request in another function that returns both the completion state (based on a flag that you set via the m.request promise chain), and the data, and then use the background: true option to prevent the deferral of the redraw, and also bind m.redraw to the promise chain in order to have redrawing happen after the request.

This was originally described here: https://github.com/lhorie/mithril.js/issues/192

var requestWithFeedback = function(args) {
  var completed = m.prop(false)
  var complete = function(value) {
    completed(true)
    return value
  }
  args.background = true
  return {
    data: m.request(args).then(complete, complete).then(function(value) {
      m.redraw()
      return value
    }),
    ready: completed
  }
}

var MyController = function() {
  this.things = requestWithFeedback({method: "GET", url: "/things"})
}
var myView = function(ctrl) {
  return !ctrl.things.ready() ? m("img[src=loading.gif]") : m("ul", [
    ctrl.things.data().map(function(thing) {
      return m("li", thing.name)
    })
  ]) 
}

m.module(document.body, {controller: MyController, view: myView})
Sunday, August 28, 2022
 
guyik
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :