Ajax connection to function in php failing - javascript

I am trying to submit a form via ajax but it doesn't let me:
Ajax - samepage
<script type="text/javascript">
$(document).on('submit','.subscribe',function(e) {
$.ajax({ url: 'lib/common-functions.php',
data: {action: 'subscribe'},
type: 'post',
success: function(output) {
alert(output);
}
});
});
</script>
HTML - same page
<form class="subscribe">
<label class="lablabel">Name:</label><input type="text" class="subscribe-field" id="sname" name="sname"></br>
<label class="lablabel">Email:</label><input type="text" class="subscribe-field" id="semail" name="semail" >
<input type="submit" id="ssub" value="Subscribe">
</form>
PHP - common-functions.php
<?php
require_once('dbconn.php');
function subscribe() {
$name = $_POST['sname'];
$email = $_POST['semail'];
$db->query("INSERT INTO subscribers (`name`, `email`, 'confirmed') VALUES ($sname, $email, 0)");
echo "You have been subscribed";
}
?>
EDIT added dbconn
$db = new mysqli($dbhostname, $dbuser, $dbpass, $dbname);
if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
In the console I get nothing. After I click submit and check the console. I can see in red how is actioning common-functions.php but doesn't do anything. Please help.

TL;DR You need to do six things to fix the problems in the code you have provided. There are pitfalls with event propagation, scoping, and variable validation.
First, add this to your JavaScript: event.preventDefault(); event.stopPropagation();.
Second, submit your actual data.
Example showing these fixes:
$(document).on('submit','.subscribe',function(e) {
e.preventDefault(); // add here
e.stopPropagation(); // add here
$.ajax({ url: 'lib/common-functions.php',
data: {action: 'subscribe',
sname: $("#sname").val(),
semail: $("#semail").val()},
type: 'post',
success: function(output) {
alert(output);
}
});
});
Third, actually call subscribe().
Fourth, you have a scoping problem: $db is a global, but you don't refer to it as one. That's why I added global $db; below.
Fifth, check the existence of your POST values.
Sixth, put quotes around your database values and escape them first.
<?php
require_once('dbconn.php');
function subscribe() {
global $db;
if(isset($_POST['semail'], $_POST['sname'])) {
$name = $_POST['sname'];
$email = $_POST['semail'];
$db->query("INSERT INTO subscribers (`name`, `email`, 'confirmed') VALUES ('".$db->escape_string($sname)."', '".$db->escape_string($email)."', 0)");
echo "You have been subscribed";
}
}
subscribe();
?>
NOTE: This just shows how to fix the code that you have posted. The code in the question, however, is wide open to SQL injection. You really should use prepared statements instead of relying on escaping of special characters.

You have to include the data youre accessing via Post in PHP in the data object in the $.ajax call:
$.ajax({ url: 'lib/common-functions.php',
data: {action: 'subscribe',
sname: $("#name").val()
semail: $("#semail").val()},
type: 'post',
success: function(output) {
alert(output);
}
});
});
Also your PHP function subscribe doesnt get called just by setting action:"subscribe"
You have to check wheter $_POST["action"] is "subscribe":
if($_POST["action"]=="subscribe")
{
subscribe();
}

Related

Handling ajax response exceptions

I am currently handling a form with php and calling it via an ajax request, i want to handle exceptions showing a small div instead of the basic popup
so i did multiple if conditions based on the responsetext, however one of the exceptions doesnt get handled
This exception is the empty fields exception it always shows the wrong username or pw instead
here is the ajax call
function sendLogin(){
username = $('#loginEmail').val();
password = $('#loginPassword').val();
a = $.ajax({
type: 'post',
data: 'username='+username+'&password='+password,
url: '/account/login.php',
async: false,
});
if(a.responseText == "LoggedIn"){
$("#WrongPW_Error").fadeOut("fast");
$("#Empty_Error").fadeOut("fast");
$("#LoggedIn").fadeIn("fast");
setTimeout(location.reload(),2200);
}
else if(a.responseText == "Empty_Fields") {
//alert(a.responseText);
$("#WrongPW_Error").fadeOut("fast");
$("#Empty_Error").fadeIn("fast");
}
else if(a.responseText == "Wrong_Credentials") {
//alert(a.responseText);
$("#Empty_Error").fadeOut("fast");
$("#WrongPW_Error").fadeIn("fast");
}
}
and here is the php file
<?php
if(!isset($_POST['username']) || !isset($_POST['password'])){
echo "Empty_Fields";
die();
}
$username = $_POST['username'];
$password = $_POST['password'];
$hashed_pass = hash("sha512", $password);
$stmt = $dbh->prepare("SELECT Count(email)as total, username from Users where email = :username and password= :password");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $hashed_pass, PDO::PARAM_STR);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$total = $row['total'];
if($total == 1){
session_start();
$_SESSION['user'] = $username;
$_SESSION['user_name'] = $row['username'];
echo "LoggedIn";
die();
}
else{
echo "Wrong_Credentials";
die();
}
?>
You are not performing the correct check in PHP to see if the POST variables are empty.
Read: What's the difference between 'isset()' and '!empty()' in PHP?
isset($_POST['username'])
will return true if the POST parameter exists, even if its content is an empty string. You need both tests: isset AND empty.
if(!isset($_POST['username']) || !isset($_POST['password'])){
echo "Missing_Param";
die();
}
if(empty($_POST['username']) || empty($_POST['password'])){
echo "Empty_Fields";
die();
}
Edit: I did not notice that you're using async: false; leaving this answer for reference. In general it's a good idea to use non-blocking calls in JS so other UI elements aren't affected.
$.ajax does not return anything; it's an asynchronous call that will call a function when it completes. You'll need to do something like this:
$.ajax({
// other arguments here
success: function(data) {
// handle success
},
error: function() {
// handle error
}
});
More examples available here and here.
Instead of calling die() on your PHP code, send an error response. Call http_response_code(401) (not authorized response). Second issue is that $.ajax doesn't return a response and async = false has been deprecated and should not be used. Instead, define two functions for success and failure and just set those as the success and error parameters of your AJAX request.
$.ajax({
type: 'post',
data: 'username='+username+'&password='+password,
url: '/account/login.php',
async: false,
success: successFunction,
error: errorFunction
});
function successFunction(response){
$("#WrongPW_Error").fadeOut("fast");
$("#Empty_Error").fadeOut("fast");
$("#LoggedIn").fadeIn("fast");
setTimeout(location.reload(),2200);
}
function errorFunction(response){
$("#WrongPW_Error").fadeOut("fast");
$("#Empty_Error").fadeIn("fast");
}

My server side php doesn't get the data from my client side AJAX requiest

Here is my AJAX code:
$("#loginbutton").click(function(){
var email = $('#email').val();
var password = $('#password').val();
$.ajax({
url: 'login.php',
type: 'POST',
dataType: 'json',
data: { email:email, password:password},
success: function(data){
$("#samplediv").innerHTML ="Welcome";
}
});
});
And this is my PHP:
<?php
session_start();
$conn = mysqli_connect("localhost", "root", "", "getpet");
if(isset($_POST['email'])){
echo $_POST['email'];
}
?>
As you can see it will be a login system, but the php doesn't write out the $_POST['email']
variable. I think it is probably a syntax mistake, just I am too blind. I would really appreciate it if somebody can help me.
UPDATE:
Here is my whole php code, i think it's not relevant, but this is ther reason, why i use dataType: json.
<?php
session_start();
$conn = mysqli_connect("localhost", "root", "", "getpet");
if(isset($_POST['email'])){
echo $_POST['email'];
}/*
$results = array(
'success' => false,
'user_id' => "azaz",
'fname' => "",
'lname' => ""
);
if(!empty($_POST['email']) && !empty($_POST['password'])){
$email = $_POST['email'];
$password = md5($_POST['password']);
$sql= "SELECT * FROM users WHERE email = '$email' AND password = '$password'";
$rowsql = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($rowsql, MYSQLI_BOTH);
if(mysqli_num_rows($rowsql) == "1"){
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['fname'] = $row['fname'];
$_SESSION['lname'] = $row['lname'];
$results['success'] = true;
$results['user_id'] = $row['user_id'];
$results['fname'] = $row['fname'];
$results['lname'] = $row['lname'];
}
}
//echo json_encode($results);*/
?>
In your data object, your keys are not strings, but the variables that you have defined. Do it like that to have email and password taken literally:
data: { 'email':email, 'password':password},
i think this is a cross origin problem, but normaly this is shown in console. append a error ouput to your json and look for it, if it's a php error you will get noticed now.
$.ajax({
url: 'login.php',
type: 'POST',
dataType: 'json',
data: { email:email, password:password},
success: function(data){
$("#samplediv").innerHTML ="Welcome";
},
error: function (jqXHR, textStatus, errorThrown) {{
console.error('ajax response failed');
console.log(jqXHR.responseText);
}
});
$("#samplediv").innerHTML ="Welcome"; is wrong
you have a jquery element here and try to access with vanilla functions.
$("#samplediv").text("Welcome");
// or
$("#samplediv")[0].innerHTML = "Welcome";
if you open your browsers dev tools it should show you the error:
innerHTML is not a function of ...
-> make sure you call jQuery though :)
-> added document ready
-> added prevent default
-> use input instead of button is only my convenience
<script type="text/javascript">
$(document).ready( function() { /* only when everything is set up */
$("#loginbutton").click(function(e){
e.preventDefault();
var email = $('#email').val();
var password = $('#password').val();
$.ajax({
url: "login.php",
method: "POST", /* changed to `method` */
data: "email="+email+"&password="+password, /* MODIFIED */
success: function(data){
alert(data);
$("#samplediv").html("Welcome !");
},
error: function (request, status, error) { /* added error handling */
alert(request.responseText);
}
});
});
});
</script>
<div id="samplediv"></div>
<form action="#" id="form" method="post">
<p><input type="text" name="email" id="email" value="" /> email</p>
<p><input type="text" name="password" id="password" value="" /> pwd</p>
<input type="submit" id="loginbutton" value="GO" />
</form>
of course, make the input password type !
As I don't know why you connect (possible select ?) with DB, I just made php file simple, as follows :
<?php
/* login.php */
error_reporting(E_ALL); ini_set('display_errors', 1);
$email = $_POST['email'];
$pwd = $_POST['password'];
echo"[ email > $email / pwd : $pwd ]"; /* for example only, of course, not with real credentials */
?>
after edit of the original question, I saw php code and I would recommand
NOT using MD5 anymore but password_hash / password_verify
you should really consider using PPS : Prepared Parameterized Statements. This will help Preventing SQL injection

How to get id and type in php foreach loop and send to server via ajax?

So i have 2 files index.php and changeLikeDislike.php. I think the issue is where javascript is trying to get the type and id but I do not know how I would go about that. My javascript function is being called in the foreach->li->divs. It was working before like this: data: dataString, but I added schoolId into data of ajax as well so it's like this now data: {dataString:dataString, schoolId:schoolId},
index.php
<?php
$last_id = 0;
foreach ($list as $rs) {
$last_id = $rs['id']; // keep the last id for the paging
?>
<li>
<div style="width:100%; color:#000;">
<?php echo '<div class="product_like thumb-div"><img src="like.png" class="rating-image " onclick=changeLikeDislike("like","'.$rs['id'].'")> <br><span id="product_like_'.$rs['id'].'">'.$rs['pLike'].'</span></div>';?>
<?php echo '<div class="product_dislike"><img src="dislike.png" class="rating-image" onclick=changeLikeDislike("dislike","'.$rs['id'].'")><br> <span id="product_dislike_'.$rs['id'].'">'.$rs['pDislike'].'</span></div>';?>
</div>
</li>
<?php
}
?>
<script type="text/javascript">
//begin like and dislike
function changeLikeDislike(type,id){
var dataString = 'id='+ id + '&type=' + type;
$.ajax({
type: "POST",
url: "changeLikeDislike.php",
data: {dataString:dataString, schoolId:schoolId},
cache: false,
success: function(result){
if(result){
console.log('working');
}
}
});//end ajax
}
schoolId works in data but not dataString in ajax How would i go about grabbing those. My php file for reference:
//checks if school page id was brought and stores into variable
if (isset($_POST['schoolId'])) {
$schoolIdFinal = $_POST['schoolId'];
}else {
echo "nope";
}
if (isset($_POST['type'])) {
$type = $_POST['type'];
}else {
echo "nope type";
}
if (isset($_POST['id'])) {
$id = $_POST['id'];
}else {
echo "nope id";
}
my page is echoing out "nope type nope id"
Please change
data: {dataString:dataString, schoolId:schoolId},
to
data: {type:type, id:id, schoolId:schoolId},
to match the params to your PHP script.
data can either be a query string (like your dataString) OR a json struct (like {type:type, id:id, schoolId:schoolId}).
See the documentation of jQuery.ajax():
"The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}."
see http://api.jquery.com/jquery.ajax/
The issue is in the data bracket. change
data: {dataString:dataString, schoolId:schoolId}
to
data: {dataString:'dataString', schoolId:'schoolId'}
next time do a print_r of $_REQUEST or $_POST to see what fields are being recognized and in this case it looks like its not detecting anything.

AJAX PHP function onchange select box

I have a problem about which I am very confused. I have a select box with s dynamically generated using a mysqli query:
$result = mysqli_query($db, "SELECT * FROM `users` WHERE `user_id` > 0");
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
while($row = $result->fetch_assoc()){
echo '<option value = '.$row['user_name'].'>'.$row['user_name'] . '</option>';
}
echo '</select></form>';
I am completely new to AJAX, but I need to use jquery and ajax to pass the this.value variable to a php variable for use in a later query.
Here is my script (most of which was found online):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
$("#contacts").change(function() {
//get the selected value
var selectedValue = this.value;
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});
</script>
Now, when I click a value in the select box, nothing happens. There are no warnings or errors, etc.
Please help me.
p.s. function.php does exist. It is just a simple echo for now (for testing purposes)
UPDATE: HERE IS FUNCION.PHP:
<?php
/*$val = $_REQUEST['selectedValue'];
echo $val;*/
function function(){
$val = $_REQUEST['selectedValue'];
echo $val;
}
?>
UPDATE: Thank you everyone for all your help. I have now got it to work in that the network section of chrome inspect shows the function.php being requested however I still don't get the echo (I used external .js files to get it to work). My J query function is also successful (the success function echoes into the console)
Your select box has no ID and you are watching the change event of $("#contacts").
Change:
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
to:
echo '<html><form name="contacts" method="post"><select name="contacts" id="contacts"><option value="Contact list">Contact List</option>';
^^^^^^^^^^^^^ here
You also only need one event handler, so I have removed the inline one which doesn't seem to do anything anyway.
Edit: If the select is created using ajax as well, you need event delegation:
$("body").on('change', '#contacts', function() {
^^^^ for example
Edit 2: Your variable is called $_REQUEST['option'] and not $_REQUEST['selectedValue']. You are also not calling your -badly named - function so you will not get any output from php except from an error like Parse error: syntax error, unexpected 'function' ....
Call onchange function in select tag as below
echo '<form name="contacts" method="post"><select name="contacts" onchange="func(this.value)"><option value="Contact list">Contact List</option></form>';
Javascript src should be in head of the html page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
Add the above one in head of html. Update javacript as below
As onchange function is called in the select tag itself, following is enough
<script>
function func(selectedValue)
{
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
}
</script>
Updated php: If you must want to get value from function, you must call it. Otherwise, simply, you can make as below
<?php
if($_REQUEST['option'])
{
$val=$_REQUEST['option'];
echo $val;
}
?>
In .php file, receive it first-
$val = $_REQUEST['selectedValue'];
echo $val;
set an id attribute in your php code for the select tag and
please don't use the same value for the name attribute in form and select tags !!
just change your function to a 'body'.on, and give your elements an id of 'contacts'
$("body").on('change', '#contacts', function() {
//get the selected value
var selectedValue = $(this).val();
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});

Problems getting data from AJAX to PHP (and back)

The idea is that this script POSTs the value of the text input in my html form to emailform.php, which takes that data and adds it to a .txt file. I think what I'm having trouble with is setting the value of $email in the PHP to that of the html text input. As a result, currently when the script is triggered I get two alerts (first 'error' then 'complete', from the .fail and .complete functions) and then the page reloads. That's why I think the problem is with the information being returned from the PHP but maybe I'm wrong.
<form method="post">
<input type="text" name="email" value="" class="emailSubmitSidebar" placeholder=" Your Email">
<input type="submit" name="submit" value="Add" class="submitButton" id="subscribeButton">
</form>
<script type='text/javascript'>
$(document).ready(function() {
var subscribeButton = $('#subscribeButton');
subscribeButton.click(function() {
$.ajax({
url: 'emailform.php',
type: 'POST',
dataType: 'text',
data: {email: $("input[name=email]").val()},
})
.done(function(data) {
alert("Added!");
})
.fail(function() {
alert("error");
})
.always(function() {
alert("complete");
})
})
})
</script>
And below is the PHP, I've added the first two lines to check for any errors, of which there are none anymore. What's strange is that when I run the PHP separately, the echo line prints the number 3 on the page without any apparent cause. I commented out the variable $email because I was led to believe it was better/necessary to first check if it isset.
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$fileHandle = fopen('emailList.txt', 'a') OR die ("Can't open file\n");
$email= isset($_POST['email']) ? $_POST['email'] : "";
// $email=$_POST['email'];
$result = fwrite ($fileHandle, "$email; \n");
fclose($fileHandle);
echo (!$result) ? "error" : $result;
die;
?>
I think there is something wrong with your data, try to serialize it into a json data array:
var data = $(form).serialize();
$.ajax({
url: 'emailform.php',
type: 'POST',
dataType: 'text',
data: data,
})
The values will be sent as a normal post request, so the email address will be in $_POST['email'];
Updated from here
The jquery .done() and .fail() functions require http status codes to work, so your php file should return these codes. When a request is made and succeeded anything in the 200 range will be ok. While on an error, something from the 400 or 500 range should be returned. There is a full list here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
So the ajax .success function is fired when 2xx is returned (replace .done with .success) and the .error is called when status code 4xx or 5xx is returned. See php below how to implement this.
The number 3 you are getting is the $return value of the fwrite function, according to: http://nl3.php.net/fwrite
fwrite() returns the number of bytes written, or FALSE on error.
Make your php like this:
<?php
//ini_set('display_errors', 'On');
//error_reporting(E_ALL);
if($fileHandle = fopen('emailList.txt', 'a')) {
if(isset($_POST['email']) && !empty($_POST['email'])) {
$email = $_POST['email'];
$result = fwrite ($fileHandle, "$email; \n");
fclose($fileHandle);
if(isset($result) && !empty($result)) { // Something was written
http_response_code(200);
echo "File written";
} else { // Writing failed
http_response_code(500);
echo "Writing of file failed";
}
} else { // Empty email
http_response_code(500);
echo "Email was empty";
}
} else { // File could not be opened
http_response_code(500);
echo "File could not be opened for writing";
}
?>
(Simple)
Change HTML to:
<input type="text" name="email" value="" class="emailSubmitSidebar" placeholder=" Your Email">
Change JS to :
$.ajax({
url: 'emailform.php',
type: 'POST',
dataType: 'text',
data: {email: $("input[name=email]").val()}
})
.done(function(data) {
// there checking
alert("success!")
})
Change PHP to:
$fileHandle = fopen('emailList.txt', 'a') OR die ("Can't open file\n");
$email=$_POST["email"];
$result = fwrite ($fileHandle, "$email; <br/>");
fclose($fileHandle);
echo (!$result)? "error" : $result;
die;

Categories