kittu
kittu

Reputation: 7008

unable to post data using jquery ajax

I am able fetch the json data using the form below:

<form enctype="multipart/form-data" action="http://46.51.220.101/kookooapi/index.php/IVRSUploadFile/UploadFile" method="post">
    <input id="default_file" name="file" type="file" />
    <input id="account" name="account" type="hidden" value="testing"  />
    <input type="submit" value="Save">                               
</form>

but the same form when used with jquery ajax is throwing error: 501 (Not Implemented)

$('#default_file').change(function (e) {
    //on change event  
    formdata = new FormData();
    if ($(this).prop('files').length > 0)
    {
        file = $(this).prop('files')[0];
        formdata.append("music", file);
    }
});


function hitexternal(e) {
    $.ajax({
        url: "http://46.51.220.101/kookooapi/index.php/IVRSUploadFile/UploadFile",
        type: "POST",
        data: new FormData($("#default_file")[0], {data :{"account":"testing"}}),
        processData: false,
        contentType: 'application/json',
        success: function (response) {
            console.log('resp: ' , response);
        },
        error: function (jqXHR, textStatus, errorMessage) {
            console.log("error:" , errorMessage);
        }
    });
    e.preventDefault();
}

What did I miss here?

Upvotes: 2

Views: 2614

Answers (5)

Zasha
Zasha

Reputation: 52

Year 2020 update An Alternative answer to jquery $.ajax post method. After spending the whole night, I crafted my own solution used with a php script. I have tried everything, from $.post, $jqhr, $jqXHR but no luck

This scripts tells if an user exists. But this technique can used in other uses too.

jquery version 3.5 PHP version 7.4

I observed that the data doesn't gets sends to PHP, even upo using the $_GET in the php script, so the efficient way is to craft the url yourself and post it!

Javascript Code

    var email = $('#email').val();
    $.ajax({
            url: 'userexists.php?email='+email,
            method: 'POST',
            dataType:'text',
            contentType: 'application/x-www-form-urlencoded',
            data: {
              'email': email
            },

            // on success response
            success:function(response) {

              $("#result").html(response);

            },

            // error response
            error:function(e) {
              $("#result").html("Some error encountered.");
            }
          })

PHP Code

<?php
  require 'dbconfig.php';

  $email = $_GET['email'];
  $usr = "SELECT * FROM users WHERE email = '$email' ";
  $results = $connection->query($usr);



  if (mysqli_num_rows($results) == 0) { // if new user . Insert a new record
    echo "fresh";
    echo $email;
  } else {   // If Returned user . update the user record   
    echo "taken";
  }


  $connection->close();
  exit();


?>

Upvotes: 0

Hiren Patel
Hiren Patel

Reputation: 101

Hello Here is the answer please check


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<script>
    function savedata()
    {
        jQuery.post({
            url:"http://127.0.0.1/hk/ajaxpostaction.php",
            type:"POST",
            data:{"name":document.getElementById('username').value,"address":document.getElementById('address').value},
            success: function(response){
                alert("Post data : "+ result);
            },
            error: function(err){console.log('Error :  ' + err);}
        });
    }
</script>

</head>

<body>
    <form method="post">
            Name : <input type="text" id="username" name="username" />
            Address : <input type="text" id="address" name="address" />
            <input type="button" name="submit" onclick="savedata();" value="submit" />
    </form>
</body>
</html>

Thanks And Regards Hiren

Upvotes: 0

rajiv
rajiv

Reputation: 74

A 501 is HTTP status code for not implemented. This status code is received when the server does not support the facility required. I don't know if this is related, but generally when requesting JSON on the client to a server in a different domain you'll need to use JSONP instead of JSON due to the Same Origin Policy. The good thing is ,it doesn't appear that their API supports using JSONP. You can reffer these: How to mock a 501 error from ajax call Why do I get this 501 Not Implemented error? Post data into database via ajax. displays 501 internal error Enable ASP.NET ASMX web service for HTTP POST / GET requests http://www.computerhope.com/issues/ch001020.htm

Upvotes: 1

madalinivascu
madalinivascu

Reputation: 32354

Remove the content type FormData takes as input the form and converts it into key/value pairs

function hitexternal(e) {
    var formdata =  new FormData($("form")[0]);
    $.ajax({
        url: "http://46.51.220.101/kookooapi/index.php/IVRSUploadFile/UploadFile",
        type: "POST",
        data: formdata ,
        processData: false,
        contentType: 'multipart/form-data', // or set it as false to let jquery chose the right one for you
        success: function (response) {
            console.log('resp: ' , response);
        },
        error: function (jqXHR, textStatus, errorMessage) {
            console.log("error:" , errorMessage);
        }
    });
    e.preventDefault();

Upvotes: 2

Karthikeyan Sekar
Karthikeyan Sekar

Reputation: 333

 function hitexternal(e) {
        e.preventDefault();
        var fd=new FormData();  
        fd.append('image',$("#default_file")[0].files[0]);  
        fd.append('account','testing');
        $.ajax({
            url: "http://46.51.220.101/kookooapi/index.php/IVRSUploadFile/UploadFile",
            type: "POST",
            data: fd,
            processData: false,
            contentType: false,
            datatype:'JSON',
            success: function (response) {
                console.log('resp: ' , response);
            },
            error: function (jqXHR, textStatus, errorMessage) {
                console.log("error:" , errorMessage);
            }
        });

    }

Lets Try this code

Upvotes: 0

Related Questions