I'm playing around a little with Ajax and i'm using the following code.
var r = new XMLHttpRequest();
r.open("POST", "pythonTesting.php", true);
r.onreadystatechange = function () {
if (r.readyState === 4 && r.status === 200) {
alert("Success: " + r.responseText);
}
};
r.send("text=yellow");
It is successful but the alert isn't showing the actual responseText.
pythonTesting.php (not to be confused by the name) is just:
<?php
echo $_POST['text'];
?>
I'm expecting the responseText to be yellow because that's how I sent it but its not. I'm not really seeing what the problem is though. It must be one of those easy to fix mistakes.
from http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp:
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
Since this is a post I believe you will need to set the length:
r.setRequestHeader("Content-length", "text=yellow".length);
send the variables through the address:
r.open("POST", "pythonTesting.php?text=yellow", true);
then retrieve the variable in php by
$text = $_REQUEST['text'];
Related
I'm new in programming and API and I want to know how can I redirect to the URL sent by an API Response like below, please take note that the merchantURL changes everytime a customer submit new transaction.
decision = ACCEPT
reasonCode = 100
requestID = 5199043764236716204011
requestToken = AhjnrwSTGdc55dvfMd/rmBles0iRokq1GiOZKW+XDR/x6Q27g++QyaSZbpAcCSAkxnXOeXb3zHf6wAAAAQqe
apSaleReply->reasonCode = 100
apSaleReply->merchantURL = https://www.sofort.com/payment/go/3e54e5e50b5114f5c11ef40b2d45dbb7a4d808b3
This is how I requested the merchantURL:
printf( "apSaleReply->merchantURL = " . $reply->apSaleReply->merchantURL . "<br>");
and I have an IF statement that if the reason code is equal to 100 then it will redirect to the URL:
if ($reply->reasonCode == 100){
?>
<script>
window.location.href = "";
</script>
<?php
}
This is already working if I input any URL, I'm only stuck on how to get the value of the merchantURL since it is always changing and specify it in the window.location.href.
Hope you can help me out! Thank you in advance!
You can use php header
header("Location: " . $reply->apSaleReply->merchantUR );
Or you can alter your existing code as below to get this work
if ($reply->reasonCode == 100){
?>
<script>
window.location.href = "<?php echo $reply->apSaleReply->merchantUR; ?>";
</script>
<?php
}
What about this?
window.location.href = "<?= $reply->apSaleReply->merchantURL ?>";
(I assume your template and back-end code is in the same file, otherwise use a session data. Let me know if it's the case.)
I am a beginner and I am trying to echo arrays and append them into a html division i created. The AJAX call I made was successful but the response was not appearing inside the division i assigned it to. Upon further inspection, I found out that the response I have received has an array length over 600 ( I am expecting 10 records). So there must be something wrong with my echo PHP file or the receiving end of the HTML file but just cannot figure out what that is.
Here are my codes:
listdiscount.php
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "root", "root", "bencoolen");
$userid = $_GET['userid'];
$result = $conn->query("select userid, codename from discountcode where userid ='" . $userid . "' ");
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
printf("Userid: %s '' Codename: %s", $row["userid"], $row["codename"]);
}
$conn->close();
?>
index.html ( with js codes )
<html>
<script>
function mydiscount(){
var userid = "jimmy";
var xmlhttp = new XMLHttpRequest();
var url = serverURL() + "/listdiscount.php";
url += "?userid=" + userid;
alert(url);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert("readystate=4 and status =200");
mydiscountresult(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function mydiscountresult(response) {
var arr = response;
alert(arr); //alerted
alert(arr.length); //alerted 600+ arrays
alert("mydiscountresult working"); //alerted
var i;
$("#discountcontent").empty();
for(i = 0; i < arr.length; i++) {
$("#discountcontent").append("<b>" + arr[i].userid + "</b>"+ arr[i].codename + "<hr>");
}
}
mydiscount();
</script>
<div data-role="content" class="ui-content" id="discount">
LIST OF DISCOUNT CODE:<br>
<div id="discountcontent" class="ui-grid-solo">
</div>
</div>
</html>
Here is what my response look like when alerted:
addition note: my php files are in different folder so serverurl() is declared and used here.
the get request returns a json array so you need to convet it in to normal array using json parse. you may please change the line of code as
mydiscountresult(JSON.parse(xmlhttp.responseText));
It will work fine.
The Function xmlhttp.responseText retun a String, right?
You gave this string into function mydiscountresult and copy it into variable var. It is still a string, isn't it?
So the alerts work fine and do there jobs on the string (length 600 and so on)
Then you walk over this string letter by letter (this is what your for-loop is doing). On every letter var[i] you try to read a property userid. I think no normal letter (calld char) hav a property called userid. So this result in an empty string.
I think you would like to get the array from the string xmlhttp.responseText. To do so you just let JSON parse this string and it gave you an Object.
JSON.parse(xmlhttp.responseText)
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Im trying to send a string to a php server, but for some reason, Im not able to read the string on the server... I tried many ways to type it well but it seems like I never got the correct syntax. Anyone have clues?
var command="";
if(document.getElementById("Text_1").value != "" && document.getElementById("Text_2").value != "")
{
command += " " + document.getElementById("Text_1").value + " " + document.getElementById("Text_2").value;
}
alert(command);
xmlhttp.open("POST", "server.php", false);
xmlhttp.setRequestHeader('info', command)
//TRIED xmlhttp.setRequestHeader("info, command")
//TRIED xmlhttp.setRequestHeader('info', 'command')
//TRIED many others sketchy things...
xmlhttp.send();
//TRIED xmlhttp.send(command);
var output = xmlhttp.responseText;
On php server :
<?php
$parameter = $_POST['command'];
$output = exec("someexecutable.exe $parameter");
echo json_encode($parameter);
?>
For them wondering, if I hardcode $parameter with a right string, it works, so the executable isn't the problem. The server just cant get the value of the string in $_POST.
setRequestHeader is used to set headers on the request. Things like Content-type and Content-length.
You need to pass the data to send(). For $_POST to work, they need to be in key=val&vey2=val2 format. Actually, in newer browsers, you can use FormData.
xmlhttp.open("POST", "server.php", false);
// To emulate a `<form>` POST
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// To get the response, you need to set a callback
xmlhttp.onreadystatechange = function(){
// readyState 4 = complete
// status = 200 OK
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
var output = xmlhttp.responseText;
}
};
// Create the Form Data
var params = new FormData;
params.append('command', command);
xmlhttp.send(params);
P.S. You should run escapeshellarg() before running your command. This could be worse than just SQL injection if people can run arbitrary commands on your server.
<?php
$parameter = escapeshellarg($_POST['command']);
$output = exec("someexecutable.exe $parameter");
?>
P.P.S. escapeshellarg() will make your command treat the entire $_POST['command'] string as one parameter. If you don't want that, then you'll need to POST an array from your JavaScript.
// Create the Form Data
var params = new FormData;
params.append('command[]', document.getElementById("Text_1").value);
params.append('command[]', document.getElementById("Text_2").value);
xmlhttp.send(params);
Now $_POST['command'] will be an array, so you'll have to run the command like so:
<?php
$parameters = array_map('escapeshellarg', $_POST['command']);
$output = exec("someexecutable.exe ".implode(' ', $parameters));
?>
I wanted to post this online because I have been searching for days on this JQuery Remote validation issue. I cannot get it to work. I think my PHP code is correct as I have test the URL with a query in the URL and it returns false and true depending on with the recordset count is one or more
This is my Jquery Validate Code:
// validate form and submit
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j("#myform").validate({
rules: {
ord_ref: {
required: true,
minlength: 12,
remote: "check_ord_ref.php"
},
messages: {
ord_ref: {
remote: "Order Number Does Not Exist"
}
}
}
});
});
This is my PHP code for the remote page "check_ord_ref.php"
$colname_rscheck_ord_ref = "-1";
if (isset($_GET['ord_ref'])) {
$colname_rscheck_ord_ref = (get_magic_quotes_gpc()) ? $_GET['ord_ref'] : addslashes($_GET['ord_ref']);
}
mysql_select_db($database_conn, $conn);
$query_rscheck_ord_ref = sprintf("SELECT ref_ord FROM orders WHERE ref_ord = '%s'", $colname_rscheck_ord_ref);
$rscheck_ord_ref = mysql_query($query_rscheck_ord_ref, $conn) or die(mysql_error());
$row_rscheck_ord_ref = mysql_fetch_assoc($rscheck_ord_ref);
$totalRows_rscheck_ord_ref = mysql_num_rows($rscheck_ord_ref);
if($totalRows_rscheck_ord_ref < 0){
$valid = 'false';
} else {
$valid = 'true';
}
echo $valid;
Please someone can you help solve the puzzle for myself and anyone else having issues
Using JQuery 1.5.2min
Validates OK without remote function
Ok, so I'm no PHP expert, but I do know that jQuery Validate expects the following result from a remote validation method:
The response is evaluated as JSON and must be true for valid elements,
and can be any false, undefined or null for invalid elements
Sending down "true" or "false" (note the quotation marks) is going to result in the value being parsed as the error message instead of being evaluated as a boolean primitive.
Back to the PHP part, I think you should probably use json_encode with a boolean primitive. I'm not quite sure the way to do this in PHP, but I believe it would be something like this:
$colname_rscheck_ord_ref = "-1";
if (isset($_GET['ord_ref'])) {
$colname_rscheck_ord_ref = (get_magic_quotes_gpc()) ? $_GET['ord_ref'] : addslashes($_GET['ord_ref']);
}
mysql_select_db($database_conn, $conn);
$query_rscheck_ord_ref = sprintf("SELECT ref_ord FROM orders WHERE ref_ord = '%s'", $colname_rscheck_ord_ref);
$rscheck_ord_ref = mysql_query($query_rscheck_ord_ref, $conn) or die(mysql_error());
$row_rscheck_ord_ref = mysql_fetch_assoc($rscheck_ord_ref);
$totalRows_rscheck_ord_ref = mysql_num_rows($rscheck_ord_ref);
if($totalRows_rscheck_ord_ref < 0){
$valid = false; // <-- Note the use of a boolean primitive.
} else {
$valid = true;
}
echo json_encode($valid);
This problem seems to be plaguing remote validation scripters and the jQuery documentation on the matter is clearly lacking.
I notice you are using jQuery 1.5.2: from what I understand (and found from experience) you must use the jQuery callback that is sent to the remote script with $_REQUEST with versions after 1.4, AND jQuery is expecting "true" or "false" as a STRING. Here is an example, confirmed working on multiple forms (I'm using jQuery 1.7.1):
if($totalRows_rscheck_ord_ref < 0){
header('Content-type: application/json');
$valid = 'false'; // <---yes, Validate is expecting a string
$result = $_REQUEST['callback'].'('.$check.')';
echo $result;
} else {
header('Content-type: application/json');
$valid = 'true'; // <---yes, Validate is expecting a string
$result = $_REQUEST['callback'].'('.$check.')';
echo $result;
}
I found this answer here (in the answers section), randomly, and have since stopped pulling out my hair. Hope this helps someone.
To add to Andrew Whitaker's response above, I must stress that you are sure that the response is strictly JSON and that there are no other content types being returned. I was having the same issue with my script, and everything appeared to be set properly - including using json_encode(). After some troubleshooting with Firebug's NET tab, I was able to determine that PHP notices were being sent back to the browser converting the data from JSON to text/html. After I turned the errors off, all was well.
//check_validate.php
<?php
// some logic here
echo json_encode(true);
?>
So I must be missing something. I can retrieve the zpid and the zestimate no problem doing the following:
$zdata->response->zpid; //zpid
$zdata->response->zestimate->amount; //zestimate
But then when I try what appears to be the obvious equivalent to retrieve a part of the address:
$zdata->response->address->street;
$zdata->response->address->city;
None of it works! Why?? Clearly I must be missing something here. Below is my entire code
<?php
$zillow_id = '1234';
$search = $_POST['address'];
$citystate = $_POST['csz'];
$address = urlencode($search);
$citystatezip = urlencode($citystate);
$url = "http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=".$zillow_id."&address=".$address."&citystatezip=".$citystatezip;
$result = file_get_contents($url);
$data = simplexml_load_string($result);
$zpidNum = $data->response->results->result[0]->zpid;
$zurl = "http://www.zillow.com/webservice/GetZestimate.htm?zws-id=".$zillow_id."&zpid=".$zpidNum;
$zresult = file_get_contents($zurl);
$zdata = simplexml_load_string($zresult);
//echo $zdata->response->zestimate->amount;
//$zestimate=$zdata->response->zestimate->amount;
$zstreet=$zdata->response->address->street;
echo $street;
?>
Looking at the XML output as seen on Zillow's own documentation, I am following the same pattern to try to get the street as to get the zestimate. I am not very familiar with working with XML so it is very possible I am missing something.
So I am getting an error in my console that shows the following:
Uncaught SyntaxError: Unexpected token T
The 'T' seems to be the first letter of the street that is entered, as it changes accordingly. Perhaps this could shine some light on the issue?
I'll post my AJAX too but I don't know why there would be something wrong with it. As stated above, I am able to display the ZPID and Zestimate just fine, only the address isn't working.
AJAX/JS:
function validateAddress(){
var address = document.getElementById('address').value;
var csz = document.getElementById('city_state_zip').value;
if (address == null || address == "" || csz == null || csz == "") {
return false;
}
else{
getZestimate(address,csz);
}
}
function getZestimate(address,csz){
var xmlhttp = new XMLHttpRequest();
var userdata = "address="+address+"&csz="+csz;
xmlhttp.open("POST","../wp-content/themes/realhomes/submit_address.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
//retrieve = JSON.parse(xmlhttp.responseText);
retrieve = xmlhttp.responseText;
document.getElementById("zestimateArea").innerHTML = '<div id="zillowWrap"><img src="http://www.zillow.com/widgets/GetVersionedResource.htm?path=/static/logos/Zillowlogo_150x40.gif" width="150" height="40" alt="Zillow Real Estate Search" id="ZillowLogo" /><span id="zestimateTag">Zestimate®</span></div><span id="zestimatePrice">'+retrieve+'</span><div id="zillowDisclaimer"><span>© Zillow, Inc., 2006-2014. Use is subject to Terms of Use</span><span>What’s a Zestimate?';
}
else{
document.getElementById("zestimateArea").innerHTML = "Error!"
}
}
xmlhttp.send(userdata);
document.getElementById("zestimateArea").innerHTML = "Generating...";
return false;
}
So when I went to post my AJAX as a last ditch effort for help I had seen I still had this line of code:
retrieve = JSON.parse(xmlhttp.responseText);
As Daedalus helpfully explained, this wasn't an issue when I was retrieving integers but posed a problem when I was retrieving text. I had originally put that line of code in when I was trying to retrieve both the Zestimate and the address together in an array encoded with JSON. When it was unsuccessful I took a step back to see if I could retrieve the address individually with no success. I never thought twice about that line of code since the AJAX still seemed to work fine.
Hence the perplexing outcome.
Changing that line back to:
retrieve = xmlhttp.responseText;
Allowed me to retrieve the address with success.
Don't you had simple mistakes that cause huge problems? Back to figuring out why the JSON encode and parsing wasn't working, but that's a question for a different post.