Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i have a simple ajax script that sends 3 variables to an external php script, it then adds them into an array and sends the array back, and i want it to output it in the javascript console, so that i can check that the variables are being passed back successfully, however when i run the script nothing appears in the console, only that

XHR finished loading: "http://localhost/blank/scripts/ajax/profile_password_submit.php". 

Here is the ajax

$("#pro_content_password").submit(function() {

    var url = "scripts/ajax/profile_password_submit.php"; // the script where you handle the form input.
    var js_array=new Array();
    $.ajax({
           type: "POST",
           url: url,
           data: $("#pro_content_password").serialize(), // serializes the form's elements.
           success: function(data){

                js_array=data;

                console.log(js_array);

             },
             dataType: 'json'
         });

    return false; // avoid to execute the actual submit of the form.
});

Here is the external php script

    session_start();
  include '../../connect.php';

  $user_id = "";
  $user_id = $_SESSION['userId'];
  echo $user_id;
 if(empty($_SESSION['userId'])){

     echo "user id session not set";
     exit;
  }


$old_password = $_POST['pro_content_password_old'];
$new_password = $_POST['pro_content_password_new'];
$new_password1 = $_POST['pro_content_password_verify'];


$password_array = array("old"=>$old_password,"new"=>$new_password, "new1"=>$new_password1);


echo json_encode($password_array);

Any ideas? Also i am using Google Chrome console

share|improve this question
 
Do you just need to do console.log instead of document.write? –  edmondscommerce Feb 4 at 22:30
 
Are you sure, that everything works correctly? Try to put "exit('ok');" as first row in your php file. Then open "Network tab" in Developers Tools and try to watch response of request. If there is your 'ok' then you can just try var_dump()... If not - let's see more. –  Danny Chernyavsky Feb 4 at 22:31
 
document.write does nothing as well, and i have passed other variables correctly with the script, just not arrays –  Arken Feb 4 at 22:34
 
ok, i tested the exit(ok) and it showed correctly, so it tried var_dump($password_array) and it showed the array correctly in some preivew section in the network area, so does that mean there is a problem in the javascript section? –  Arken Feb 4 at 22:39
add comment

3 Answers

It looks like you're not outputting a proper JSON object. I don't know for a fact, since you haven't shared what your PHP script is outputting, but I have a feeling that this line in that is what's causing your problem:

echo $user_id;

You're not just outputting a JSON encoded PHP array, you're also outputting the $user_id variable.

jQuery's ajax success callback only fires if it receives a properly formatted JSON object, which yours is not. It probably looks something more like this:

1234{"old": "oldpass", "new": "newpass", "new1": "newpass1"]

share|improve this answer
 
Hi, i commented out the echo of the user_id, but it still doesn't show in the array in the console, only in the network section of the developer tools in chrome –  Arken Feb 6 at 14:16
add comment

You need JSON.stringify :

$("#pro_content_password").submit(function() {

    var url = "scripts/ajax/profile_password_submit.php"; // the script where you handle the form input.
    var js_array=new Array();
    $.ajax({
           type: "POST",
           url: url,
           data: $("#pro_content_password").serialize(), // serializes the form's elements.
           success: function(data){

                js_array=JSON.stringify(data);

                console.log(js_array);

             },
             dataType: 'json'
         });

    return false; // avoid to execute the actual submit of the form.
});
share|improve this answer
 
that still shows nothing in the console log –  Arken Feb 4 at 22:40
 
it means that scripts/ajax/profile_password_submit.php isn't returning data. You can debug that in the Network tab, just click to expand the call and you should see data. –  Goran.it Feb 4 at 22:44
 
yeah i can see the correct array showing in the network tab when i var_dump the array in the php script, but what would be causing it to not display in the javascript? –  Arken Feb 4 at 22:45
 
Did you add header('Content-Type: application/json'); and outputed the data with : echo json_encode( $arr ); .. Note that the page shouldn't contain anything else, or it will broke JSON format –  Goran.it Feb 4 at 22:52
 
no i didn't add that in the header, and there is a lot of other code on the page as well like html, php etc... –  Arken Feb 4 at 22:54
show 4 more comments
up vote 0 down vote accepted

Here is the final working version now, its a lot different to my original but it works a lot better

    <script type="text/javascript">
function submit_profile_password(){
    //var results = document.getElementById("results");
    var result_error = document.getElementById("pro_content_error_password");
    var old_error = document.getElementById("pro_password_old_comment");
    var new_error = document.getElementById("pro_password_new_comment");
    var new1_error = document.getElementById("pro_password_new1_comment");

    var oldPass = document.getElementsByName("pro_content_password_old")[0].value;
    var newPass = document.getElementsByName("pro_content_password_new")[0].value;
    var new1Pass = document.getElementsByName("pro_content_password_verify")[0].value;
    var vars = "oldPass="+oldPass+"&newPass="+newPass+"&new1Pass="+new1Pass;

    var hr = new XMLHttpRequest();
    hr.open("POST", "scripts/ajax/profile_password_submit.php", true);
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
            var data = JSON.parse(hr.responseText);
            //results.innerHTML = "";

            for(var obj in data){
                if(obj == "old"){
                    old_error.innerHTML = "";
                    old_error.innerHTML = data[obj];

                }else if(obj == "new"){
                    new_error.innerHTML = "";
                    new_error.innerHTML = data[obj];

                }else if(obj == "new1"){
                    new1_error.innerHTML = "";
                    new1_error.innerHTML = data[obj];

                }else if(obj == "result"){
                    result_error.innerHTML = "";
                    result_error.innerHTML = data[obj];

                }

                //alert("Key = "+obj+"value = "+data[obj]+"");

            }
        }
    }
    hr.send(vars);
    //results.innerHTML = "requesting...";
    return false; 
}





</script>

Thanks all for the help

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.