How to pass a variable with $.post for javascript script? - javascript

Here is my code in my jquery/javascript that is performing the ajax request...
else {
$.post("http://www.example.com", {email: val},
function(response){
finishAjax('email', response);
});
}
joinAjax('cemail');
}
if (id == 'cemail') {
$('#cemailMsg').hide();
var email = $('#email').val();
if (errors.email == false) {
if (val != email) {
The ajax request is working and all is good, but the next if statement where the argument is:
if (errors.email == false) {
I need to be able to set this variable from my ajax.php file to either true or false and return it so the javascript can read it. Is this possible??
It is because the ajax is checking if the username is available or not, if not available a form error would be true preventing the form submitting, or if false then the user can submit.
My ajax.php file:
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo '<div id="emailMsg" class="success">Email OK</div>';
exit();
}
else {
echo '<div id="emailMsg" class="error">Email taken</div>';
exit();
}
}

Why not have your ajax.php return an associative array like so:
echo json_encode(array("email" => "success", "key2" => "val2"));
And then use
var responseJSON = JSON.parse(response);
In the $.post callback function to read the response and act accordingly. You can generate the appropriate markup (divs or whatever) client-side and insert it.

You may want to back up and determine what you want here. If all you want to do is display a different message depending on the result of the post, return (from the post) the smallest amount of information. In this case the value could simply be boolean. email valid or invalid.
I would recommend returning json from your post.
If you are returning json, the success method (function(response){}) is where you could operate on or evaluate the response.
If you return json (which can be strings from PHP, in this case), it evaluates to JavaScript objects. so if you returned '{"errors":"true"}' it will evaluate to (response.errors === true) within your success method in the post call.
'errors' is undefined, correct? Make it a property of the response json object, and be sure to test for undefined values on the data you get back.
Generate HTML or manipulate CSS based on the values you get from the post.
In that vein, jquery makes it easy to add HTML to the DOM. Try
(can someone fix my formatting and add a code tag if you can edit? I'm on my cell ATM)
$('&ltdiv&gt&lt/div&gt', {
text : 'your text here',
class : 'yourclass'
}).appendTo($(element));

Related

trouble submitting ajax form in yii

I am creating a widget for use in a website to 'find' a match in any field in the database. I currently am using a jQuery 'Dialog' box, and wish to submit the form, have the form redirect to a controller/action (I am using yii which uses the MCV model), and return the output of that function into the current window.
I am currently using a hidden div, and the jquery load function.
$("#find_results").load(loadPage, function(){
}).show();
which calls a function that does this essentially:
public function actionFind(){
if (!empty($_POST)){
//do really big query
//put results into <tr> and <td> tags using a for loop
}else{
echo <tr><td>"no results found"</td></tr>;
}
}
this code returns an output, but only ever "no results found", leading me to believe that the form never actually gets posted.
does anyone know what kind of black magic is happening here??
thanks!
P.S.
The dialog box is a partial view which contains the form to be submitted with the action /controller/find
updated:
I implemented this instead: new error is "undefined index: findtext", which is the name of my text input.
$("#find_results").load(loadPage,{ data: $("#find_form").serialize() },function(data){
console.log(data);
$('#find_results').html(data);
$(this).show();
});
First, lets look at the signature for .load()
.load( url [, data ] [, complete ] )
url
Type: String
A string containing the URL to which the request is sent.
data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.
complete
Type: Function( String responseText, String textStatus, jqXHR jqXHR )
A callback function that is executed when the request completes.
So, if you want to send data to the server, you'd do something like:
$("#find_results").load(loadPage, {someKey: 'some value'}, function(){
$(this).show();
});
Now, that we are sending data, nevermind what I said before about $_GET
From the docs:
Request Method
The POST method is used if data is provided as an object; otherwise, GET is assumed.
Also, since you've tagged yii you may need to access $_POST differently in your app, something like this:
public function actionFind( ){ // pass in $request from your app
$request = Yii::$app->request;
if (!empty( $request->post() )){ // change this
//do really big query
//put results into <tr> and <td> tags using a for loop
}else{
echo <tr><td>"no results found"</td></tr>;
}
}
See The Definitive Guide to Yii 2.0 which says this:
$request = Yii::$app->request;
$post = $request->post();
// equivalent to: $post = $_POST;
$id = $request->post('id');
// equivalent to: $id = isset($_POST['id']) ? $_POST['id'] : null;

PHP, Javascript, mysql, and selection lists

I'm working on a piece of some software that will grab information from a mysql database and throw it onto our form dynamically. I'm running into a couple problems, though. I'll give a quick rundown of some functionality.
When the form loads, we have a ton of selection lists. These are all populated through arrays with various keys/values in php. When I select an option from one list, we'll call it a "customers" list, on-click I need to check if that customer has a special flag (stored in the database), and update another selection list based on that data.
How I understand the core of my solution is I need to have a javascript trigger on-click, which I have. The function that is called references a php page that handles the database query through a class and it's function.
<script>
function setService()
{ // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.get('thePage.php?key=setService?customer='+customer);
}
</script>
This function then talks to my php. The CustomerProvider class works 100%. I have tested that thoroughly on other pages. The problem arises when I try to actually get my selection list to change.
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
if ($s != '')
{ ?> <script>var element = document.getElementById('ticket_service');
element.value = 'Contracted Hours';</script> <? }
else return;
}
?>
I'm coding in javascript literally for the first time ever and they kinda just threw me on this project. I know that my portion isn't being read as html or output as I intend. I know that every other part of the php and the first bit of javascript seems to be executing okay. Any help would be incredibly appreciated.
You seem to be on the right track but just for your own sanity here are a couple pointers. You shouldn't be returning Javascript from PHP for a situation like this. Instead you should be relying on Javascript promises to wait for a response containing just the data and continue the execution of your client code once you have your values returned. Take a look at this:
<script>
function setService() { // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.get('thePage.php?key=setService?customer=' + customer, function(data) {
console.log(data + ' was returned from your php script!');
if(data.hasContract=='1')
$('#ticket_service').val('Contracted Hours');
else
$('#ticket_service').val('No Contracted Hours');
});
}
</script>
And then your PHP script will just look like this:
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
if ($s != ''){
$hasContract = 1;
}
else
$hasContract = 0;
echo json_encode(array('hasContract' => $hasContract));
}
?>
Therefore returning only the data needed for the client app to continue... not application logic
Your code isn't doing anything with the output of the PHP script. If you want the output to be inserted somewhere in the DOM, you should use .load() rather than $.get.
$("#someelement").load('thePage.php?key=setService?customer='+customer);
This will put the output into <div id="someelement">. If the output contains <script>, the script will be executed.
If you know the result is just a script, you could use $.getScript() instead of $.get. Then the output should just be the Javascript, not enclosed in HTML tags like <script>.
The problem here is that you are not using the result from the server. Your JavaScript may indeed be correct, but the browser never sees or runs it. From the docs:
Request the test.php page, but ignore the return results.
$.get( "test.php" );
Try this code, which utilizes the $.getJSON() shortcut function. I've written two versions, which you can see commented in the code. One moves the logic for determining contract status into the JS. Either should work.
PHP
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
// Default output
$output = array('hasContract' => false);
// Customer has contract
if ($s != '')
$output['hasContract'] = true;
echo json_encode($output)
// Alternative: PHP just returns getHasContract, JS determines action
// (this would replace $ouput, conditional, and echo)
// echo json_encode(array("hasContract" => $s));
}
?>
JavaScript
function setService()
{ // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.getJSON('thePage.php?key=setService?customer='+customer, function(result) {
// Alternative
// if (result.hasContract != "")
if (result.hasContract)
{
var element = document.getElementById('ticket_service');
element.value = 'Contracted Hours';
}
});
}
As others wrote, your code doesn't do a thing with the GET variables.
the element "ticket_service" doesn't exists on page and even if it was, the code has no impact on the page that sent the request, you should print/echo the result you want to display/return and then manipulate it with JS/Jquery.
since I'm against GET and pro POST which is safer method, here's an example with POST:
JS:
function postSomthing(customerID){
$.post(
'thePage.php',
{key:'setService',customer:customerID},
function(data){
if(data!='x'){
$('#ticket_service').val(data)
}
else{alert('no ticket');/*whatever you want to do*/}
});
}
PHP(thePage.php) :
if(isset($_POST['key']) && $_POST['key'] == 'setService'){
$customer = intval($_POST['customer']);
$s = CustomerProvider::getHasContract($customer);
if ($s != ''){echo 'x';/* false, or whatever you want*/}
else{echo 'Contracted Hours';}
}
notes:
you should create an element with the id "ticket_service" in the viewed page and not in the backstage one.

How to receive data in php sent from javascript [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
I am sending some data from my pain page to app.php using javascript
$(document).on('click', '.app' , function(){
var data=$(this).attr("id");
window.location="application/app.php?data="+data; //data send in this statement
});
my php code is this :
<?php
if($_GET['data'])
{
echo $app_id=$_GET["data"]; receiving data
}
?>
It works sometime but now it is giving Notice in an alert box: Undefined index data in app.php. But it is showing the echo.
I want to know how I can receive the data I need using $_POST or $_GET. like we receive by making an Ajax call. But I haven't specified something like this in Javascript. is there any way to this?
I want to clarify that the data exists and it is non empty because echo is successfully printing that on the page
Try this:
<?php
if(!empty($_GET['data']))
{
$app_id = $_GET['data']; // receiving data
}
?>
Please be aware that passing data without validation is not secure. Reccomended reading: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
use isset() to first check if the key exists. data won't exist in $_GET when it's not passed via a parameter in the url
you probably want some logic that looks like this:
if (isset($_GET['data'])) {
if (!empty($_GET['data'])) {
$appId = $_GET['data'];
}
else {
// data exists, but it's empty
}
}
else {
// data does not exist
}
and maybe you even want to check if it's a valid id, like being numeric or something

Use variable value on php webpage in separate javascript function

I have a server running which has a php function which returns true/false depending on input values. Currently I am just echoing the result on the page. I want to use this true/false in a to evaluate a condition in a javascript function running completely separately from the server.
Is there a javascript function I can use to get the text from a webpage and put it in a variable? I looked at the jquery load() function but this doesn't seem like it will work for this purpose.
Keep the output of the PHP script as simple as possible (a text response outputting only "true" or "false").
To send a text response (instead of an HTML response), you can use:
header("Content-Type: text/plain");
You have to call this function before outputting anything.
Now, assuming you can access the output of the script at the URL http://www.example.com/webpage.php
if($.ajax({type: "GET", url: "http://www.example.com/webpage.php", async: false}).responseText == "true")
{
// do something
}
else // "false"
{
// do something else
}
Not sure if it would work, but you might try using document.body.innerHTML. It gets you the innerHTML from the body element from the document (which, in your case, should be a true or false string).
If you are just wanting to use jQuery to get the echoed out result of your php you can do:
var whatever = "<?php echo $result ?>";
In your PHP/HTML (assuming you have a function named "yourFunction" that returns a boolean):
<div id="your_id">
<?php echo yourFunction()?'true':'false';?>
</div>
And in your JavaScript
if($('#your_id').text() == "true")
// do something
else
// do something else
You could treat it like html, update your doc to add a tag around the result. "true" at which point your almost using XML.
You should be able to get the raw response. I usually don't recommend consuming raw text tho as people could inject malicious js into the response.

What's the most proper/friendly way to handle returned data from PHP JavaScript (AJAX)?

EDIT: Okay, now that I think about it, JSON does sound decent for this, and as long as I code right, there shouldn't be a syntax error to disrupt it or anything.
Good evening!
Something that's always bothered me is how to handle returned data from PHP in an AJAX request, and how to even return the data!
Say I have a log in form, and it processes submitted form data through AJAX. We'll say we use GET for simplicity's sake.
"page.php?username=Foo&password=bar"
Here's what bugs/irks me, and why I feel compulsive and feel as though I need to know the right way to do this:
I sent the data and it's been processed. Now what?
Say my username and password are valid/correct. What do I do?
Return true in PHP? A string?
Then what do I do with the JavaScript?
if(ajaxRequest.responseText=="true"){
//Username and password are correct! Execute this...
}
What I thought was a cool idea was returning a JSON object as a string, and parsing through JavaScript.
var object=JSON.parse(ajaxRequest.responseText);
if(object.success=="true"){
//Username and password are correct! Execute this...
}
But, what if my username and password combo is...wrong?
Do I return false via PHP, or a string again?
Between true and false, there are only 2 choices:
1. The username and password were correct
2. The username and password were not correct
But what if the username doesn't even exist? Returning "false" doesn't help me tell the client exactly why they can't log in.
Diving deeper into my OCD on this, what about unexpected or parse errors?
If there is some sort of DB connection error or a parse error, how do I return that to tell the user? I looked into Trying...and Catching syntax errors, but I had no luck.
A recent thought I had was to do THIS:
If everything executes properly, and the username and password exist (going back to our original scenario), then we don't return ANYTHING. The responseText will be an empty string. That means the user logged in successfully!
Otherwise, if there is an error, DO return something (typically a string) and display it as an error.
Am I going about this the right way? Am I on the right track?
My personal preference, which is in no way "THE" correct way to do it, is to use JSON for everything.
So I have a JavaScript function that, when a form is submitted, will convert the form data to a JSON string and POST it to the server.
The server then processes it, and returns another JSON object. In your login example, therefore, the server would receive:
{"username":"Foo","password":"bar"}
And it would return one of these:
{"ok":false,"error":"No user with that name was found."}
{"ok":false,"error":"The password you entered was incorrect."}
{"ok":false,"error":"Failed to log you in (error code: ###)"}
{"ok":true,"redirect":"/home"}
Every AJAX request response has this "ok" property. If it is false, there will be an "error" property saying what happened (and there may be additional data depending on the situation). On success, the "ok" property is true. A lot of requests just get {"ok":true} all by itself, but sometimes there is additional data here too.
As I said, this is not "THE" way to do it, but I like it and it's consistent.
EDIT: Forgot to mention the bit about PHP errors.
The JavaScript that receives the server's response attempts to parse it as JSON using a try...catch block. If parsing fails, then there was a server error. In such a case, an error message is popped up with the raw response from the server, with a note advising the user to contact me about the error message.
A fairly common pattern for this is to return an error array, which could be a JSON object in your case. If the error array is empty you are good to go, and if it's not then display the error to your user.
I think you are over complicating yourself with the if and buts of response.
Following is an old example i have have used once. i am using following ajax to send username/password to php file through AJAX
$.ajax({
type: "POST",
url: SITE_URL+"ajax_files/ajax_login.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
if(data.success=='y') {
window.location.href='index.php';
} else {
$('#messagesnormal').hide();
//Show results div
$('#resultsAjax').show();
//Put received response into result div
//$('#resultsAjax').html(data.msg);
}
}
});
And following is my php file code.
header('Content-Type: application/json');
include("../config/config.php");
$username = trimdata($_POST['username']);
$password = trimdata($_POST['password']);
$r = $db->select("SELECT * FROM users where email = '".dbAddslashes($username)."' and password='".dbAddslashes($password)."' and status = '1' and locked_by_admin = '0'");
if($db->row_count > 0) {
while ($row=$db->get_row($r, 'MYSQL_ASSOC')) {
$_SESSION["userdata"]["userid"] = $row['user_id'];
$_SESSION["userdata"]["usertype"] = $row['type'];
$_SESSION["userdata"]["useremail"] = $row['email'];
$_SESSION["userdata"]["name"] = $row['name'];
if($_SESSION["userdata"]["usertype"]=='1') {
$_SESSION["userdata"]["userrole"] = 'admin';
} else {
$_SESSION["userdata"]["userrole"] = 'user';
}
$_SESSION["userdata"]["last_login"] = $row['last_login'];
$_SESSION["userdata"]["last_login_ip"] = $row['last_login_ip'];
$success = 'y';
$msg = 'login successfull';
/*Insert login time and IP*/
$data = array('last_login' => time(), 'last_login_ip' => getRealIPAddr());
$rows = $db->update_array('users', $data, "user_id=".$row['user_id']);
print json_encode(array('success' => $success, 'msg' => $msg));
exit;
}
} else {
$success = 'n';
$msg = '<div class="gagalsmall">Invalid credentials.Please try again.</div>';
print json_encode(array('success' => $success, 'msg' => $msg));
exit;
}
exit;
Although i have only queried for both username password exists, you can apply similar check on different occasion. then pass these values back to jquery in json format.
You can use all the values assign in php as i did above on line:
if(data.success=='y') {
where success is assigned from php file.
Hope this helps you.

Categories

Resources