Ethen
Ethen

Reputation: 171

javascript is not sending data through php code

Hi i have a requirement where i need to execute mysql queries once user will confirm Ok from confirmation box.In my case what ever data i am passing to insert_details.php is not working. one more thing i would like to bring to your notice that i need to send data to different script and navigate it to different page.kindly suggest where is the problem?

     <script type="text/javascript">
            var r=confirm("This email address already exits in our database. Do you want to continue?");
 if (r==true)
 {  
 var dataObj = {
    fname : document.getElementById('fname').value,                  
    phone : document.getElementById('phone').value,
    pemail : document.getElementById('email').value
}
        var xhr = new XMLHttpRequest();
      xhr.open("POST","insert_details.php", true);
      xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
      xhr.send(JSON.stringify(dataObj));

xhr.onreadystatechange = function() {
    if (xhr.readyState>3) {
        window.location = 'http://localhost/myproject/test.php?eid=<?php echo $primary_email; ?>';
    }
}

alert("test");



  }
else
  {
   window.location = 'http://localhost/myproject/registration_request.php'
   }

    </script>  

code in insert_details.php

$date = "Date:" . date("d/m/Y h:i:s") . "\n"; //to get today's date and time                  
        $logfile = "testing";
         $fpath ="myproject/";
        $filepath = $fpath .$logfile . '-log-' . date('Y-m-d') . '.csv';  //path of error log file

        $fh1 = fopen($filepath, 'a') or die("can't open file"); //opening the error log file 
        fwrite($fh1, "******************index*******************" . "\n");
        fwrite($fh1, $date); 


$test=json_decode(file_get_contents('php://input'));
fwrite($fh1, $test[0]); 

Upvotes: 0

Views: 128

Answers (1)

epascarello
epascarello

Reputation: 207501

You are not sending up a named pair. You are just sending up the value of the textbox.

what is looks like as a string.

xhr.send("[email protected]");

Second you have a race condition between the Ajax call and the window.location.href.

You need to wait for the response to come back before doing the redirection.

Basic idea:

var dataObj = {
    fname : document.getElementById('fname').value,                  
    phone : document.getElementById('phone').value,
    pemail : document.getElementById('email').value
}
xhr.onreadystatechange = function() {
    if (xhr.readyState>=3) {
        window.location = 'http://localhost/myproject/test.php?eid=<?php echo $primary_email; ?>';
    }
}
xhr.send(JSON.stringify(dataObj));

Upvotes: 2

Related Questions