Comparing strings in JQuery not working - javascript

Alright so here's the situation. I have the following code block in my php file, and for some reason, whenever it comes to check data, it doesn't accept. I've printed out the value of data, and it is indeed "accepted" (without quotes obviously). Am I comparing these wrong somehow? Running basically the exact same code in another section of my website and it works fine.
$(document).ready(function () {
$("#sign").click(function () {
jQuery.ajax({
url: "loginConfirm.php",
data: { // Correct
username: $("#username").val(),
password: $("#password").val()
},
type: "POST",
success: function (data) {
if ($("#username").val() === "") {
//Do nothin
} else if (data === "accepted") {
alert("Here");
redirectSignIn();
} else {
alert("There");
$("#signInTitle").html(data);
}
},
error: function () {}
});
});
});
EDIT: php code I'm calling in the url below
<?php
// The global $_POST variable allows you to access the data sent with the POST method
// To access the data sent with the GET method, you can use $_GET
$username = htmlspecialchars($_POST['username']);
$userpassword = htmlspecialchars($_POST['password']);
require_once("dbcontroller.php");
$db_handle = new DBController();
$result = mysql_query("SELECT count(*) FROM loginInfo WHERE userName='" . $username . "' AND password='" . $userpassword . "'");
$row = mysql_fetch_row($result);
$user_count = $row[0];
if($user_count>0)
echo "accepted";
else
echo "denied";
?>

You cant validate if ($("#username").val() === "") { in success function. For that you are suppose to validate it before making Ajax call.

I would like to give some advice here that first you have to validate the inputs of the user if validate then you can call ajax.
and then you not required to check the value of the username in AJAX process.
Like....
if($("#username").val() === "" && $("#passoword").val() === "")
{
//AJAX call
}
else
{
//alert to enter the valid inputs
}
hope you get it my concept...

Related

Passing js variable to php using ajax does not work

I want to get variable rating_idex in my php file so if is user click button #add-review it should pass in ajax variable and it will get array in php file and send review to the database, but it is not working and I don't see solution
$('#add-review').click(function(){
var user_name = $('#reviewer-name').val();
var user_review = $('#review').val();
console.log(user_name);
console.log(rating_index);
console.log(user_review);
if(user_name == '' || user_review == '')
{
alert("Please Fill Both Field");
return false;
}
else
{
$.ajax({
url:"rating-data.php",
method:"GET",
data:{
rating_index: rating_index,
user_name: user_name,
user_review: user_review
},
success:function(data)
{
$('#review_modal').modal('hide');
load_rating_data();
console.log(data);
}
})
}
});
This is my php code when I can get the variable and send them to the database:
<?php
include 'connection.php';
echo ($rating_index);
if(isset($_GET["rating_index"]))
{
$data = array(
':user_name' => $_GET["user_name"],
':user_rating' => $_GET["rating_index"],
':user_review' => $_GET["user_review"],
':datetime' => time()
);
$query = "
INSERT INTO review_table
(user_name, user_rating, user_review, datetime)
VALUES (:user_name, :user_rating, :user_review, :datetime)
";
$query_run = mysqli_query($conn, $query);
if($query_run){
echo "Your Review & Rating Successfully Submitted";
} else{
echo '<script type="text/javascript"> alert("Something went wrong") </script>';
echo mysqli_error($conn);
}
}
?>
When I am trying to echo ($rating_index) it give me feedback that variable does not exist so it is something with ajax but can't find solution, thanks in advance for any solutions
Instead of echo ($rating_index); try echo ($_GET["rating_index"]); reason being you didn't actually declared $rating_index
if I'm not wrong you want to pass the PHP variable in javascript?
if yes you cant pass the PHP variable in js like this.
var x = " < ? php echo"$name" ? >";
you can pass your PHP variable like this but in only the .php file not in the .js

Data Not inserting to DB - PHP MYSQL

Trying to get together the sign up validation with PHP and Ajax. Not sure what is wrong but the submission does not happen. If I don't add the validation part everything looks fine and i am able to insert the data to mysql.
<script type="application/javascript">
$("#submit").submit(function (event) {
event.preventDefault();
var datatopost = $(this).serializeArray();
console.log(datatopost);
$.ajax({
url: "signupregister.php",
type: "POST",
data: datatopost,
success: function (data) {
if (data) {
$("#signupmessage".html(data));
}
},
error: function () {
$("#signupmessage").html("<div class = 'alert alert-danger'></div>")
}
});
});
</script>
_
<?php
session_start();
include('mysqlconnection.php');
include('index.php');
function customError($errors, $errorslevel)
{
}
set_error_handler("customError", E_ALL);
if (isset($_POST['submit'])) {
if ($_POST($first_name) == "") {
$errors .= $first_nameError;
} else {
$first_name =
filter_var($_POST["first_name"], FILTER_SANITIZE_STRING);
}
}
if ($errors) {
$resultMessage = '<div class="alert alert-danger">' .
$errors . '</div>';
echo $resultMessage;
exit;
}
$first_nameError = '<p>first name required</p>';
First up, in your validation PHP script, you won't need to include 'index.php'
Try redirecting the form to an empty page where you only include your validation data, while setting a session variable for the first error encountered.
At the end of your validation, if your error variable contains an error, you can redirect to the form and display your said error at a convenient location. Keep in mind you will have to save form data in session variables if you want to preserve all user input (thus removing the hassle of refilling the form over and over again).
If it doesn't, you can proceed to insert the data in your db then redirect to your desired landing page.
Here's a sample code based on your input:
<?php
session_start();
if(isset($_POST['submit'])){
$_SESSION['fname'] = $_POST['fname'];
//so on for your other variables
if($_SESSION['fname'] == ""){
$_SESSION['err'] = "First Name Required";
}
if(//insert your format validation for first name){
$_SESSION['err'] = "First Name Invalid";}
}
//end of validation
if isset($_SESSION['err']){
header('Location: myform.php');
}
else{
//save all your variables into normal ones, i.e $fname-$_POST['fname'];
//insert into database;
//check correct insertion;
//redirect to landing page;
}
}
?>

AJAX to PHP --> PHP not picking up the pass

I am still a noobie and still learning, but I can't understand why the data from an AJAX call is not being passed successfully into the PHP.
Where have I gone wrong here? I have literally spent hours on hours and I can't understand why the AJAX call hasn't posted this into the PHP. I believe there must be something wrong with either the data attribute from " data: name+email" in the ajax call OR there is something wrong in the PHP side retrieving the data post from AJAX....
I am totally confused...
Thanks for your help (and go easy on me!)
Thanks
<?php
include_once 'db.php';
$fullname = $_POST['name'];
$email = $_POST['email'];
//this is the new stuff we are putting in
mysqli_select_db('table1');
if(isset($_POST['email']))
{
$checkdata = "SELECT signup_email_of_user FROM table1 WHERE signup_email_of_user = '$email'";
$query = mysqli_query($conn, $checkdata);
if(mysqli_num_rows($query) > 0)
{
echo "err";
exit();
}
else {
$sql = "INSERT INTO table1 (signup_name_of_user, signup_email_of_user) VALUES ('$fullname', '$email')";
mysqli_query($conn, $sql);
echo 'ok';
die;
}
}
?>
function submitform1(){
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var name = $('#signup_name_of_user').val();
var email = $('#signup_email_of_user').val();
if(name.trim() == '' ){
alert('Please enter your name.');
$('#signup_name_of_user').focus();
return false;
}else if(email.trim() == '' ){
alert('Please enter your email.');
$('#signup_email_of_user').focus();
return false;
}else if(email.trim() != '' && !reg.test(email)){
alert('Please enter valid email.');
$('#signup_email_of_user').focus();
return false;
}else{
$.ajax({
type:'POST',
url:'test_signup.php',
data: name+email,
beforeSend: function () {
$('.btn-light').attr("disabled","disabled");
$('.sign-up').css('opacity', '.5');
},
success: function(msg){
if(msg == 'ok'){
$('#signup_name_of_user').val('');
$('#signup_email_of_user').val('');
$('.statusMsg').html('<span style="color:green;">Thanks for contacting us, we\'ll get back to you soon.</p>');
}else{
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
}
});
}
}
This is indeed wrong:
data: name+email
Values are sent as key/value pairs. All you're sending is a value without a key. How would the server-side code know how to retrieve that value without a key? Instead, consider something like this:
data: { 'name': name, 'email': email }
Then server-side you can retrieve the values by their keys:
$_POST['name']
or:
$_POST['email']
Note: The keys don't need to be the same name as the variables which hold the values. They just seem to be reasonably applicable names in this case. You could just as easily do this:
data: { 'first': name, 'another': email }
and retrieve the values with the updated keys:
$_POST['first']
As your form grows in complexity, there are a variety of ways to create an object in JavaScript to define the keys and values. You could serialize an entire <form> in a single line of code, for example. Or perhaps define more complex objects in JSON, serialized, and then de-serialize them server-side. But starting with some simple key/value pairs would work just fine here.
Your data seems to be malformed, try this:
var data = {};
data.name = $('#signup_name_of_user').val();
data.email = $('#signup_email_of_user').val();
and in the ajax: data: data,
According to jQuery documentation data attribute accepts following formats:
Type: PlainObject or String or Array
where the PlainObject is the one we need here:
var data = {'objectmember': 'objectvalue'};

String with special chars from Ajax POST to DB insert

i have a form with some text inputs, then i have an ajax event to send this value via POST to my database php script, the issue is that i dont know how to send special chars from my ajax event, if the string has ' " \ or similar chars, it wont insert data to my database, but if the string only contains Numbers/Letters and no special chars...i can insert the data without a problem.
Ajax event
$$("#message").click(function(e) {
var nick_ = window.localStorage.getItem("username");
var message_ = $.trim(($("#msgtext").val()).replace(/(\r\n|\n|\r)/gm,""));
if (message_ .length>0 && message_ .length<=500)
$.ajax({type: "POST",
url: "insert.php",
data: ({nick: nick_, mensaje: message_ }),
cache: false,
dataType: "json",
success: function(data) {
if(data.status == 'success'){
$('input[type=text], textarea').val('');
}
}});
else myApp.alert('Min:1 Max:500','Chars:');
});
And this is my database script
<?php
//jSON
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
//Connect to DB
include('con.php');
//POST vars
$nick=htmlspecialchars(trim($_POST['nick']));
$message=htmlspecialchars(trim($_POST['mensaje']));
$date=date("Y-m-d H:i:s");
//DB insert
$mysqli->real_query("INSERT INTO messages VALUES ('0','$nick','$message','$date')");
if ($mysqli) $response_array['status'] = 'success';
else
$response_array['status'] = 'error';
echo json_encode($response_array);
?>
before sending your data ({nick: nick_, mensaje: message_ }) in ajax, you can verify it using:
function isValid(data){
for (i in data){
if(!data[i].match(/^[a-zA-Z0-9]*$/))
return false;
}
return true;
}
use it like:
isValid({nick: nick_, mensaje: message_ })
this will return true if the data is either letter or character, and false otherwise.
Moreover, you should not be relying on any client side script for this kind of validation.
The problem is in your php script. Try this
$v = trim($_POST['mensaje']);
$message = htmlspecialchars($conn->escape_string($v));
All i did is to escape the post value.
And also the way you are checking if your query was sucessfull should be changed. you are checking the conn object instead of catching a return boolean value from the $conn->real_query () which should give you the real outcome of your query processing (True of false).
$result = $conn->real_query("........);
if ($result){
//do something
}else{
echo $conn->error;
}
If you have a form you can try data:$(this).serializeArray() which escapes those characters
OR
You can use an editor which I would recommend something like tinyMCE.

How to pass row name from php to ajax using jquery

I have a table in which the details are fetched from the DB.
if(mysql_num_rows($sql) > 0)
{
$row_count_n=1;
while($rows=mysql_fetch_assoc($sql))
{
extract($rows);
$options1 = select_data_as_options("project_resources", "name", $resource_allocated);
$options2 = select_data_as_options("project_roles", "name", $role);
echo "<tr>";
echo "<td><select name='ra_$row_count_n'><option value=''>-- Select --$options1</option></select></td>";
echo "<td><select name='role_$row_count_n'><option value=''>-- Select --$options2</option></select></td>";
echo "<td><input type='text' name='start_date_tentative_$row_count_n' class='date_one' value=$tentatively_starts_on /></td>";
echo "</tr>";
$row_count_n++;
}
}
I wanted to update the table when required, am doing this using Ajax by collecting data from the form using Jquery and saving it on button click.
$("#save_changes_id").click(function()
{
// To retrieve the current TAB and assign it to a variable ...
var curTab = $('.ui-tabs-active'); // in NEWER jQueryUI, this is now ui-tabs-active
var curTabPanelId = curTab.find("a").attr("href");
if(curTabPanelId == "#tab_dia")
{
var curTab = $('#sub_tabs .ui-tabs-active');
var curTabPanelId = curTab.find("a").attr("href");
}
responseData = doAjaxCall($(curTabPanelId + " form"));
if(responseData == 1)
showMessage('status_msg', 'Project details updated successfully', 'green');
else
showMessage('status_msg', 'Error: Please check all the fields', 'red');
});
function doAjaxCall(objForm)
{
var values = objForm.serialize();
$.ajax({
url: ajaxURL,
type: "post",
data: values,
async: false,
success: function(data)
{
responseData = data;
},
error:function()
{
alert('Connection error. Please contact administrator. Thanks.');
}
});
return responseData;
}
Ajax code is as below:
case "allocate_ba_details":
for($i=1; $i<=$row_count; $i++)
{
$resource = $_REQUEST["ra_$i"];
$role = $_REQUEST["role_$i"];
$start_date_tentative = $_REQUEST["start_date_tentative_$i"];
$already_available_check = mysql_num_rows(mysql_query("select * from project_allocate_ba where project_id = $pdid"));
if($already_available_check > 0)
{
$sql = ("UPDATE project_allocate_ba SET resource_allocated='$resource', role='$role', tentatively_starts_on='$start_date_tentative' WHERE project_id=$pdid");
}
}
echo $sql;
break;
As I am new to this am not sure how to pass the row name in order to update a particular row.
Please suggest a solution. Thanks in advance.
firstly use PDO or some php framework that has nice API to work with mysql. Second don't use success/error callback in jquery is too deprecated. Instanted use done/fail.always.
I understand that you want update row in html table data from the server ?
In success callback simply update the table using jquery text method for jquery object. You don't paste all code so i write example:
in server.php
<?php
[...]
$already_available_check = mysql_num_rows(mysql_query("select * from project_allocate_ba where project_id =" . intval($pdid)));
[...]
echo $already_available_check;
?>
This code return the integer, so in doAjaxCall:
function doAjaxCall(objForm)
{
var values = objForm.serialize();
$.ajax({
url: ajaxURL,
type: "post",
data: values,
async: false,
success: function(data)
{
if(typeof data !== 'undefined' && $.isNumeric(data)) {//check that server send correct anserw
$('whereIsData').text(data);
}
},
error:function()
{
alert('Connection error. Please contact administrator. Thanks.');
}
});
}
Now in success method you populate some DOM element using text method. You cannot simply return data from ajaxCall method because $.ajax is asynchronized method and responseData has value only when ajax request ends, so always return undefined in you example. You must present responseData to the user in success callback method.
For one thing...
$sql = ("UPDATE project_allocate_ba SET resource_allocated='$resource', role='$role', tentatively_starts_on='$start_date_tentative' WHERE project_id=$pdid")
needs single quotes around $pdid
Also don't echo the $sql. Instead do your inspection and form a response.
$response = array();
if(EVERYTHING_IS_GOOD){
$response['status'] = 'good to go';
}else{
$response['status'] = 'it went horribly wrong';
}
echo json_encode($response);

Categories