Ajax post not working codeigniter - javascript

I am using codeigniter 3.1
Ajax post not working and i am getting 403 (Forbidden) in console.
[POST http://localhost/test/post 403 (Forbidden)]
HTML
<div class="post">
<input type="text" id="data1" name="data1" value="">
<input type="text" id="data2" name="data2" value="">
</div>
<button id="post">Submit</button>
JAVASCRIPT
$('#post').on('click', function () {
var value1=$("#data1").val();
var value2=$("#data2").val();
$.ajax({
url: window.location.href+'/post',
type: "POST",
data:"{'data1':'"+value1+"','data2':'"+value2+"'}"
});
CONTROLLERS
public function post()
{
$data1 = $this->common->nohtml($this->input->post("data1", true));
$data2 = $this->common->nohtml($this->input->post("data2", true));
$this->data_models->update($this->data->INFO, array(
"data1" => $data1,
"data2" => $data2,
)
);
}

If you want CSRF protection on (a good idea) then you must pass the CSRF token when posting form data - via AJAX or not. Consider this approach.
The easiest way to put the token in your form is to use Codeigniter's "Form Helper" (Documented here) You can load the function your controller or use autoloading. This view code assumes you have the helper loaded.
HTML
<div class="post">
<?= form_open('controller_name/post'); //makes form opening HTML tag ?>
<input type="text" id="data1" name="data1" value="">
<input type="text" id="data2" name="data2" value="">
<?php
echo form_submit('submit','Submit', ['id'=>'post']); //makes standard "submit" button html
echo form_close(); // outputs </form>
?>
</div>
The form_open() function also automatically adds a hidden field containing the CSRF token to the HTML.
Javascript
$('#post').submit(function( event ) {
//the next line will capture your form's fields to a format
//perfect for posting to the server
var postingData = $( this ).serializeArray();
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
data: postingData,
dataType: 'json',
success: function(data){
console.log(data);
}
});
});
controller
By the time $_POST gets to your controller the CSRF token has been striped away so you don't have to worry about it "polluting" your incoming data.
public function post()
{
//get all the posted data in one gulp and NO, you do not want to use xss_clean
$posted = $this->input->post();
//With the above the var $posted has this value (showing made up values)
// array("data1" => "whatever was in the field", "data2" => "whatever was in the field");
//sanitize the field data (?)
//just stick the clean data back where it came from
$posted['data1'] = $this->common->nohtml($posted["data1"]);
$posted['data2'] = $this->common->nohtml($posted["data2"]);
$this->data_models->update($this->data->INFO, $posted);
//you must respond to the ajax in some fashion
//this could be one way to indicate success
$response['status'] = 'success';
echo json_encode($response);
}
You could also send back some other status if, for instance, the model function reported a problem. You then need to react to that status in you javascript. But if you don't respond it will likely result in problems down the road.

Related

ajax [file 1] -> php [file 2] -> $_POST [file 1]

I am building a budget application with HTML, Javascript, and PHP. My goal is to have the user be able to add data into a database from a form provided. I already have a ton of php at the top of my 'dashboard.php' (which contains the form) so I didn't want to run dashboard.php on submit, so instead I created a button that preforms an AJAX call to a different php file 'addIncome.php'.
I have two different files...
dashboard.php &
addincome.php
dashboard.php contains my form, as well as my javascript to run an AJAX call.
addincome.php is using $_POST to grab the values from the form in dashboard.php and make a mysqli_query. However, at first nothing was happening so I decided to echo the value of one of the return values from my $_POST. And ended up getting this error...
undefined index iName in addIncome.php
undefined index iAmount in addIncome.php
So from there I though that maybe I didn't have access to the dashboard.php by default so I included...
include('dashboard.php');
Still no difference...
I'm really at a stand still here. Any thoughts?
Thanks
The form...
<form>
<input type="text" name="iName" placeholder="income name">
<input type="number" step="0.01" min="0" name="iAmount" placeholder="amount">
<input type="date" name="iDate">
</form>
The javascript...
<script>
$('.in-btn').click(function() {
$.ajax({
url: "addIncome.php",
type: "POST",
data: 'show=content',
success: function(data) {
$('.in-btn').html(data);
}
});
setTimeout(() => {
// location.reload();
}, 2000);
});
</script>
The php...
<?php
echo "adding...";
require_once('connection.php');
include('dashboard.php');
$iUser = $_SESSION["username"];
$iName = $_POST["iName"];
$iAmount = $_POST["iAmount"];
echo $iName;
$sql = "INSERT INTO income (user, name, amount, date) VALUE ('pmanke', '$iName', '$iAmount','1/16/19')";
mysqli_query($dbCon, $sql);
?>
You are not sending any post data with your AJAX call except for:
show=content. You want to send your form data. You can retrieve your form data with:
$("#id-of-form").serialize()
That way your PHP code is able to retrieve the correct values from your POST data.
An even more general way to do this is to just create a normal form with a submit button and an action and use javascript to catch the submit event and make an AJAX call instead:
HTML:
<form id="idForm" action="addIncome.php">
<input type="text" name="iName" placeholder="income name">
<input type="number" step="0.01" min="0" name="iAmount" placeholder="amount">
<input type="date" name="iDate">
<input type="submit" />
</form>
Javascript:
$("#idForm").submit(function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data) {
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});

Passing variable from PHP to Javascript, using Ajax returns 'undefined'

I have got a PHP file that received data that has been posted from a form. It then sends it to a database. However I needed to get those variables and put them in JavaScript. I have done the following, but when logging the variables supposed to store the php data (in the script file) it return undefined.
What am I doing wrong? I am new to all the languages. The files are all separate - with the PHP and Script files being external.
SCRIPT:
$(function(){
var data1 = $("#username").val();
console.log(data1);
$.ajax({
type: "POST",
url: 'signUp.php',
data: ({data1}),
success: function(data) {
console.log("success");
}
});
});
PHP
if (isset($_POST['signup'])){
//The connection to the database
include_once 'databaseHandler.php';
//Gets the infomation submitted from the form
//Protects the database by converting everything to text...
//The database therefore cannot read the inputs as code
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
echo (".$user.");
HTML
<form action="signUp.php" method="POST">
<input id="usernameSignUp" type="text" name="username" placeholder="Username">
<br>
<input id="passwordSignUp" type="password" name="password" placeholder="Password">
<br>
<button class="BUTTON" type="submit" name="signup">SIGN UP</button>
</form>
You never set the post parameter 'signup'. Which in turn does not let you enter your if construct and therefor php gives you nothing.
Try:
data:{
"username":$('usernameSignUp').val(),
"password":$('passwordSignUp').val(),
"signup":1,
}
I think, you don't send the variable correctly.
var data1 = $("#usernameSignUp").val();
var data2 = $("#passwordSignUp").val();
$.ajax({
type: "POST",
url: 'signUp.php',
data: {signup:'1',username:data1,password:data2 },//Supose data1= username data, data2 = password data
success: function(data) {
console.log("success");
}
});
There is so much wrong here, it is hard to know where to begin.
You make the Ajax request when the page loads. This is before the user has typed anything into the form.
When the form is submitted, you don't use Ajax at all
You pass a field called data1 to the server (which it is not looking for)
You give that field the value of the input with id="username" (which doesn't exist)
You don't pass fields called username or password to the PHP (which it is looking for)
You don't pass a field called signup to the PHP (which it tests for with isset before doing anything)
Your PHP echos a variable called $user which you haven't defined
Your JavaScript doesn't look at the response, it just logs the string "success"
You'd need something more like:
$(function() {
$("form").on("submit", function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: 'http://example.com/signUp.php',
data: ({
signup: 1,
username: $("#usernameSignUp").val(),
password: $("#passwordSignUp").val()
}),
success: function(data) {
console.log("Success", data);
},
error: function(data) {
console.log("This is a cross origin request to a dummy URL, what did you expect");
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="signUp.php" method="POST">
<input id="usernameSignUp" type="text" name="username" placeholder="Username">
<br>
<input id="passwordSignUp" type="password" name="password" placeholder="Password">
<br>
<button class="BUTTON" type="submit" name="signup">SIGN UP</button>
</form>
Then there are the things which are bad practises but which don't directly affect the ability of the code to work.
You use mysqli_real_escape_string instead of placeholders.
You don't hash your passwords. "Not hashing at all" is an unsuitable hashing algorithm; you need to take better care of your users' passwords.
The HTML5 placeholder attribute is not a substitute for the label element

Setting PHP session variables with ajax

Want to change value of SESSION variable "fullname" without refreshing the page.
My implementation using ajax:
Page 1 html:
<input type="text" name="fullname" id="fullname" placeholder="Full name">
<button onclick="setSession()"> GO </button>
Page 1 script:
<script>
function setSession(){
var fullname = $("#fullname").val();
var dataString = 'fullname=' + fullname;
$.ajax({
type: "POST",
url: "Page2.php",
data: dataString,
cache: false,
success: function( data ) {
if(data === 'True'){
alert("<?php echo $_SESSION['fullname'];?>");
}
}
});
}
</script>
And in Page 2:
session_start();
$_SESSION["fullname"] = $_POST["fullname"];
echo 'True';
exit();
It doesn't change the value of the session variable.
Both pages have session_start().
Your code should already be changing the value in the PHP session. You just don't have your client-side script set up properly to show that.
Return some kind of indicator in your PHP script:
<?php
// Page2.php
session_start();
$_SESSION["fullname"] = $_POST["fullname"];
echo 'set session fullname to ' . $_POST['fullname'];
Then in your AJAX success function, show that response:
...
success: function( response ) {
alert(response);
}
...
When you use alert("<?php echo $_SESSION['fullname'];?>"); in your success function, PHP will fill in the $_SESSION['fullname'] value in that alert box once when the page loads, and it will never change until the page is reloaded, even if you do successfully update the session value via AJAX.
First, have you watched the AJAX request / response in the browser's developer tools? Have you included the jQuery library in the project? Are there any errors reported? Are you running this on a web-server?
Second, you're starting a session in a remote page. That session data will not be available in the current page until you reload the current page. In addition you have some wonky quoting in your alert, it should be:
alert("<?php echo $_SESSION['fullname'];?>");
Page 1 HTML
<input type="text" name="fullname" id="fullname" placeholder="Full name">
<button onclick="setSession()"> GO </button>
Page 1 Script
<script>
function setSession(){
$.ajax({
type: "POST",
url: "Page2.php",
data: { fullname: $("#fullname").val() },
dataType: "json",
cache: false,
success: function( data ) {
alert(data.fullname);
}
});
}
</script>
Page 2 PHP Script
session_start();
$_SESSION["fullname"] = $_POST["fullname"];
echo json_encode(array('fullname' => $_SESSION['fullname']));
It's generally a bad idea to mix server-side and client-side scripts together so try to separate your PHP and Javascript logic. They both execute at different times/stages of a page request life-cycle.
You are setting the variable in JS using PHP Inline coding. You could however echo the session variable in page2 if no post has been set. If you then request page two without any post you can use the response body in JS to get the current set session variable and put it in a JS variable.
Var name;
$.get(‘page2.php’, function(data){ name = data; } );
I’m using the iOS app so above code is not complete but an indication for what can be done.

PHP post does not take the value of a button tag

I have in a login.php the code to check if the user exist or not and also an AJAX call, I have in the form a button tag; If I use type='submit' the PHP works but not the AJAX; and if I use type='button' the AJAX works but not the PHP.
I've also tried with input but it's the same:
<?php
if (isset($_POST['enviar'])) {
include "php/conexion.php";
try {
$user = $_POST['user'];
$pass = $_POST['pass'];
$sql = 'SELECT count(user_name) FROM user WHERE user_name=:usuario AND password=:password';
$query = $conexion->prepare($sql);
$query->bindParam(":usuario", $user);
$query->bindParam(":password", $pass);
$query->execute();
if($res = $query->fetch())
{
header("refresh:0.1;url=main.php");
}else{
echo"User or Password incorrect";
}
} catch (Exception $ex) {
$a= $ex->getMessage();
var_dump($a);
die();
}
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function realizaProceso(user,pass){
$.ajax({
data: {"user" : user, "pass": pass},
url: 'php/functions_sql.php',
type: 'post',
success: function(output) {
}
});
}
</script>
<div class="container">
<div class="login-container">
</div>
<div class="form-box">
<form action="login.php" method="post">
<input name="user" id="user" type="text" placeholder="User">
<input type="password" name="pass" id="pass" placeholder="Password">
<button class="btn btn-info btn-block login" type="button" id="enviar" name="enviar" onclick="realizaProceso($('#user').val(),$('#pass').val());" >Login</button>
</form>
</div>
</div>
</div>
</div>
You need to prevent your form from submitting, to allow your AJAX call to execute. Make the following change to your code:
onclick="realizaProceso($('#user').val(),$('#pass').val()); return false;"
The return false; statement tells the HTML form to 'stop' the execution of the form submission to allow you to perform a custom action instead, such as an AJAX form submission. That is why your form seems to fail when using type='submit'
Your AJAX call also appears to be calling 'php/functions_sql.php'. Are you sure you want your AJAX making a call to what appears to be (based on its title) a Helper class containing SQL related methods?
I am concerned you are posting to 'functions_sql.php', which probably isn't designed to read those variables.
Everything within if (isset($_POST['enviar'])) { ... } appears to be a login script (and reads variables). You appear to be mixing 'asynchronous' (AJAX) and 'non-asynchronous' usages together, which is why you are getting confused.
Move that code into a separate file (login_auth.php, for example), then change your AJAX call to talk to it specifically ($.ajax({ ... , url: 'login_auth.php'})
The PHP checks for $_POST['enviar'], but the AJAX call doesn't put that in the data: option. Use:
$.ajax({
data: { user: user, pass: pass, enviar: 1 },
url: 'php/functions_sql.php',
type: 'post',
success: function(output) {
}
});
instead of button, use <input type='button' ....
It has to be an input field to work properly cross browsers

Problems using JQuery Mobile to send data to server using PHP, POST, and JSON

I have thoroughly researched this topic, but cannot seem to find an answer due to the fragmented nature of the discussions and the very different use cases everyone seems to have.
I am using JQuery mobile to send data to a PHP login/registration script via $.ajax() call. It appears that the data I am trying to send never makes it to the server to be evaluated, and I am at a loss as to why.
I am trying to send the data from this form:
<div data-role="content">
<form id="reg_form" data-ajax="false">
<div data-role="fieldcontain">
<label for="reg_email">Email:</label>
<input type="email" name="reg_email" id="reg_email" value="" />
<label for="reg_pass">Password:</label>
<input type="password" name="reg_pass" id="reg_pass" value="" />
<label for="reg_pass_conf">Password:</label>
<input type="password" name="reg_pass_conf" id="reg_pass_conf" value="" />
<h4 id="reg_notification"><?php echo 'Notifications will appear here...'; ?></h4>
<button data-theme="b" id="reg_submit" type="button">Register!</button>
</div>
</form>
</div>
Which is triggered by this javascript:
$(document).on('pageshow', '#reg_page', function() {
$("#reg_notification").text("page loaded");
$(document).on('click', '#reg_submit', function(){
$("#reg_notification").text("button clicked");
var formDataReg = $("#reg_form").serialize();
$.ajax({
type: "POST", // Method of sending data to server
url: "php_scripts/reg_handle.php", // php script being sent to
cache: false, // requested pages won't be cached by server
data: formDataReg, // data to be sent to server
dataType: "json", // data type to be received back from server
success: onRegSuccess, // function to call on success
error: onError // function to call on error
});
return false;
});
});
function onRegSuccess(data, status)
{
alert(data);
$("#reg_notification").text(data.email + ' ' + data.pass + ' ' + data.pass_conf);
}
Which is sent to this php script:
<?php
if (isset($_POST['formDataReg'])) {
$reg_email = 'formData is set';
}else{
$reg_email = 'formData is not set';
}
$formData = json_decode($_POST['formDataReg']);
$reg_pass = $formData->{'reg_pass'};
$reg_pass_conf = $formData->{'reg_pass_conf'};
$output = array('email' => $reg_email, 'pass' => $reg_pass, 'pass_conf' => $reg_pass_conf);
echo json_encode($output);
?>
However, as stated earlier, the if/else block detects that $_POST['formDataReg'] is not even set. When I try to use it to assign values to variables, it obviously has no data to assign and I get null values.
I used alert to verify that indeed formDataReg did hold the proper form values before being passed to the server in the ajax call. It somehow gets lost in the ajax call, or I am not accessing it correctly.
If someone can point me in the right direction, I would very much appreciate it.
By this:
var formDataReg = $("#reg_form").serialize();
You serialized your form into the form. Now in formDataReg has such contents:
reg_email=xxx#gmail.com&reg_pass=yyy&reg_pass_conf=yyy
You have to parse this query in your php file:
$email = $_POST['reg_email'];
$pass = $_POST['reg_pass'];
$pass_conf = $_POST['reg_pass_conf'];
But you tried to work with $_POST['formDataReg'] which wasn't sent. So it is wrong. Yes, you had variable formDataReg in your JS, but it means nothing. You had sent serialized string (query) with your ajax-request and have to handle it.
So this code:
if (isset($_POST['formDataReg'])) {
$reg_email = 'formData is set';
}else{
$reg_email = 'formData is not set';
}
$formData = json_decode($_POST['formDataReg']);
wouldn't work because you hadn't sent formDataReg and there are no value with this key in $_POST array.
This:
$reg_pass = $formData->{'reg_pass'};
$reg_pass_conf = $formData->{'reg_pass_conf'};
$output = array('email' => $reg_email, 'pass' => $reg_pass, 'pass_conf' => $reg_pass_conf);
echo json_encode($output);
should work properly.
Let me know is something is unclear.

Categories

Resources