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.
Related
I am trying to send some variables to PHP script and then to upload them in MySQL db.
Here is my JS script:
$.ajax({
url: '/insert.php',
type: 'POST',
data: {endadres:endadres,stadres:stadres,amount_of_carriers:amount_of_carriers, price_finalized:price_finalized },
success: function(data) {
console.log(data);
}
})
All of variables are extisting inside the same function (I checked it via "alert()").
Here is my PHP code:
// Check connection
if($link === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_REQUEST['FirstName']);
$last_name = mysqli_real_escape_string($link, $_REQUEST['LastName']);
$start_adress = $_POST['startadress'];
$end_adress = $_POST['endadress'];
$Price = $_POST['finallprice'];
$CarriersQuant = $_POST['carriersamo'];
// Attempt insert query execution
$post = "INSERT INTO Orders (FirstName, LastName, StartAdress, EndAdress, Price, CarriersQuant) VALUES ('$first_name', '$last_name', '$start_adress', '$end_adress', '$Price', '$CarriersQuant')";
LastName and FirstName are taken from .html, and I can upload them into my DB, but I am not able to get variables from js.
Error from console:
The variable names in the ajax post doesn't correspond with what you try to extract in the receiving end (PHP). If you stick with these names in JavaScript:
data: {
endadres,
stadres,
amount_of_carriers,
price_finalized
},
You must use the same key to collect them in PHP:
$foo = $_POST["endadres"]
To debug, I often find it useful to add this debug output to see all posted variables:
var_dump($_POST);
On a second note (unrelated to your question though), your SQL insert statement is very dangerous. You are concatenating the variables directly from the external request into the database query string, which means that a potential offender could post something like:
carriersamo: "'; DROP TABLE Orders;"
which would drop your Orders table from your database. I recommend you read up on PHP's PDO module, where it's quite easy to prepare "safe" statements to the database. http://php.net/manual/en/book.pdo.php
I'm trying to send a JavaScript variable to a PHP script, use the variable in my SQL statement, and then send the results back to JavaScript.
JavaScript:
// Sending a variable to PHP script
var variableToSend = '30';
$.post('myPHPscript.php', {variable: variableToSend});
// Using the variable from earlier, run PHP script to get results
var data_from_ajax;
$.get('http://www.mywebsite.com/myPHPscript.php', function(data) {
data_from_ajax = data;
});
// Display results on the document
var displayResult = document.getElementById('displayResult');
displayResult.innerHTML = data_from_ajax;
PHP:
<?php
// Connection stuff
$conn = new mysqli($servername, $username, $password, $dbname);
// Get the sent variable
$variable = $_POST['variable'];
// Run SQL statement
$sql = "
SELECT column
FROM myDatabase
WHERE id=$variable
";
$result = $conn->query($sql);
// Send results back to JavaScript
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
echo $row["column"];
}
?>
The reason that JS is calling a PHP script is because I used an event listener in JS to determine the variable that I want to send. The variableToSend varies every time depending on what was clicked, but I have set it to some random number here.
I'm aware that the problem lies in sending variables to PHP scripts in the JavaScript, but I'm unsure how else I can do this, besides using .post and .get.
I also considered using an AJAX call, but I wasn't sure how that would work.
Thank you for any pointers.
You are already using ajax, twice, via $.post and $.get.
You only need to make the post request, and display the response:
// Sending a variable to PHP script via ajax post, and display the returned results
var variableToSend = '30';
$.post('http://www.mywebsite.com/myPHPscript.php', {variable: variableToSend}, function(responseFromPhp){
$('#displayResult').html(responsefromPhp);
});
The data you want will be returned on this post ajax call. To retrieve it specify success function.
$.post( "test.php", { name: "John", time: "2pm" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
and also use some validation and escaping before use post values in mysql:
http://php.net/manual/en/mysqli.real-escape-string.php
I'm currently making a WordPress plugin where I want to be able to send e-mail to people from a list. I have made the form (id: campaign), and all checkboxes seems to work. The form submit to itself with a query string, so in the same file I have a if-then that check if this query string has some data.
I have made an admin page with a sub form underneath that lists all e-mail addresses:
I want the script to send out e-mails to each e-mail that has been selected, updating the MySQL table that the mail has been sent, and showing a counter on the page (i.e. '#/15 e-mails sent'). I know how to make this script in plain PHP, but my lack of knowledge with AJAX is the problem.
So this is what I want:
The form sending data to itself (same PHP file) - this is working.
Starting the AJAX script based on the selected checkboxes
Sending out e-mails and updating the SQL table based on a timer (to avoid spam)
Showing real-time counter
This is what I have so far:
<div id="feedback"></div>
<?php
add_action('wp_ajax_sendPromo', 'sendPromo');
add_action('wp_ajax_nopriv_sendPromo', 'sendPromo'); // not really needed
?>
<script type="text/javascript">
jQuery('#campaign').submit(ajaxSubmit);
function ajaxSubmit(){
var campaign = jQuery(this).serialize();
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: campaign,
success:function(data){
jQuery("#feedback").html(data);
}
});
return false;
}
</script>
<?php
function sendPromo(){
global $wpdb;
$recepients = $_GET['recepients_email']; // array of checkboxes
for($i=0; $i < count($recepients); $i++){
mail($recepients[$i], $subject, $message, $headers); // mail is being sent
if($wpdb->update('wp_ap_promo',array(
'sent'=>1
), array( 'email' => '" . $recepients[$i] . "' ))===FALSE){
echo "Error";
}
else {
echo "Successfully sent to '".$recepients[$i]. "', row ID is ".$wpdb->update_id;
}
}
die();
}
One of the problems seems to be that the JS isn't being run because the page is reloading (it is meant to reload, because I want the user to see a plain page with the send counter.
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.
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();
?>