So this one problem has taken me on a wild goose chase for a week or so now and I am really hoping that the problem will finally be able to be solved tonight. I'm not at all experienced with Ajax or JS so I really struggle here and am still learning. Here is what I hope to achieve...
I have a basic PHP messaging system in messages.php showing all messages between two users within a DIV which automatically adds a scroll bar when you receive more messages. Here is my DIV which does this:
<div class="list-group-message" style="overflow-y: scroll;height:385px;width:680px">
<div id="content">
/// PHP MESSAGE SCRIPT
</div>
</div>
When you send a reply, it uses this Ajax script to send that data to be processed on system/reply_system.php if it notices you are talking to an automated account, it will also send the data to system/sars_system.php to be processed, this works fine for adding, and sending back messages...
<script>
setInterval(function() {
$("#content").load(location.href+" #content","");
}, 5000);
</script>
<script>
function loadDoc() {
$.ajax({
url: 'system/reply_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
console.log("success");
var $content = $(".list-group-message");
$content.text(data); // Here you have to insert the received data.
$content[0].scrollTop = $content[0].scrollHeight;
// Second ajax
$.ajax({
url: 'system/sars_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
$content.text(data); // Here you have to insert the received data.
$content[0].scrollTop = $content[0].scrollHeight;
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
}
</script>
The nice gent who helped me with this script has informed me that I need to receive data back from system/sars_system.php and system/reply_system.php which basically look like this:
<?
require 'db.php';
$message = $_POST['message'];
$conversation_id = $_POST['conversation_id'];
$sarssystem = $_POST['sarssystem'];
$user_id = $_POST['user_id'];
$usr_message = str_replace("'","\\'",$message);
mysqli_query($conn,"INSERT INTO ap_messages (message_id, message, sender_id, time_sent, time_read, conversation_id)
VALUES ('','$usr_message','$user_id', NOW(), NOW(), '$conversation_id')");
mysqli_query($conn, "UPDATE ap_conversations SET time = NOW() WHERE conversation_id = '$conversation_id'");
echo json_encode('success');
?>
But I am having a real big problem trying to figure out how to do that or what data I even need to send back or how I go about coding that in to the current script? If this all works, the final aim is to automatically initiate sending the scroll bar to the very bottom of the page every time this Ajax script runs?
The ajax looks right because it is ready to receive data. In the php you can set the data to whatever you need, it could be the results of the database call. Here's a small example of sending some data back to the ajax script.
$data = array(
'status' => 'ok',
'message' => 'Customer account saved',
);
return json_encode($data);
If you know how to get whatever data you need on the server you can encode it and return it to the client.
The success method will run on the ajax object. It is passed the data and you can reference and manipulate/use it. Your code looks like it is already prepared for this:
success: function(data) { // <-- this is the data in json format from the server
console.log("success");
var $content = $(".list-group-message");
$content.text(data); // Here you have to insert the received data.
Related
I'm sorry but I'm having a hard time setting up something simple but that doesn't work for me. I'm trying to put a code that counts the number of clicks on a phone number ( the last 4 hidden digits that appear ) then record this data in my DB. I set up the JAVASCRIPT at the bottom of my PHP page where I will listen if there is a click ( Addeventlistener.... ) on the phone number.
I understood that we can not execute PHP code in a JS script, OK, so I execute an Ajax code to send to a PHP file the values to insert in a new entry to my DB. Except that during the execution the functions that open a connection to the DB are not recognized while in the same way I use others functions in the same PHP file that selects and returns me data from the DB.
Is the difference that they are two different types of request SELECT and INSERT or it is because I send the data through Ajax that the PHP files that load the function of DB connection are not loaded?
AJAX Script
<script>
var phoneclick = document.querySelector(".data-phone");
var baseUrl = "public_html/oc-content/themes/delta/"
phoneclick.addEventListener("click", function() {
var item_id = 8111;
var ajaxPhoneClick = 1;
$.ajax({
url: '<?php echo osc_current_web_theme_url('model/sql_projet.php'); ?>',
type: "GET",
data: {
id: '1111'
},
success: function(data) {
console.log(data);
}
});
});
</script>
PHP FIle
$itemId = $_GET['id'];
$conn = DBConnectionClass::newInstance();
$data = $conn->getDb();
$comm = new DBCommandClass($data);
$db_prefix = DB_TABLE_PREFIX;
$query = "INSERT INTO {$db_prefix}t_item_stats (item_id,phone_clicks) VALUES ($itemId,1) ";
$result = $comm->query($query);
The error i get is this Fatal error: Uncaught Error: Class 'DBConnectionClass' not found in /Applications/XAMPP/
I want to know the reason why this error is throwing and what should i do to bypass this
I am trying to get the contents from some autogenerated divs (with php) and put the contents in a php file for further processing. The reason for that is I have counters that count the number of clicks in each div. Now, I ran into a problem. When I echo back the data from the php file, the call is made, but I get undefined in the form-data section of the headers, and NULL if I do var_dump($_POST). I am almost certain I am doing something wrong with the AJAX call. I am inexperienced to say the least in AJAX or Javascript. Any ideas? The code is pasted below. Thanks for any help / ideas.
The AJAX:
$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).find(".test");
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#resultcart").html(returnhtml);
}
});
});
});
The PHP is a simple echo. Please advise.
Suppose you have a div
<div id="send_me">
<div class="sub-item">Hello, please send me via ajax</div>
<span class="sub-item">Hello, please send me also via ajax</span>
</div>
Make AJAX request like
$.ajax({
url: 'get_sorted_content.php',
type: 'POST', // GET is default
data: {
yourData: $('#send_me').html()
// in PHP, use $_POST['yourData']
},
success: function(msg) {
alert('Data returned from PHP: ' + msg);
},
error: function(msg) {
alert('AJAX request failed!' + msg);
}
});
Now in PHP, you can access this data passed in the following manner
<?php
// get_sorted_content.php
if(!empty($_POST['yourdata']))
echo 'data received!';
else
echo 'no data received!';
?>
It's sorted. Thanks to everyone. The problem was I didn't respect the pattern parent -> child of the divs. All I needed to do was to wrap everything in another div. I really didn't know this was happening because I was echoing HTML code from PHP.
I am trying to pass a JSON object that looks similar to this:
{"service": "AAS1", "sizeTypes":[{"id":"20HU", "value":"1.0"},{"id":"40FB","2.5"}]}
Just a note: In the sizeTypes, there are a total of about 58 items in the array.
When the user clicks the submit button, I need to be able to send the object to a PHP script to run an UPDATE query. Here is the javascript that should be sending the JSON to the PHP script:
$('#addNewSubmit').click(function()
{
var payload = {
name: $('#addservice').val();
sizeTypes: []
};
$('input.size_types[type=text]').each(function(){
payload.sizeTypes.push({
id: $(this).attr('id'),
value: $(this).val()
});
});
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {service: payload},
dataType: 'json',
success: function(msh){
console.log('success');
},
error: function(msg){
console.log('fail');
}
});
});
Using the above click function, I am trying to send the object over to php script below, which is in api/editService.php:
<?php
if(isset($_POST['service']))
{
$json = json_decode($_POST['service'], true);
echo $json["service"]["name"] . "<br />";
foreach ($json["service"]["sizeTypes"] as $key => $value){
echo $value["value"] . "<br />";
}
}
else
{
echo "Nooooooob";
}
?>
I do not have the UPDATE query in place yet because I am not even sure if I am passing the JSON correctly. In the javascript click function, you see the SUCCESS and ERROR functions. All I am producing is the ERROR function in Chrome's console.
I am not sure where the error lies, in the JavaScript or the PHP.
Why can I only produce the error function in the AJAX post?
Edit
I removed the dataType in the ajax call, and added JSON.stringify to data:
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {servce: JSON.stringify(payload)},
success: function(msg){
console.log('success');
},
error: function(msg){
console.log('fail'), msg);
}
});
In the PHP script, I tried this:
if(isset($_POST['service'))
{
$json = json_decode($_POST['service'], true);
foreach ($json["service"]["sizeTypes"] as $key => $value){
$insert = mysqli_query($dbc, "INSERT INTO table (COLUMN, COLUMN, COLUMN) VALUES (".$json["service"] . ", " . "$value["id"] . ", " . $value["value"]")");
}
}
else
{
echo "noooooob";
}
With this update, I am able to get the success message to fire, but that's pretty much it. I cannot get the query to run.
without seeing the error, I suspect the error is because ajax is expecting json (dataType: 'json',) but you are echoing html in your php
Try to change
error: function(msg){
console.log('fail');
}
to
error: function(msg){
console.log(msg);
}
There might be some php error or syntax issue and you should be able to see it there.
Also try to debug your php script step by step by adding something like
echo "still works";die;
on the beginning of php script and moving it down till it'll cause error, then you'll know where the error is.
Also if you're expecting JSON (and you are - dataType: 'json' in js , don't echo any HTML in your php.
As you are sending an object in your service key, you probably have a multi-dimensional array in $_POST['service'].
If you want to send a string, you should convert the object to json:
data: {service: JSON.stringify(payload)},
Now you can decode it like you are doing in php.
Also note that you can only send json back from php if you set the dataType to json. Anything other than valid json will have you end up in the error handler.
Example how to handle a JSON response from editService.php. Typically, the editService.php script will be the worker and will handle whatever it is you need done. It will (typically) send a simple response back to the success method (consider updating your $.ajax to use the latest methods, eg. $.done, etc). From there you handle the responses appropriately.
$.ajax({
method: 'POST',
url: '/api/editService.php',
data: { service: payload },
dataType: 'json'
})
.done(function(msh) {
if (msh.success) {
console.log('success');
}
else {
console.log('failed');
}
})
.fail(function(msg) {
console.log('fail');
});
Example /editService.php and how to work with JSON via $.ajax
<?php
$response = [];
if ( isset($_POST['service']) ) {
// do your stuff; DO NOT output (echo) anything here, this is simply logic
// ... do some more stuff
// if everything has satisfied, send response back
$response['success'] = true;
// else, if this logic fails, send that response back
$response['success'] = false;
}
else {
// initial condition failed
$response['success'] = false;
}
echo json_encode($response);
I have a modal that will display when the user clicks a delete button. Once they hit the delete button I am using AJAX to subimit the form. Eveything works fine, but it is not display my success message which is set in PHP.
Here is my AJAX code:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function () {
// This is empty because i don't know what to put here.
}
});
}
Here is the PHP code:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
} else {
$errors[] = lang("SQL_ERROR");
}
And then I call it like this:
<div class="col-lg-12" id="resultBlock">
<?php echo resultBlock($errors,$successes); ?>
</div>
When I use AJAX it does not display the message. This works fine on other pages that does not require AJAX to submit the form.
I think you are getting confused with how AJAX works, the PHP script you call will not directly output to the page, consider the below simplified lifecycle of an AJAX request:
Main Page -> Submit Form -> Put form data into array
|
--> Send array to a script to be processed on the server
|
|----> Callback from the server script to modify DOM (or whatever you want to do)
There are many callbacks, but here lets discuss success and error
If your PHP script was not found on the server or there was any other internal error, an error callback is returned, else a success callback is fired, in jQuery you can specify a data array to be received in your callback - this contains any data echoed from your PHP script.
In your case, you should amend your PHP file to echo your arrays, this means that if a successful request is made, the $successes or $errors array is echoed back to the data parameter of your AJAX call
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo $successes;
} else {
$errors[] = lang("SQL_ERROR");
echo $errors;
}
You can then test you received an object by logging it to the console:
success: function(data) {
console.log(data);
}
Well, it's quite not clear what does work and what does not work, but two things are bothering me : the function for success in Ajax is empty and you have a header function making a refresh in case of success. Have you tried removing the header function ?
success: function(data) {
alert(data);
}
In case of success this would alert the data that is echoed on the php page. That's how it works.
I'm using this a lot when I'm using $.post
Your header will not do anything. You'll have to show the data on the Java script side, maybe with alert, and then afterwards redirect the user to where you want in javascript.
you need put some var in success function
success: function(data) {
alert(data);
}
then, when you read var "data" u can do anything with the text
Here is what I changed the PHP to:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo resultBlock($errors,$successes);
} else {
$errors[] = lang("SQL_ERROR");
echo resultBlock($errors,$successes);
}
And the I changed the AJAX to this:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function (data) {
result = $(data).find("#success");
$('#resultBlock').html(result);
}
});
}
Because data was loading all html I had to find exactly what I was looking for out of the HTMl so that is why I did .find.
I m validating email id in php and ajax, and want to return value from php page to html in JSON format.
I want to keep that return value in php variable for the further use.
I'm doing these all in codeigniter, and I want to show .gif image while my AJAX is processing. (Pre loader image)
AJAX/Javascript/jQuery:
function checkEmail(value_email_mobile) {
if (value_email_mobile !== '') {
//alert('te');
$.ajax({
type: "POST",
url: url_check_user_avail_status,
data: "value_email_mobile=" + value_email_mobile,
success: function(msg) {
alert(msg);
//$('#psid').html("<img src='images/spacer.gif'>");
// $('#stat').html(msg);
//
//$('#sid').sSelect({ddMaxHeight: '300px'});
},
error: function() {
//alert('some error has occured...');
},
start: function() {
//alert('ajax has been started...');
}
});
}
}
PHP/Controller:
<?php
function check_email_or_mobile($param)
{
$ci = CI();
$value = $param['email_or_mobile'];
$query = "SELECT user_email , mobile FROM tb_users WHERE user_email = '$value' or mobile = '$value'";
$query = $ci->db->query($query);
if ($query->num_rows() > 0)
{
if (is_numeric($value))
{
return $res = "This mobile number is not registerd";
}
else
{
return $res = "This Email id is not registerd";
}
}
}
This is just to give you an example on how it will work.
First off, (obviously) there must the a preloader image ready inside the document. This must be hidden initially.
Second, before triggering the AJAX request, show the loading animated GIF.
Third, after the request if successful. Hide the image again inside your success: block inside the $.ajax().
Consider this example: Sample Output
PHP:
function check_email_or_mobile($param) {
// your functions, processes, blah blah
// lets say your processes and functions takes time
// lets emulate the processing by using sleep :)
sleep(3); // THIS IS JUST AN EXAMPLE! If your processing really takes time
$data['message'] = 'Process finished!';
// with regarding to storing, use sessions $_SESSION for further use
$_SESSION['your_data'] = $data_that_you_got;
echo json_encode($data); // use this function
exit;
}
// just a simple trigger for that post request (only used in this example)
// you really dont need this since you will access it thru your url
// domain/controller/method
if(isset($_POST['request'])) {
check_email_or_mobile(1);
}
HTML/jQuery/AJAX:
<!-- your animated loading image -->
<img src="http://i600.photobucket.com/albums/tt82/ugmhemhe/preloader.gif" id="loader" style="display: none;" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- <script type="text/javascript" src="jquery.min.js"></script> -->
<script type="text/javascript">
$(document).ready(function(){
// before the request, show the GIF
$('#loader').show();
$.ajax({
url: document.URL, // JUST A SAMPLE (url_check_user_avail_status)
type: 'POST',
data: {request: true},
dataType: 'JSON',
// data: "value_email_mobile=" + value_email_mobile,
success: function(response) {
// After a succesful response, hide the GIF
$('#loader').fadeOut();
alert(response.message);
}
});
});
</script>
My assumption is, since this is just a simple email checking, this wont really take a chunk of time. The other way is to fake the loading process.
success: function(response) {
// After a succesful response, hide the GIF
// Fake the loading time, lets say 3 seconds
setInterval(function(){
$('#loader').fadeOut();
alert(response.message);
}, 3000);
}
Let us know what part of your code is not working?
1) Check if the request flow is hitting the function checkEmail? PHP has inbuilt JSON converting utility json_encode. You could start using that.
2) If you want to store this on the server for further use, you could think about usage like
a) Storing it in Database (If really needed based on your requirements. Note: This is always expensive)
b) Session - If you would want this info to be available for all the other users too.
c) Or keep it in the memory like any of the caching mechanisms like memcache etc
3) For displaying the busy display,
// Before the below ajax call, show the busy display
$.ajax({
});
// After the ajax call, hide the busy display.
You could do this using JavaScript / JQuery on your choice.
I remember using
JSON.parse(data)
to convert JSON ino a javascript object.
Jquery has its own JSON parser btw. Something like $.JSONParse(data)