Bryan
Bryan

Reputation: 35

Sending JSON with AJAX to PHP

Good afternoon,

I am trying to send some values from a text form (made by Gravity Form) to a PHP file where I can then send those values to an API (Insightly). The reason for this is Insightly does not take AJAX calls.

The code I have is below, when I click the submit button I keep getting the "Failed To Send" error defined below, it never succeeds. So far I haven't finished my PHP scripting, I only have the following line:

$obj = $_POST['myData'];

I've been researching this issue for awhile now and still can't figure it out. Any assistance is greatly appreciated! Without further ado, here is the Javascript I have so far:

$(document).ready(function() {
$("#gform_submit_button_1").click(function() {
    var name = document.getElementById("input_1_19").value;
    // split name into first and last names
    var fname = name.split(" ")[0];
    var lname = name.split(" ")[1];
    var company = document.getElementById("input_1_15").value;
    var email = document.getElementById("input_1_6").value;
    var phone = document.getElementById("input_1_14").value;
    var hearAbout = document.getElementById("input_1_10").value;
    var solution = document.getElementById("input_1_11").value;
    var market = document.getElementById("input_1_17").value;
    var details = document.getElementById("input_1_5").value;

    var information =
    {
        "fname": fname,
        "lname": lname,
        "company":company,
        "email": email,
        "phone": phone,
        "hearAbout": hearAbout,
        "solution": solution,
        "market": market,
        "details": details
    };

var dataString = JSON.stringify(information);

    $.ajax({
        type: "POST",
        dataType: "json",
        url: "insightlyAPI.php",
        data: {myData: dataString},
        success: function(data){
            alert('AJAX Success!');
        },
        error: function(){
            alert('Failed To Send');
        }
    });
});
});

Upvotes: 1

Views: 196

Answers (1)

Borys Serebrov
Borys Serebrov

Reputation: 16172

The dataType parameter you pass to $.ajax call tell jQuery to expect data from the server:

"json": Evaluates the response as JSON and returns a JavaScript object. Cross-domain "json" requests are converted to "jsonp" unless the request includes jsonp: false in its request options. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown.

Try to return json from your PHP script, for example, add at the end:

echo json_encode(array());

Upvotes: 3

Related Questions