0

I am building a website that uses jQuery/AJAX to send data to a php page, and from there insert it into a database. For some reason, the code isn't inserted and I get no response at all.

my javascript:

    function insert_data(){
    var title = debate_title.value;
    var subtitle = debate_sub.value;
    var sides = debate_sides.value;

    $(function() {
        $.ajaxSetup({
            error: function(jqXHR, exception) {
                if (jqXHR.status === 0) {
                    window.location.replace('errors/noConnection.html');
                } else if (jqXHR.status == 404) {
                    window.location.replace('errors/noConnection.html');
                } else if (jqXHR.status == 500) {
                    window.location.replace('errors/noConnection.html');
                } else if (exception === 'parsererror') {
                    window.location.replace('errors/noConnection.html');
                } else if (exception === 'timeout') {
                    window.location.replace('errors/noConnection.html');
                } else if (exception === 'abort') {
                    window.location.replace('errors/noConnection.html');
                } else {
                    window.location.replace('errors/noConnection.html');
                }
            }
        });
    });

    $.ajax({
        type: "POST",
        url: "post_debate.php",
        data: { post_title: title, post_sub: subtitle, post_sides: sidesm, ajax: 1 },
        dataType: "json",
        timeout: 5000, // in milliseconds
        success: function(data) {
            if(data!==null){
                window.location.replace('show_debate.php?id=' + data);
            }else{
                window.location.replace('errors/noConnection.html');
            }
        }
    });
}

My PHP code (post_debate.php):

    <?php

    require('connect.php');

    $title = $_POST['post_title'];

    $subtitle = $_POST['post_sub'];

    $sides = $_POST['post_sides'];

    $ajax = $_POST['ajax'];

    $date = new DateTime();
    $timeStamp = $date->getTimeStamp();

    if($ajax==1){
        $query = mysql_query("INSERT INTO debates VALUES('','$title','$subtitle','$sides','0','0','$timeStamp')");
        $get_data = mysql_query("SELECT id FROM debates WHERE title='$title', subtitle='$subtitle', sides='$sides', timestamp='$timeStamp'");
        while($id=mysql_fetch_array($get_data)){
            $final_id = $id['id'];
        }
        exit($final_id);
    }else{
        die("404 SERVER ERROR");
    }

?>

Thanks!


EDIT - NOT SOLVED YET

My new PHP code:

<?php
header("content-type: application/json");

require('connect.php');

$title = $_POST['post_title'];

$subtitle = $_POST['post_sub'];

$sides = $_POST['post_sides'];

$ajax = $_POST['ajax'];

$date = new DateTime();
$timeStamp = $date->getTimeStamp();

if($ajax==1){
    $query = mysql_query("INSERT INTO debates VALUES('','$title','$subtitle','$sides','0','0','$timeStamp')");
    $get_data = mysql_query("SELECT id FROM debates WHERE title='$title', subtitle='$subtitle', sides='$sides', timestamp='$timeStamp'");
    while($id=mysql_fetch_array($get_data)){
        $final_id = $id['id'];
    }
    print (json_encode(array("Id"=>$final_id)));
}else{
    die("404 SERVER ERROR");
}

?>

my new Javascript .ajax:

    $.ajax({
    type: "POST",
    url: "post_debate.php",
    data: { post_title: title, post_sub: subtitle, post_sides: sides, ajax: 1 },
    dataType: "json",
    timeout: 5000, // in milliseconds
    success: function(data) {
        if(data!==null){
            window.location.replace('show_debate.php?id=' + data['Id']);
        }else{
            window.location.replace('errors/noConnection.html');
        }
    }
});
6
  • in success: function(data) try doing an alert(data) and post what is in data Commented Dec 14, 2012 at 15:19
  • 1
    Use your browser's development tools to check that there are no errors with your JavaScript code and that the AJAX request is being made. Commented Dec 14, 2012 at 15:29
  • Also, be aware you're using string concatenation to generate your SQL - what happens if any of your data fields contains an apostrophe? Anyone could run any code against your database. Remember Little Bobby Tables Commented Dec 14, 2012 at 15:29
  • Thanks @AnthonyGrist, i found a typo this way. But im still in some trouble - please look at the answer below (basic). Commented Dec 14, 2012 at 15:41
  • @arielschon12 I'm not a PHP programmer, so can't help you with any server-side code issues. I'd use the browser development tools again to check that the response you're actually sending is what you're expecting to be sent. Commented Dec 14, 2012 at 15:47

1 Answer 1

1

Your code is expecting JSON as a response...

dataType: "json",

(Documentation Here)

But you're returning a non-json value without an appropriate content-type header.

Try changing your PHP script from

   exit($final_id);

to (untested)

header("content-type: application/json");
print (json_encode(array(
        "Id"=>$final_id
    )));

Also, put a breakpoint on your success callback in your Javascript code (using Firebug or a similar tool) and examine what data contains. It should now be an associative array so you can do

window.location.replace('show_debate.php?id=' + data['Id']);

Improvement:

Instead of doing a SELECT to get the recently inserted Id, use mysql_insert_id(). Something like this...

$query = mysql_query("INSERT INTO debates VALUES('','$title','$subtitle','$sides','0','0','$timeStamp')");
$final_id = mysql_insert_id();
print (json_encode(array("Id"=>$final_id)));

Also, an alternate way to test what your PHP is returning if you can't see the response in your development tool is to browse to the page directly (You'd have to change all your $_POST to $_REQUEST)

Sign up to request clarification or add additional context in comments.

8 Comments

Ok, so i did this and now i can see that the data gets into my database. However, my success function gets a null data (moves to the else statement in the success) - so i get redirected to the wrong place! Why is this?
Ok, go to the "Net" tab in your debugger and look at the response coming from your script - is it Valid JSON with the correct headers?
I am using chrome and the javascript console.. How can i do this?
In Chrome on Windows, press F12 and one of the tabs should be "Network". If you're on a Mac, I think you can get the same by going to the console tab and finding the request
You're welcome - but look at my edited answer under "Improvement" - That whole step is redundant...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.