JavaScript events, mixed with PHP? - javascript

I have encountered a huge error for an idea I came up with. So I am working on a project, on my main website and we needed to put up a being worked on page, yadayda but I wanted to add the functionality of letting the user send us their email , but after we received that data a pop dialog would show.. But this doesn't work as I would like for it to.
So what I need help with, is actually the PHP and the JavaScript event to make it acknowledge that the message and email was sent, then show the dialog box. Does anyone know how to do this? Or maybe at least how to make a dialog show after a user did something, like entered information rather then just clicking a button? If anyone can help I would ridiculously appreciate it!

If you use jQuery, you can make an AJAX call to your serverside script and use the success callback to initiate the dialog on the client side.
$.ajax({
url: 'ajax/test.php',
data: { name: "WeLikeThePandaz", email: "panda#gmail.com" },
success: function(response) {
if (response.status == "OK"){
// Show dialog
}else{
// Let the user know there were errors
alert(response.error);
}
}
},'json');
Here is the relevant documentation for using the $.ajax method -
http://api.jquery.com/jQuery.ajax/
Your server side PHP code in ajax/test.php can then decipher the data that was sent and assemble a json object to be returned to the jQuery -
<?php
$err= '';
$name = sanitizeString($_POST['name']);
$email = sanitizeString($_POST['email']);
// note the sanitization of the strings before we insert them - always make sure
// to sanitize your data before insertion into your database.
// Insert data into database.
$result = mysql_query('INSERT INTO `user_table` VALUES...');
if (!$result) {
$status = "FAIL";
$err = mysql_error();
}else{
$status = "OK";
}
echo json_encode(array('error'=>$err,'status'=>$status)); // send the response
exit();
?>

Related

PHP records not inserted to database using Ajax

here is the AJAX request body
Ajax
var date = new Date().toLocaleTimeString();
var text=this.value;
var id=1;
$.ajax({
type: "GET",
url: "StoreMessages.php" ,
data: { room: id, msg:text,sendat:date }
});
PHP Code
if(isset($_GET['room']))
{
$chatroom_name = $_GET['room'];
if(isset($_GET['msg']))
{
$text= $_GET['msg'] ;
if(isset($_GET['sendat']))
{
$local_time= $_GET['sendat']);
insertMessage( $text,$local_time, $chatroom_name);
}
}
}
function insertMessage($message_body,$local_time,$room_id)
{
echo "<script type='text/javascript'>alert('$message_body');</script>";
echo "<script type='text/javascript'>alert('$local_time');</script>";
echo "<script type='text/javascript'>alert('$room_id');</script>";
$conn = new mysqli($GLOBALS['server'], $GLOBALS['user'], $GLOBALS['pass'], $GLOBALS['db_name']);
if($conn==false)
{
die("unable to connect database");
}
$sql="INSERT INTO `message` (`Message_Text`, `Time`, `Conversation_Id`) VALUES ('$message_body', '$local_time', '$room_id')";
if(mysqli_query($conn,$sql)){
echo "record inserted successfully"."<br/>";
}
else{
echo "error".mysqli_error($db_conn);
}
Explanation
ajax call triggers when user typed message and hit enter key ajax data field variable contains value i checked then by setting alert when i checked the the data field variables value by setting alert in php code there only text variable contain value and alertbox didn't appears for other variables acutally i am trying to store live chat to database
The first step to debugging this is is/was diagnosing where the failure occurred. To do this:
Open your developer console
Go to the network tab
Make whatever action triggers the AJAX request
Click the request that appears in the network tab
Go to the response tab*
*If the status code of the request is a 500 that also is an indication that the script is failing on the PHP side. Go to the server and look at the error logs.
From the response we got in the response tab we identify the issue to be the trailing closing parenthesis on this line:
$local_time= $_GET['sendat']);
Additionally you should use parameterized queries. A single quote in any of the fields will break your query.
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
Roughly:
$sql="INSERT INTO `message` (`Message_Text`, `Time`, `Conversation_Id`) VALUES (?, ?, ?)";
Then prepare that, bind the values, and execute the query.
Also I'd send back a JSON object rather than JS code. Take a look at http://php.net/manual/en/function.json-encode.php.

Really bizarre bug when using jquery ajax and php

I'm trying to create a like button for different images posted by user. This is my html :
Like
This is my javascript:
<script>
$(function(){
$(".likes").click(function(){
var postid = $(this).attr("id");
alert(postid);
$.ajax({
type:'POST',
url:'likes.php',
data:'id='+postid,
success:function(data){
alert("success");
}
});
});
});
</script>
This is likes.php, for testing purpose it's quite simple:
<?php
require('config.php');
$postid=$_POST['id'];
echo $postid;
?>
When I clicked the like button, a small window will correctly postid, and then "success",which indicates that the ajax is successful, however, when I opened likes.php, I got an error that says: Notice: Undefined index: id in C:\XAMPP\htdocs\likes.php on line 3
I tried adding e.preventDefault(). I tried different syntax,such as data:'id='+postid, data:{id:postid},data:{'id':postid},etc. I experimented with basically all combinations of single quotes and double quotes. I also tried adding datatype:html and datatype:text. Every time I just got a alert that says "success", but when I open likes.php, $_POST['id'] is always undefined.
Can someone help me please this bug took me a lot of time.
Update: I found that even if I entered a completely non-existing url, like url:"aabbll.php", after I clicked the "like" button, I would still see a window that alerts "success", why does the page keep alerting "success" even though clearly the AJAX process wasn't a success?
You are not sending the post variable "id" when you are opening like.php in a new browser window.
The error "Notice: Undefined index" is shown because the $_POST array does not contain the id field.
You can use a chrome extension called postman to test endpoints with post variables.
A tip to improve the code could be to wrap it in an if isset statement
if(isset($_POST['id'])){
// this code will only be executed if the post variable is sent to the page
$postid=$_POST['id'];
// update database
echo "Success";
}else{
echo "ERROR: No id post variable found";
}
Your javascript code is sending the post variable
Try to put var_dump($_POST) to see what you really post.
Couple of suggestions.
Your JS can be simply
<script>
$(function() {
$('.likes').on('click', function() {
var postid = $(this).attr('id');
$.post("likes.php", {id: postid}).done(function( data ) {
alert( 'Data Loaded: ' + data );
});
});
});
For your PHP
<?php
if (!isset($_POST['id'])) {
/// Do what you want to do in this case.
}
$id = $_POST['id'];
// If using PHP7
$id = $_POST['id'] ?? null;
Though $('.likes') works try to avoid that since it is slowest selector in most cases.

PHP inside Javascript in a registration form (for validation)

I'm developing a registration form for my site. Actually when a visitor choose an username, a php query to my MySQL DB is used to control if it's already used and if so, a javascript windowd appear.
Can i use a PHP query inside Javascript for displaing a real-time notice near the form (using HTML5)?
<script>
var username = document.getElementById('username');
var userdb = <? php control_username($username); ?>
var checkUsername = function () {
if (userdb.value == true) {
username.setCustomValidity('Username already used');
} else {
username.setCustomValidity('');
}
};
username.addEventListener('change', checkUsername, false);
</script>
and here there's the php function:
<?php function control_username($username){
$db=connessione_db();
$query = "SELECT username FROM utente WHERE username = '$username';";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_close();
if($row[0]==$username){
return TRUE;
}
else{
return FALSE;
}
$query=NULL;
}
how can i do?
You can use AJAX or jQuery AJAX to send a request to a php page, Check if the username exists, return the result, and display it using Javascript again.
Here is the jQuery sample:
<script>
$.ajax({
type: 'POST',
url : 'checkUsername.php',
data: {'username' : $('#username').html()},
cache : false,
success: function(data){
if(data == 'exists')
//username exists
alert('username already exists!');
},
error: function(request , status , error){
alert(request.resposeText);
}
});
</script>
and this should be your checkUsername.php file:
<?php
$db=connessione_db();
$query = "SELECT count(*) as count FROM utente WHERE username = '$username'";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_close();
if($row[count] > 0)
echo 'exists';
else
echo '';
PHP is run on the server, Javascript is run on the client's machine. Once your PHP script has generated a page and sent it to the user, it doesn't run any longer. Your client has no knowledge of a PHP script. It can't directly run, call, or read anything about your PHP script because it resides solely on the server (never on the client's machine). Your client's machine does, however, know about your Javscript since it has been sent along with the page. If you want to access PHP functionality from your page, you can either send a GET/POST call to the server and reload the page, or use AJAX to make the call in the background. Check out Jquery's implementation of AJAX calls, it makes using it pretty simple.
No you can't do it like that. PHP is serverside, Javascript clientside. The moment Javascript is executed is the code working clientside. All PHP code is fixed.
Compare it to the combination of HTML and PHP in an HTML page. It is fixed there as well. Same applies to PHP in Javascript.
Here are some answers from related questions on stackoverflow:
How to put php inside javascript?
How to embed php in javascript?
Here is an example from ajaxref, showing the basics:
http://ajaxref.com/ch3/asyncsend.html
This is another tutorial showing how an ajax call is handled:
http://code.tutsplus.com/articles/how-to-make-ajax-requests-with-raw-javascript--net-4855
I advice you to first understand this process and later on start using a framework like jQuery.

How to use send responses back to ajax and process each response separately

On Page1:
An AJAX script is processed loading Page2
On Page2:
A mysqli Database query will run, if the database query is successful, I want to send a success response back to AJAX query and reload the page. If the database query fails, I want to send a fail response back to AJAX query and redirect to fail page.
Is this possible? How would I write this? I'm new to AJAX and have reviewed some AJAX scripts and also read documentation, but I learn best by experimenting with code to find solutions that work for me. I have played with a few ajax scripts but can't get any of them to work correctly and can't find one that does anything near what I need. Seems like it would be a fairly easy ajax script, so I was hoping someone could help me with it.
Here's a possible jQuery solution. Let me know if you want pure JavaScript.
index.html
<input type="text" id="input" />
<button type="button">Submit!</button>
scripts.js
$('button').on('click',function() {
var val = $('#input').val();
sendQuery(val);
});
function sendQuery(x) {
var val = x;
$('body').load('query.php?input=' + val);
}
query.php
$mysqli = new mysqli('localhost','root','password','db');
$val = $_GET['input'];
$query = <<<Q
SELECT
*
FROM
table
WHERE
column = ?
Q;
$stmt = $mysqli->stmt_init();
if($stmt->prepare($query)) {
$stmt->bind_param("i",$val);
$stmt->execute();
while($stmt->fetch()) {
#if the query is successful
echo '<script>
$(function() {
location.reload();
});
</script>';
}
} else {
echo '<script>
$(function() {
window.location.href = "http://www.yoursite.com/errorpage.html";
});
</script>';
}
$mysqli->close();
The only thing I'm uncertain about is why you want to send a response back with AJAX, and then move to a completely new page. To me that kind of seems like that negates the reason you're wanting to use AJAX in the first place. Any thoughts?
What the above does is use jQuery to load XMLHTTPRequest.responseText into the body (the reponseText is the scripts that are echoed by your php doc). In this case, in the case of success from the db, it echoes a script that reloads the page. In the case of a failure, it echoes a script that moves the user to an error page.

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