Maybe i am wrong but i can not find anyone who wants to display a json message just in json format from url on the page except for me.
I have a webshop in html, javascript and css. I am looking for some code example to display the json message just on the page. I don't want to parse the json into html or what else. I just want to display the json message as it is like this format: {"success":0,"message":"User not known"}.
This message above is the url response from my php database in xampp.
Below is my code and it works good, the problem is that this code is static. I am looking for some dynamic solution where you enter the url and it responds with json message. Any help is appriciated.
this is my login.html
if(form.id.value == "" || form.pass.value == "") {
alert("Empty details!");
}else if (form.id.value=="johan" && form.pass.value=="123") {
location="Page2.html"
} else { alert("Wrong username or password!")
}
}
and this is the json read:
// 1 - read josn:
var my_json_output = {"success":1,"message":"Vol","Username":"jan","UserSurname":"janman"}',
json_yes.succes json_yes = JSON.parse(my_json_output);
var my_json_output = '{"success":0,"message":"User_Unknown"}',
json_no = JSON.parse(my_json_output);
if(json_no.success == 1) { alert("Welcome, " + s + json_yes.Username);
}else if(json_no.success == 0) { alert("Try again");
}
Now i could find the answer and will share with others: just make a variable from XMLHttpRequest(); and use that variable for the message:
myconnect = new XMLHttpRequest();
Related
I have developing the one application using titanium.
Here the values are inserted successfully.But i didn't get the success message from webservices code.
I have using following code for insert a databaase :
In titanium side code :
function StaffRegistration(){
if($.staff_firstname.value != "" && $.staff_firstname.value != null){
var request = Ti.Network.createHTTPClient({
onload:alert(this.responseText),
onerror: function(e){
Ti.API.debug(e.error);
alert(this.responseText);
},
timeout:1000,
});
request.open("POST","xxx/xxx.php");
var params = ({"staff_firstname": $.staff_firstname.value,"staff_email": $.staff_email.value,"staff_password": $.staff_password.value,});
request.send(params);
}
else{
alert("Please enter the firstname");
}
Ti.API.info("Result for registration = " + this.responseText);
};
I have using a following php(webservice code) :
<?php
$request = base64_decode($_POST['jsondata']);
$data = json_decode($request,true);
$staff_firstname = $data['staff_firstname'];
$staff_email = $data['staff_email'];
$staff_password = md5($data['staff_password']);
include "db_connect.php";
$db = new DB_CONNECT();
$result = mysql_query("SELECT staff_email,staff_firstname from at_staff WHERE staff_email = '$staff_email'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
while($queryresult=mysql_fetch_array($result)) {
$uname[]=$queryresult['staff_firstname'];
$uemail[]=$queryresult['staff_email'];
}
if(in_array($staff_firstname,$uname) and in_array($staff_email,$uemail)) {
$response='{"Error":"1","Message":"Username and Email already exist"}';
echo $response;
} else if (in_array($staff_firstname,$uname)) {
$response='{"Error":"1","Message":"Username already exist"}';
echo $response;
} else {
$response='{"Error":"1","Message":"Email already exist"}';
echo $response;
}
} else {
$response='{"Error":"1","Message":"Successfully Registered"}';
echo $response;
$data=array("staff_firstname"=>"'".$staff_firstname."'",
"staff_email"=>"'".$staff_email."'",
"staff_password"=>"'".$staff_password."'"
);
echo $response;
}
?>
How can i get the $response in titanium from this webservice url.
#user2218667
Ti.API.info("Result for registration = " + this.responseText);
will NEVER work as you show in the first piece of code .
why ? because you send a request which will take like 1 seconde (for exemple), obviously, your programm won't wait 1 sec after
request.send(params);
i will continue the programm and when the request return a result, it will get into
onload(e) :
and here only you will be able to have your $result.
is this ok? well now, if this.responseData isn't effective, I don't have the solution .Can you check your line : "} else {" ,i supose there is a if above in the code? are you sure $result is defined upper?
Can you try the same request without titanium with a basic html form to be sure $result is write correctly in this case, like this, we will know if the problem come from php or from the link betwin php & titanium.
well , i supose it's asynchronous request, so the folowing may not work
Ti.API.info("Result for registration = " + this.responseText);
coud you try :
onload : function(e) {
Ti.API.info(this.responseText); // maybe Ti.API.info(this.reponsedata) according to your php.
},
onerror : function(e) {...
in my mind, if you receive JSON information (it trully look's like), you need
this.responseData //instead of this.responseText
I have successfully implemented the Jquery Validation Plugin http://posabsolute.github.com/jQuery-Validation-Engine/ but i am now trying to get an ajax database email check to work (email exists / email available) and i have written some php script to get this done. Its kinda working but i am getting the most unexpected heretically odd behavior from my IF ELSE statement (seems really crazy to me). observe ### marked comments
PHP code: LOOK AT THE IF ELSE STATEMENT
/* RECEIVE VALUE */
$validateValue = $_REQUEST['fieldValue'];
$validateId = $_REQUEST['fieldId'];
$validateError = "This username is already taken";
$validateSuccess = "This username is available";
/* RETURN VALUE */
$arrayToJs = array();
$arrayToJs[0] = $validateId;
$req = "SELECT Email
FROM business
WHERE Email = '$validateValue'";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results = array($row['Email']);
}
if (in_array($validateValue, $results)) {
$arrayToJs[1] = false;
echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR ### popup shows "validating, please wait" then "This username is already taken" when email typed is in database - i.e. Working
file_put_contents('output.txt', print_r("1 in array - Email is Taken " . $validateValue, true)); ### this runs!!
}else{
$arrayToJs[1] = true; // RETURN TRUE
echo json_encode($arrayToJs); // RETURN ARRAY WITH success ### popup shows "validating, please wait" when email typed is NOT in the database - i.e. not Working
file_put_contents('output.txt', print_r("2 else - Email is available " . $validateValue, true));
//### THIS RUNS TOO !!!!!!!!!!!!! i.e. echo json_encode($arrayToJs) wont work for both.. If I change (in_array()) to (!in_array()) i get the reverse when email is in database.
//i.e. only the else statements echo json_encode($arrayToJs) runs and the popup msg shows up green "This username is available" crazy right???
//so basically IF ELSE statements run as expected (confirmed by output.txt) but only one echo json_encode($arrayToJs) will work.!!!!
//If i remove the json_encode($arrayToJs) statements and place it once after the IF ELSE statement i get the same problem.
//both $arrayToJs[1] = false; and $arrayToJs[1] = true; can work separately depending on which is first run IF or ELSE but they will not work in the one after another;
}
HERE IS THE REST OF THE CODE-->
1-HTML FORM INPUT CODE:
<tr>
<td> <Label>Business Email</Label>
<br>
<input type="text" name="Email" id="Email" class="validate[required,custom[email],ajax[ajaxUserCallPhp]] text-input">
</td>
</tr>
2-Relevant JQUERY code in jquery.validationEngine.js:
$.ajax({
type: type,
url: url,
cache: false,
dataType: dataType,
data: data,
form: form,
methods: methods,
options: options,
beforeSend: function() {
return options.onBeforeAjaxFormValidation(form, options);
},
error: function(data, transport) {
methods._ajaxError(data, transport);
},
success: function(json) {
if ((dataType == "json") && (json !== true)) {
// getting to this case doesn't necessary means that the form is invalid
// the server may return green or closing prompt actions
// this flag helps figuring it out
var errorInForm=false;
for (var i = 0; i < json.length; i++) {
var value = json[i];
var errorFieldId = value[0];
var errorField = $($("#" + errorFieldId)[0]);
// make sure we found the element
if (errorField.length == 1) {
// promptText or selector
var msg = value[2];
// if the field is valid
if (value[1] == true) {
if (msg == "" || !msg){
// if for some reason, status==true and error="", just close the prompt
methods._closePrompt(errorField);
} else {
// the field is valid, but we are displaying a green prompt
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertTextOk;
if (txt)
msg = txt;
}
if (options.showPrompts) methods._showPrompt(errorField, msg, "pass", false, options, true);
}
} else {
// the field is invalid, show the red error prompt
errorInForm|=true;
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertText;
if (txt)
msg = txt;
}
if(options.showPrompts) methods._showPrompt(errorField, msg, "", false, options, true);
}
}
}
options.onAjaxFormComplete(!errorInForm, form, json, options);
} else
options.onAjaxFormComplete(true, form, json, options);
}
});
3-Relevent code for ajaxUserCallPhp in jquery.validationEngine-en.js:
"ajaxUserCallPhp": {
"url": "validation/php/ajaxValidateFieldUser.php",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* This username is available",
"alertText": "* This user is already taken",
"alertTextLoad": "*Validating, please wait"
},
Im sure the problem lies with this echo.
echo json_encode($arrayToJs)
Please help i've spent to long on this and its almost working fully.
To clarify - I basically am trying to code it so that if i type an email in the db it shows red "This username is taken" then if i edit the input box to an email not in the database it changes to green "username is available" at the moment only one json_encode will run in any scenario no matter how i change the if else statement –
Thank you very much in advance.
Ok got it finally after a fiddle. I found that json_encode() returns false when any error or warning is posted. using the php error log file in xampp/php/logs/error_logs file i realised that i was getting an error only when the query result was null making $results = null. this caused an output error preventing json_encode() from echoing true, which is why i only got one response.
To fix it i made sure that the $result array was not empty by using the following code after the query to array part.
if(empty($results)){
$results [0]= ("obujasdcb8374db");
}
The whole code is now
$req = "SELECT Email
FROM business
WHERE Email = '$validateValue'";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results[] = $row['Email'];
}
if(empty($results)){
$results [0]= ("obujasdcb8374db");
}
if (in_array($validateValue, $results)) {
$arrayToJs[1] = 0;
echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR
} else {
$arrayToJs[1] = 1; // RETURN TRUE
echo json_encode($arrayToJs); // RETURN ARRAY WITH success
}
I was able to change ajax url for ajaxusercallphp, ajaxnamecallphp without modifying the languge file... You need to search for this line inside jaquery.validateEngine.js
Find : _ajax:function(field,rules,I,options)
Then scroll down to the ajax request .ie $.ajax
And change url:rule.url to options.ajaxCallPhpUrl
Then all you have to do is include the url as an option like this:
JQuery("#formid").validateEngine('attach', {ajaCallPhpUrl : "yoururl goes here", onValidationComplete:function(form,status){
})
I was able to change ajax url for ajaxusercallphp, ajaxnamecallphp without modifying the languge file... You need to search for this line inside jaquery.validateEngine.js
Find : _ajax:function(field,rules,I,options)
Then scroll down to the ajax request .ie $.ajax
And change url:rule.url to options.ajaxCallPhpUrl
Then all you have to do is include the url as an option like this:
JQuery("#formid").validateEngine('attach', {ajaCallPhpUrl : "yoururl goes here", onValidationComplete:function(form,status){
})
i have a situation where i'm stuck at the idea of catching the appropriate error during file upload in the ajax response in jquery form-plugin.
i'l give an idea of what i want to achieve through some pseudocode.
My php is :
$file = strtolower($_FILES["myfile"]["name"]);
$extension = substr($file, strrpos($file, '.') + 1);
if($extension == 'jpg'){
// upload the file
if(move_uploaded_file($_FILES["myfile"]["tmp_name"], $folder . $finalFilename)){
// do something here like
echo "<div id='statusContainer'>
<table><tr><td>
<img src='uploads/".$finalFilename."'>
</td></tr>
<tr><td>".$finalts."</td></tr></table>
</div>";
}
} else {
$error = 1; // will give numbers to different errors like filetype error, size error etc..
}
now my JS code is :
(function() {
var status = $('#status');
$('form').ajaxForm({
complete: function(xhr) {
if(xhr.responseText == "// what do i get echoed here so i can run an array and show user appropriate error like size error, type error etc. // "){
// i want to open a dialog box with correct error message//
} else{
status.hide().html(xhr.responseText).fadeIn(1000);
}
}
});
})();
shall i get the error number echoed in the ajax response and run through an array to get the message? but then i'll have to put in a lot of if conditions in the ajax response with different error numbers.
Please anyone have a more logical idea??
you could make an array and pass error json_encode()'ing it and parse json response from ajaxForm, like
php part:
$responseArr = array();
if( file_is_uploaded ) {
$responseArr["error"] = "0";
$responseArr["message"] = "File uploaded success message";
}
else {
$responseArr["error"] = "1";
$responseArr["message"] = "Error message here";
}
echo json_encode($responseArr); //pass it as response
js part::
$('form').ajaxForm({
dataType: "json",
success: function(response) {
//parse json response and perform accordingly
console.log( response );
}
});
To cut down on traversing an array in JS, and matching error IDs to descriptions, could you associate the error description itself to be relayed in the ajax response? This would keep your JS lean and keep error handling serverside.
Example:
<tr><td>".$finalts."</td></tr></table>
</div>";
}
$error_descriptions = array("Filesize Error", "Extension Error");
} else {
$error = error_descriptions[1];
}
I need help with my flash registration form. I made sure all my information is correct, but when I enter the information, it doesn't seem to enter it into the mysql database. Here is the flash code:
var lvSend:LoadVars = new LoadVars();
var lvReceive:LoadVars = new LoadVars();
register_btn.onRelease = function() {
var valid:Boolean = validateForm();
if(valid){
//gather information and put in loadvars object
lvSend.username = username.tInput.text;
lvSend.password = password.tInput.text;
lvSend.email = email.tInput.text;
//send information php script for insertion into database
lvSend.sendAndLoad("register.php", "POST");
}
};
function validateForm():Boolean{
if(username.tInput.text == "" || password.tInput.text == "" || email.tInput.text == ""){
return false;
}
return true;
}
function clearTextFields():Void{
username.tInput.text = "";
password.tInput.text = "";
email.tInput.text = "";
}
Here is the Php Code:
http://i.stack.imgur.com/cvvcO.png
Sorry that my code is in picture form. That was the best way I could make it readable by you guys.My problem is that all the information in both codes seem correct. All my text fields are called username, password, and email, same goes for the database columns. The database info isn't wrong because I used the php code with html, I just can't get it to work with flash. My php file is called register.php and my flash file is called play.swf. Thanks for your help!
try:
lvReceive.onLoad = function(success:Boolean) {
if (success) {
trace("ok");
}
else {
trace("error");
}
lvSend.sendAndLoad("register.php", lvReceive, "POST");
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.