nhpmi nhpmi - 1 year ago 45
Ajax Question

ajax doesn't work correct

What I miss?

1.php:

<button id = "testtext">Show</button>
<script src="jquery-3.1.1.min.js"></script>
<script src="js.js"></script>


js.js:

$("#testtext").bind("click", previewNewShortnameFunc);
function previewNewShortnameFunc() {
var lalalatext = "lalala";
var lalalaint = 100;
console.log("sent: " + lalalatext + " and " + lalalaint);
$.ajax ({
url: "testprint4.php",
type: "POST",
data : {str: lalalatext, int: lalalaint},
success: function(data) {
window.open("testprint4.php");
}
});
}


testprint4.php

<?php
$str = $_POST['str'];
$int = $_POST['int'];
echo $str;
echo $int;
?>


I see blank page instead of lalala100. What am I doing wrong?

Answer Source

This code includes two separate HTTP requests. You are first doing an Ajax request getting that response prior to redirecting user to request same script w/o any parameter, thus resulting in empty page.

$.ajax ({
    url: "testprint4.php",
    type: "POST",
    data : {str: lalalatext, int: lalalaint},
    success: function(data) {

    }
});

This part makes browser requesting the script with provided data as POST. When the response has been received it is available in data of callback linked with success-property. The request is finished then.

Instead of processing that response with your expected content you use

window.open("testprint4.php");

to open new window of browser for requesting same script again, this time using GET request w/o any argument. Therefore you will see a blank page.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download