2

I'm trying to send data to my local DB server but I keep getting 400 Bad request error when I try to send it.

var studentEmail = "ali@gmail.com";
            var dataString = '&questionNumber='+ temp + '&answer='+ value + '&email='+ studentEmail;


            $.ajax({
            type: "POST",
            dataType:'json',
            url: "js/dbcon.php",
            data: JSON.stringify(dataString),
            processData: false,
            contentType: "application/json; charset=utf-8"
            });

and this is the php file

<?php
$connection = mysql_connect("127.0.0.1", "root", "root"); // Establishing Connection with Server..
$db = mysql_select_db("db", $connection); // Selecting Database
//Fetching Values from URL
$questionNumber=$_POST['questionNumber'];
$answer=$_POST['answer'];
$email=$_POST['email'];
//Insert query
$query = mysql_query("INSERT INTO answers (questionNumber,studentAnswer,studentEmail) VALUES ($questionNumber,$answer,$email)");
echo "succesfully posted";
mysql_close($connection); // Connection Closed
?>

can anyone see what I'm doing wrong?

Thanks in advance!

faradji
  • 57
  • 2
  • 7
  • ps if I change POST to GET it works but doesnt insert the data to my DB – faradji Feb 23 '17 at 12:42
  • You're sure that dbcon.php is in the js folder? Seems rather strange... – markvdlaan93 Feb 23 '17 at 12:44
  • You must escape the string `@` is not valid inside a URL. – evolutionxbox Feb 23 '17 at 12:44
  • This is not good: You are not sending key-value pairs, so you will not get any data from `$_POST` on the server, you are not sending back json so your ajax call will never finish successfully, you have an sql injection problem and you use a deprecated mysql api. – jeroen Feb 23 '17 at 12:46
  • I made sure the php file is in the js folder – faradji Feb 23 '17 at 12:47
  • Every time you use [the `mysql_`](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) database extension in new code **[a Kitten is strangled somewhere in the world](http://2.bp.blogspot.com/-zCT6jizimfI/UjJ5UTb_BeI/AAAAAAAACgg/AS6XCd6aNdg/s1600/luna_getting_strangled.jpg)** it is deprecated and has been for years and is gone for ever in PHP7. If you are just learning PHP, spend your energies learning the `PDO` or `mysqli` database extensions and prepared statements. [Start here](http://php.net/manual/en/book.pdo.php) – RiggsFolly Feb 23 '17 at 12:48
  • Your script is at risk of [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Have a look at what happened to [Little Bobby Tables](http://bobby-tables.com/) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) – RiggsFolly Feb 23 '17 at 12:48

4 Answers4

1

JSON.stringify() method is used to turn a javascript object into json string.

So dataString variable must be a javascript object:

var data ={questionNumber:temp ,answer: value ,email:studentEmail};

AJAX

$.ajax({
    type: "POST",
    dataType:'json',
    url: "js/dbcon.php",
    data: JSON.stringify(data),
    processData: false,
    contentType: "application/json; charset=utf-8"
});
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
1

if you change the post to get you have to replace $_POST with $_GET into your php file.

Sudhanshu Jain
  • 494
  • 3
  • 11
1

There is an easier way to pass data that will work correctly for both POST and GET requests

var studentEmail = "ali@gmail.com";
$.ajax({
        type: "POST",
        dataType:'json',
        url: "js/dbcon.php",
        data: {questionNumber:temp, answer:value, email: studentEmail},
        processData: false,

});

Now jQuery does all the hard work and converts the object full of data to whatever format is required for a POST or GET request

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
1

You can send the ajax request this way:

var studentEmail = "ali@gmail.com";
            $.ajax({
            type: "POST",
            dataType:'json',
            url: "js/dbcon.php",
            data: ({'questionNumber':temp,'answer':value, 'email':studentEmail }),
            processData: false,
            contentType: "application/json; charset=utf-8"
            });

Also the PHP file needs to return a json string as well.

echo "succesfully posted";

is no valid json answer.

Return something like this:

$arr = array('success' => true, 'answer' => "succesfully posted");

echo json_encode($arr);

See also here: http://php.net/manual/de/function.json-encode.php

You should validate the input data, before inserting into the database.

dns_nx
  • 3,651
  • 4
  • 37
  • 66