Pass javascript variable to php - php

I know this had been disputed a lot and the short answer would be that I can't simply pass a javascript variable to a php variable in the same file. So instead here would be what I want to try: My user inputs a code, I send it to a php file by POST. There I check if the code matches a code from my database and I post again a boolean from there. Then in my first file, I tell the user whether the code is correct or not. Can this be achieved this way? I am a webdev newbie and I am trying to learn.

To pass a value from the client side to the server you can either send it on the URL or as a post variable.
This can be accomplished easily with ajax.
I recommend using jquery. example:
$.get("http://example.com/?var1=value&var2=othervalue", function (data) {
// your response
});

jQuery:
$.get( url, { userinput: value }, function( response ) {
if( response.status ) alert( "Matches found" );
else alert( "No matches" );
}
javascript:
function get( url ) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false );
xhr.send();
return xhr.responseText;
}
var response = JSON.parse( get( url ) );
if( response.status ) alert( "Matches found" );
else alert( "No matches" );
php:
header( 'Content-type: text/json' );
if( get_matches( $_GET['userinput'] ) ) exit( '{ "status": true }' );
else exit( '{ "status": false }' );

You can post that code through AJAX to your server, have your server return a boolean, and then output a message to your user, this is quite common.
Common implementations of this logic include autosuggest, username validity verifications, simple turn on / turn off interfaces, etc.
Workflow:
User inputs code
Javascript sends AJAX request to server
Server verifies code and returns boolean
Javascript reads boolean, generates HTML and appends it to the document
User reads output
Edit: Even though i advice you to try doing it with pure javascript first (for educational reasons), you should use jQuery or other equivalent framework if you are on a schedule.

Related

Ajax returns with PHP

Alright so I am trying to put this thing together, but I do not understand what is the problem with this code. I am basically trying to return false in case name exists in the database, but no matter what ajax will just pass it as a "success"
Here is the code:
Running the
function checkName(username) {
$.ajax({
url:"assembly/handler.php",
type:"POST",
data:{func:"run_namecheck", user_name:username},
success:function(data){
return true;
},
error:function(data) {
return false;
}
});
}
The code is executed perfectly and it actually passed all the things it needs, and the PHP function does get called.
PHP function bellow.
public function nameExists($name) {
$handler = new sql();
$sql = $handler->connect();
$sql->real_escape_string($name);
$name_final = ucfirst($name);
$result = $sql->query("SELECT ime FROM users WHERE ime='".$name_final."'");
if($result->num_rows != 0) return true;
else {
$handler->log_write($name, "login_fail","NULL");
return false;
}
$sql->close();
return false;
}
Now the problem is success and the error. No matter what it will always be success. It doesn't like pay attention at when I return FALSE from the PHP at all and such.
AJAX calls are literally just an HTTP request, like any other HTTP request. You're not directly "executing" PHP code when you make an ajax call, you're doing an HTTP request to the server, which (eventually) executes a PHP script on your behalf.
That means any return from the PHP code are completely invisible to Javascript.
Only OUTPUT from PHP will ever be seen by Javascript, which means you need to echo that data, not return it.
And note that any HTTP response from PHP is also literally plain text. Any output you perform in PHP will be converted to text, which means that boolean false you're trying return will be converted to the string equivalent of a boolean false - an invisible zero-length string.
"error" condition in your js code is only for bed requests, like 500, 404 etc.
return a json { error: true } or something like with and use it in your js
success:function(data){
if(data.error) {
// do...
}
},
As far as I can see your code, you're returning nothing to client. You shall return some data that represents the boolean value about the user existence. For instance:
// PHP server-side
if( nameExists( $name)) echo "T";
else echo "F";
that will return value can then be captured by the data parameter in your AJAX function for success and be tested about the server answer.
// Javascript in client
success:function(data){
if( data === "T") return true;
else return false;
},
Hope I can help!
instead of return from php you need:
echo "True" or "false"
to on javascript side:
function checkName(username) {
$.ajax({
url:"assembly/handler.php",
type:"POST",
data:{func:"run_namecheck", user_name:username},
success:function(data){
if(data=='true'){
alert("success process");
}else{
alert("fail process");
};
},
error:function(data) {
console.log("error Ajax");
}
});
}
The data transferred between the client and the server is always text. You need to make sure that the client and server know how the client should deserialize the text. So you might return one of four things:
HTML (if it's going to populate page elements)
JSON (if you want a lightweight, fast way to send data to the client)
XML (if you want a heavier-weight, fast way to send data to the client)
Plain text (for whatever you want, really)
What the client does will depend on what Content-Type header you use in your PHP page.
so, use a header in PHP, for eg:
header('Content-Type', 'application/json');
...and the return this text from it:
{"success": true}
or
{"success": false}
I hope it will help.

how to manage errors server side (php) when Ajax is involved?

So, I have an ajax call that prevents default post submission, server side I do some validation and checking, if the data is correct I do some database operations (inserting item for user etc) but if the data is not correct I don't have to make anything but throw out an error (i.e. item already present). My case in the controller was something like this:
} else {
print('Item already present');
}
but now I have the ajax call that manages the error like this:
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
},
So obviously the php doesn't print anything.
How should I modify my php to act well with the ajax call?
When you make an ajax call, you should be expecting a particular type of data back. A typical (example) scenario is to get back data in JSON. If you are using jQuery, then I typically to look for errors in a two places because I think of ajax errors coming in two types:
network error or anything that results in a website error (404 - page not found, 500 - potential coding error, etc). This is caught in the ajax 'error' handler function as you have it above. I believe you could intentionally trigger an error in your PHP code to get this case.
logical error. This is an error that you might be expecting to handle - such as a bad username/password during a login call via ajax. In this case, you don't really want to throw a PHP error. Instead you want to return an error, but perhaps also include some meta data bout the error such as 'username does not exist' or whatever.
So, on your php server, you would have a view that needs to set the header to be a JSON response, and then output the JSON error, e.g.:
<?php
// output a json version of any list of objects that has the
// "toArray()" method defined.
// ...for ajax calls.
header( 'Content-type: application/json' );
$isError = 'false';
if (checkToSeeIfErrorOccurred())
{
$isError = 'true',
$errorMessage = getErrorMessages();
}
?>
<!-- define json result -->
{
error: "<?php echo $isError; ?>",
errorMessage: "<?php echo $errorMessage; ?>"
}
So, on your client side, in (for instance) your jquery ajax call, you would define a successHandler that needs to check for this error, and specify the dataType of the return value. Note that even though it is a successHandler, the 'success' part just means you had no network or programmatic/PHP error thrown. So, you still need to check for the logical error you might return in your JSON:
// your error handler
function myErrorHandler( xhr, status, errorThrown )
{
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
};
function mySuccessHandler( response )
{
// response is returned as an object
if (response.error === 'true')
{
// maybe call same error handler?
myErrorHandler( 'whoCares', 'logicalFailure', response.errorMessage );
}
else
{
// handle success
}
};
$.ajax(
url,
dataType: 'json',
error: myErrorHandler,
success: mySuccessHandler,
...
);
I don't know if this is typical for other folks and it is only an example but it has worked well for me...
One way you could think about this is use ajax to do your request and then return xml with a result from php echo statement. If the result is successful then your code does what it needs to do else as part of the php server return you have an xml error tag with why it went wrong and then process this in your ajax.
Another way you could return a result is with json.

jQuery ajax returning unexpected data type

attempting to implement some server side error checking for input in the very useful "handsontable" jscript library.
the following call works great:
jQuery.ajax({
url: "index.php?option=com_catalogscontroller=batchsave",
data: {"formData": querydata.getData().splice( 0, 1 ) },
dataType: 'JSON',
type: 'POST',
success: function ( response ) {
if( response.success ) {
} else {
querydata.loadData( response.data );
}
}
});
I thought the most effective way to do error checking is on the server (PHP) side, to create a multidimensional array to track any errors discovered by the server and then return that array with the form data in the same ajax call. So I modified the server code to return both the form data and the error array back to the javascript ajax call. i.e.:
if( !empty( $errors ) ) // $errors is an multi dimensional array same size as the form data
$result['success'] = false;
$result['msg'] = 'There were errors detected';
$result['data']['form'] = $formData;
$result['data']['errors'] = $errors;
}
echo json_encode( $result );
and then on the client side, the javascript routine above has been modified to:
jQuery.ajax({
url: "index.php?option=com_catalogscontroller=batchsave",
data: {"formData": querydata.getData().splice( 0, 1 ) },
dataType: 'JSON',
type: 'POST',
success: function ( response ) {
if( response.success ) {
} else {
formErrors = response.data.errors; // formErrors is a global
querydata.loadData( response.data.form );
}
}
});
The original function of the form is preserved (the form data is retrieved and properly inserted in the html), but formErrors returns with a result to me that is baffling. An alert immediately after the assignment 'alert( formErrors )' shows something like a list:
true,true,false,true,true
and I can also alert on a specific index without problem e.g. alert( formErrors[0][2] ); would display 'false'. But outside of the ajax call, the array seems to be inaccessible, giving 'undefined' errors. And both in the ajax call, and in routines outside of the ajax call alert( typeof formErrors ) displays 'object' and alert( formErrors) gives the same comma list as above, but I don't want an object, I am expecting an array OR i'd be happy with an object as long as i could access it by indices. What am I missing here?
The problem I was having appear to be centered around JSONing.
Most docs identify the requirement to JSON variables in php routines supporting a Javascript AJAX call. The use of the jQuery.ajax call alleviates some of the requirement, but if you don't know what you're doing (like me), its easy to get in trouble.
My php routine JSON encodes the complete response record with the statement:
return json_encode( $result );
Because of my:
dataType: JSON
parameter in the jQuery.ajax() call, this results in an automatic json.parse() of the result returned by the PHP routine to the jQuery javascript function. This is not successful however because the php json_encode call in the server code is not recursive, so while the result array is decoded, any arrays within that result are not.
the solution then is to json encode the components of the multidimensional array and then decode them on the client side. e.g.
if( !empty( $errors ) )
$result['success'] = false;
$result['msg'] = 'There were errors detected';
$result['data']['form'] = json_encode( $formData );
$result['data']['errors'] = json_encode( $errors );
}
echo json_encode( $result );
And then on the client side, parse (decode) these arrays specifically:
jQuery.ajax({
url: "index.php?option=com_catalogscontroller=batchsave",
data: {"formData": querydata.getData().splice( 0, 1 ) },
dataType: 'JSON',
type: 'POST',
success: function ( response ) {
if( response.success ) {
} else {
formErrors = JSON.parse( response.data.errors ); // formErrors is a global
querydata.loadData( JSON.parse( response.data.form ) );
}
}
});
I confess freely that I don't really know what I'm doing, but the code structured above seems to make sense for the logic I've developed to explain it AND it is working for me.
Anyway, thanks again to Nathan and pdoherty926.

can't make cross browser AJAX request to work

I am doing a simple ajax request to another domain like this:
<script type="text/javascript">
$(function() {
$('.clik').click(function() {
$.ajax({
type: "POST",
url: "http://sub.mydomain.com/test.php",
crossDomain: true,
dataType:"jsonp",
success: function(data) {
$('p.txt').html(data['no']);
}
});
});
});
</script>
</head>
<body>
<p class="clik">Halleluja</p>
<p class="txt"></p>
this is the test.php page on sub.mydomain.com
<?
header('Access-Control-Allow-Origin: http://mydomain.com');
// Begin Session
require_once('cl.session.php');
$session = new Session();
$session->start_session('test', false);
// Access Database
require_once('cl.database.php');
$login_db = new Database('user', 'pass', 'accounts', 'test');
$login_pdo = $login_db->PDO;
include "fn.check_login.php";
if(checkLogin($login_pdo) == true) {
// We start out by checking if the request has been made using AJAX
if (is_ajax()) {
echo "this is working";
} else {
echo "this is not working!";
}
} else {
echo 'You are not authorized to access this page, please login. <br/>';
}
// Function to check if the request is an AJAX request
function is_ajax() {
// BOOLEAN return if AJAX
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
?>
It returns a semantic issue.
Also if I simply echo some basic text:
<?
echo "Hello World!";
?>
it still returns a semantic issue.
could somebody tell me what went wrong?
Well, for a start, JSONP requests can't be POST (only GET). But I tend to assume jQuery is ignoring the invalid type. JSONP is intrinsically a GET.
Your response to it is invalid. You've told jQuery you're expecting the server to provide a JSONP response. but your responses aren't JSONP.
A JSONP response would look something like this:
callback({
"property": "value",
"anotherProperty": 42
})
...where the name of the callback (callback in the above) is taken from the query string of the request. So for instance, if the request were http://sub.mydomain.com/test.php?callback=foo, the response would use foo for the name of the callback:
foo({
"property": "value",
"anotherProperty": 42
})
jQuery will add the callback= query string parameter to the request for you automatically, and generate the corresponding function for you, which in turn calls the ajax success handler with the data passed into it.
I think you may need to use the jquery postMessage plugin (or similar if there is one). Long time since I tried it but check if you load the script from the server you wish to call (think I tried that and failed in the past but hey - its worth a bash - report back if it does).

Sending data from PHP to jQuery

I have build a simple but working AJAX form using jQuery. The form is validated with jQuery before submit and then after successful submit again with PHP.
The only problem is the error handling. When the PHP-check returned that all fields are ok, I display a success message. If there was an error, I simply display "there was an error".
How can I send back data from PHP to jQuery so invalid fields can be marked as invalid?
Or is such form of error handling unnecessary as the dynamic highlighting needs JavaScript turned on and if JavaScript is turned on, the form can't be submitted wrong?
Basically, my valid checks look like this (simplified of course):
function checkSomething( $something ) {
$valid = true;
if ( strlen( $something ) === 0 ) {
$valid = false;
}
return $valid;
}
At the end of the script, I do it like this:
if ( checkSomething( $something ) && checkThis( $this ) && checkThat( $that ) ) {
echo "success";
} else {
echo "error";
}
And in my JavaScript/jQuery code it looks like this:
$.ajax({
url: "form.php",
type: "POST",
data: string,
success: function ( result ) {
if ( result == "success" ) {
alert( "success" );
} else {
alert( "error" );
}
}
});
Your form submission has 3 steps: JavaScript Validation & Submission, PHP validation/Processing, and JavaScript on complete ( 'so invalid fields can be marked as invalid')
It sounds like you have step 1 completed and most of step 2.
In your PHP code you should have some data structure, preferably an array, which holds which values are invalid. You can return this data to the browser by echo`ng it to the browser
<?php
...
...
if( count( $invalidFieldArray ) ){
echo json_encode( array( 'status' => 'Fail',
'data' => $invalidFieldArray ) );
}else{
echo json_encode( 'status' => 'Success' );
}
The code above will return the success/fail to your JavaScript form.
I personal use a jQuery form plugin to handle form submissions, and I recommend you give it a try. It has many nice out of the box features.
$.ajax({
url: "form.php",
type: "POST",
data: string,
dataType: json,
success: function ( result ) {
if ( result.status === "Success" ) {
alert( "success" );
} elseif (result.status === 'Fail'){
for (field in result.data) {
/* Invalid field handling */
...
}
}
}
});
Tip : Slightly off-topic, but when using comparisons in JavaScript always use triple equal ( === ), double equal ( == ) is not the same in JavaScript as in other languages; JavaScript does type coercion with double equals, which provides for inconsistent results.
I think you should have only one service in PHP. You send the data from the form, if there is any invalid data, you might want to return a JSON indicating which fields are wrong, so you can parse and show it. If it went ok, you just simply display that success message.
I'm not sure I get your problem, though.
You could send the data from PHP and store it in URLs, like this url.com/#value=1

Categories