Getting data back AND $POSTing data using jQuery.Ajax - php

I'm trying to build a registration system using PHP and the AJAX components of jquery.
My jQuery takes the values of the username and password fields and makes a POST request to the PHP script, which grabs the values using $_POST and saves them to the database.
Of course, i'm wanting to make sure that there aren't any duplicate usernames, and beyond using the PHP mysql_error() function, i wasn't sure how to do this.
So i want to set my PHP to first check for entries in the database with the username the person enters in the form, if it exists, i'd like to return a custom error message to the user using the php return() feature.
How can i use jQuery to first POST the values to the script, and then return any data/ custom error messages that i am creating with return();
By the way, security is not an issue here.

Simplest way would be to make a page, for example, post.php. post.php will do all the checking and stuff you want and, I know you want to use return, but just echoing the stuff back would be the absolute easiest. So, echo any error or even a value (for example, you can echo back -1 for a false or a 1 for a true).
The jQuery side is pretty simple:
$('form').submit(function(){
$.post('post.php',{username:$('#username').val(),password:$('#password').val()},function(data){
//username and password == $_POST['username'] && $_POST['password']
//data will now equal anything you echo back. So, lets say you did as my example and used -1 for an error
if(data==-1){alert('ERROR');}
});
return false;
});
If there is an error you will get an alert otherwise nothing will happen at all. Now you could do an else{} and have whatever you want for if there is no error.

Related

Strange Error with Complex PHP Form Processing

NEW INFORMATION:
I used the print_r function on the $_REQUEST and something very strange is happening there too. Some values are being correctly passed by the GET such as a value on another form which passes in "TRUE". This can be seen in the print_r output but isn't written to the file... Still no closer to finding a solution to my problem however.
I'm working on a page with a lot of forms which are loaded in as needed by AJAX. This all works fine as does parsing the name:value pairs and storing them appropriately.
My error happens when the PHP parses the GET request sent by AJAX when the user is finished, it only seems to retrieve the values from certain fields.
The idea is that the user can add data from any number of forms, which are then turned into a GET request and sent to the server.
The JavaScript is building my request perfectly and all forms are sent correctly.
Depending on the forms the user submits, the data is processed by a large switch statement which passes the relevant names to a variadic function which grabs the values, and creates a string for writing to a file.
The strange error is that only some values get written to the file with others only having a blank line. No error reported by Apache or PHP, no error reported in the JavaScript console either.
I'll use the Colour form for example as this is one of the more complex.
So I add a colour action and click the button to submit all forms (this time, it's just the colour form though)
My get request looks like this:
actionIDs=Colour&coOptionSelect=Tinting&coColourEffect=Sepia&coRemoveColour=#000000&coRemoveFuzzNumber=0&coRemoveHueSelect=None&coReplaceColour=#000000&coReplaceFuzzNumber=0&coReplacementColour=#000000&coReplacementAlphaNumber=0&coReplaceHueSelect=None&coReplacementHueSelect=None
Next, the PHP parses the actionIDs part as sometimes, there will be many actions. This works fine.
We now jump to the Colour part of the switch statement.
case "Colour":
$config = processAction("coOptionSelect", "coColourEffect", "coRemoveColour", "coRemoveFuzzNumber", "coRemoveHueSelect", "coReplaceColour", "coReplaceFuzzNumber", "coReplacementColour", "coReplacementAlphaNumber", "coReplaceHueSelect", "coReplacementHueSelect");
file_put_contents($confpath . "colour.conf", $config);
break;
That writes to the correct file, but strangely, only coOptionsSelect and coColourEffect have their values written to the file. It isn't their input type as they are select statements similar to the other selects on the form. On other forms, it may be a number input or a text input that submits properly instead.
It isn't random either, the same ones will always write out properly. It also isn't positional as I moved around the values and it's still the same ones that write correctly, their position doesn't affect anything.
Finally here is processAction function.
function processAction()
{
$config = "";
foreach(func_get_args() as $field)
{
$temp = isset($_REQUEST[$field]) ? $_REQUEST[$field] : null;
$config = $config . $temp . "\n";
}
return $config;
}
The end result should be all values should write to their relevant files correctly, rather than the current issue where only a few values from each form are written, with the rest of the values being written as blank lines.
You probably need to encode your # sign to a encoded method %23
you could also use urlencode to do it before passing it to your variable.
Reference: http://php.net/manual/en/function.urlencode.php
Update:
If you are going to try to encode through javascript I would try and use this method
var newURL =
"http://example.com/index.php?url=" + encodeURIComponent(actionIDs);
or
var newURL =
"http://example.com/index.php?url=" + escape(actionIDs);
Reference: Encode URL in JavaScript?
You have three options:
escape() will not encode: #*/+
encodeURI() will not encode: ~!##$&*()=:/,;?+'
encodeURIComponent() will not encode: ~!*()'
But in your case, if you want to pass a URL into a GET parameter of other page, you should use escape or encodeURIComponent, but not encodeURI.
See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.

PHP Userfriendly/Smart Forms (Without JS)

Im currently trying to develop a form that can work fully without JavaScript.
Basicly i want the user to be able to do the following:
Complete form
Submit form
Success(Update DB or what ever)
Fail (Go back to step 1 but with data from step 1 before already there)
I was thinking of doing the following for example:
<input type="text" value="<?php checkPost(name);?>"/>
Then in check post doing something like:
function checkPost($name){
try{
return $_POST[name];
}
catch{
return "";
}
}
Would this stop the error:
Notice: Undefined index
Which means if the data wasnt posted then just set the value to "" but if it was posted then set the old value to it.
Is this the best way to do it can anyone tell me a smarter way to do this with my forms.
My form markup can be seen here: JS Fiddle
It will not stop error.
Because error is not an Exception in this case.
This sounds much better:
function checkPost(name){
return isset($_POST['name']) ? $_POST['name'] : '';
}
My opinion - it is very bad idea to write validation functions for each for field.
Read about Zend_Form.
You can include it in your project even if you are not using ZF.

Problem with codeigniter's redirect function

This may be a n00b topic but, anyways, I have been having a rather difficult and strange time with this bug. Basically I was working on a controller method for a page that displays a form. Basically, I was debugging the form's submitted data by var dumping the form input using codeigniter's $this->input->post function like so:
var_dump($this->input->post('first_name'));
Every other day this has worked, but today I was finding that when I dumped post variables to the browser it would return false as if they had no values even though they did have values when I submitted the form. Then I tried accessing the variables through PHP's POST superglobal array directly like so:
var_dump($_POST['first_name']);
and that returned empty as well so then I tried dumping the entire post array like so:
var_dump($_POST);
and it was empty as well despite the fact that I filled out the entire form. Nevertheless, the records in my MySQL database were being updated (which means that the form was submitting even though my $_POST variables appeared empty).
Also, I reasoned that normally, if I var dumped variables in the controller function before a redirect function call that it should give me a 'Headers already sent' error but it never did. It just redirected me to the supposed success page instead of dumping my variables.
So for the about 2 hours I thought that my POST data wasn't being sent and re-checked the code for errors and began commenting out statements one by one until I could find the culprit statement in my script.
Finally, I commented out a chunk of code that sets a success message an redirects, like so:
/*
if($record_updated_successfully)
{
$this->session->set_flashdata('success', $this->lang->line('record-updated-successfully'));
}
redirect('admin/success_page');
*/
and only then did the script start dumping out all my previous variable dumps using codeigniter's $this->input->post function as well as the $_POST superglobal array.
So ok, if the script does indeed redirect me despite the variable dumps sending output before headers are sent then I can see why the $_POST variables would appear empty.
So then the real question is why the script would still redirect despite my sending of output before headers are sent? Has anyone ever experienced this?
Any help with this would be appreciated.
EDIT: with respect to loading the view here's a simplified version of my script looks like
with the debugging var dump statements:
function some_controller_method() {
var_dump($this->input->post());
var_dump($_POST);
// some code
if($this->input->post('form_action') == 'update record') {
// code that runs when the form is submitted
/*
* ...
*/
if($record_updated_successfully)
{
$this->session->set_flashdata('success', $this->lang->line('record-updated-successfully'));
}
redirect('admin/success_page');
}
$this->load->view('my-view-file.php');
}
While I can't be sure, I'm going to assume you were outputting things like the var_dump() in your view file. A view is not executed at the time you call it, for example:
$this->load->view('some_view');
echo "hi!";
In a controller will not result in the contents of some view followed by "hi". It will results in "hi" followed by the contents of some view. The view is actually output after everything else in the controller has run.
This is the only thing that comes to mind with the information you've presented. I'd have to see more code to offer a different diagnosis.
I had "the same" problem and I found an unset() function in a loop in my code. Perhaps this will help.

Code Igniter - Get Hash Value With window.location.hash and Use in set_value()?

I need to get the hash # value from the current window url with javascript (can't get it with PHP), and then use that to set the value attibute of a form input with CI's set_value() function.
Any ideas how I can grab the value in javascript then put it into the PHP function? :-S
Thanks in advance!
I can't quite tell if you fully understand the relationship between Javascript and PHP, so I'm going to assume that you don't. PHP runs on the server and outputs HTML to the browser (along with some headers and other stuff). Once the HTML is sent to the browser, what the user does with your site is out of your control until his browser performs another GET or POST request (or opens a persistent web socket connection). As you mentioned, it's impossible for PHP to outright read the value of the hash, as it's meant to be confined to the browser, accessible only via Javascript. Since your PHP script for that particular request has stopped running and the page data has already been output to the browser, what sense does it make to grab the value using Javascript, send it back to PHP with another http request, use the set_value() function, and then what?
If you use window.location.hash and set the value of your input box equal to it, you will be able to use set_value() when the user submits the form. Take a look at CI's set_value() helper function:
function set_value($field = '', $default = '')
{
if (FALSE === ($OBJ =& _get_validation_object()))
{
if ( ! isset($_POST[$field]))
{
return $default;
}
return form_prep($_POST[$field], $field);
}
return form_prep($OBJ->set_value($field, $default), $field);
}
It first checks to see if you've set up form validation object. If you have, it runs the form_prep() function using that object's set_value (presumably to manage any rules you've set up in your form validation. If you haven't, it sees if that field exists in the $_POST array. If it doesn't, it returns the default value. If it does, it returns the value from the $_POST array. So if you a) set up a form validation rule for it and b) give that input box the name you want to use in your set_value() function, you will be able to retrieve the value of the hash in PHP which you have entered into that input box using Javascript.
In Javascript you can achieve this vis
hash = window.location.hash;
In PHP you can access it using parse_url()
parse_url() : Return Values
On seriously malformed URLs, parse_url() may return FALSE. Otherwise an associative array is returned, whose components may be (at least one):
* scheme - e.g. http
* host
* port
* user
* pass
* path
* query - after the question mark ?
* fragment - after the hashmark #

PHP work with JS Jquery

How do i make PHP work with JS?
I mean more like, i want to check if the user is logged in or not,
and if he is then it will:
$("#message").fadeIn("slow"); ..
How should i do this?
I have an idea maybe have a file that checks it in php, and then it echo out 1 or 0.
And then a script that checks if its getting 1 then do the message fade in.. But im not as so experienced to script that in JS
You cannot directly pass variables from Javascript to PHP because the PHP run on the server before it's sent to the client. But you can 'pass' variables from PHP to Javascript.
For example:
echo('<script type="text/javascript'> var phpvar = '.$variablefromphp.';</script>');
However, you can manipulate what javascript your browser will print. You can first check if the user is logged in in PHP, and based on that, conditionally print the HTML and Javascript.
For example
if($user->logged_in())
{
echo('<script type="text/javascript">$("#message").fadeIn("slow");</script>');
}
else
{
//php function
generateLoginBox();
}
I only javascript to enhance user experience. You should make your application work even when javascript turned off.
With the javascript enabled, you can add an enhanced experience, such as animated page element, AJAX request, etc.
In case of login state, you should have a way to know it in PHP script. Then in the output, you can have a conditional block that only executed if the login state is true. You can put anything you want here.
Javascript can be working in a static HTML page. You can use this to create a simple test for the code that you wrote, to see if it working as you want. Read the documentation in http://www.jquery.com/, there are many links there to many examples.

Categories