Search code examples
javascriptphpjqueryajaxhttp-status-code-400

400 bad request with Ajax


Hi I have tried everything possible here and have read through hundreds of search results,

I am getting a 400 error when I upload my code to a server, local on xampp it works just fine.

My goal is to just run the php file using ajax i have no need to post data but using post is the only way i have managed to get it to run savetodb.php Here is my code: specifically look at the success callback for ajax

<html>
<head>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script
        src="https://code.jquery.com/jquery-3.2.1.js"
        integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
        crossorigin="anonymous"></script>


    <link rel="stylesheet" type="text/css" href="style.css">
    <script>

        $( document ).ready(function() {
           var high = document.getElementById('high');
           var low = document.getElementById('low');
           var closing = document.getElementById('closing');
           var difference = document.getElementById('difference');
            getData();
        });
        function getData() {

            $.ajax({
                type: 'GET',
                url: 'https://api-fxpractice.oanda.com/v3/instruments/EUR_USD/candles?count=100',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer token goes here'
                },
                success: function(data){
                    $.ajax({
                        type: 'POST',
                        data: data.candles[0],
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        headers: {'Content-Type': 'application/json'},
                        url: 'savetodb.php',
                        success: function(){
                            console.log(data);
                        }
                    })
                }

            }).done(function(data) {
                var highNew = data.candles[0]['mid']['h'];
                var lowNew = data.candles[0]['mid']['l'];
                var closeNew = data.candles[0]['mid']['c'];
                var myArray = data.candles;

                var total = 0;
                var difftotal = 0;
                var diff = 0;
                for (var i = 0, l = data.candles.length; i < l; i++) {
                    total  += parseFloat(data.candles[i]['mid']['c']);
                    diff = data.candles[i]['mid']['h'] - data.candles[i]['mid']['l'];
                    difftotal += parseFloat(diff);
                }
                var diffAvg = difftotal / data.candles.length;
                var avg = total / data.candles.length;
                var dec = avg.toFixed(5)
                var dif = diffAvg.toFixed(10)


                high.innerHTML = highNew;
                low.innerHTML = lowNew;
                closing.innerHTML = dec;
                difference.innerHTML= dif;
            });
        }
        setInterval(getData,5000);

    </script>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-lg-12"><h1 class="title">EUR/USD</h1></div>

        <div  class="high alert alert-success col-lg-6">
        <span>HIGH</span>
            <span id="high">0.00000</span>
        </div>
        <div class="low alert alert-danger col-lg-6">
            <span>LOW</span>
            <span id="low">0.00000</span>
        </div>
        <div  class="average alert alert-info col-lg-12">
            <span>AVERAGE</span>
            <span id="closing">0.00000</span>
        </div>
        <div  class="average alert alert-info col-lg-12">
            <span>AVERAGE DIFFERENCE</span>
            <span id="difference">0.00000</span>
        </div>
    </div>
</div>
</body>
</html>

And savetodb.php is:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$ch = curl_init();
//
curl_setopt($ch, CURLOPT_URL,"https://api-fxpractice.oanda.com/v3/instruments/EUR_USD/candles?count=100");
curl_setopt($ch, CURLOPT_HTTPGET , 1);
//curl_setopt($ch, CURLOPT_POSTFIELDS,$vars);  //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$headers = [
    'Content-Type: application/json;charset=utf-8',
    'Authorization: Bearer token-cdf86287f59f25f0abf14e215a5b3cb1',
];

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$server_output = curl_exec ($ch);
$array = json_decode($server_output,true);
curl_close ($ch);

//print_r($array);
$h = array();
$l = array();
$avg = array();


$con=mysqli_connect("etc","etc","pass","db");

mysqli_query($con,'TRUNCATE TABLE prices');
// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}


foreach($array['candles'] as $item){
    mysqli_query($con,"INSERT INTO prices (low,high,close) VALUES ('".$item['mid']['l']."','".$item['mid']['h']."','".$item['mid']['c']."')");
}

mysqli_close($con);


?>


Solution

  • I fixed the 400 error by restructuring my second ajax call adding this as my success call for the first ajax request:

    success: function(data){
                        console.log('ajax success call begins');
                        $.ajax({ url: 'savetodb.php',
                            data: {action: 'test'},
                            type: 'post',
                            success: function(output) {
    
                            }
                        })
                    }

    And restructuring what was on the PHP page to look for the POST variable "action" like so

    <?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    
    if(isset($_POST['action']) && !empty($_POST['action'])) {
        $action = $_POST['action'];
        switch($action) {
            case 'test' : test();break;
        }
    }
    
    function test(){
     // stuff to do here
    }