I want to fetch data when onclick is invoked. I have four div in my form and I want only a particular div to be reloaded and fetch data. while loading it should not discard the form data. Anyone help. Thanks in advance for people who are going to help me in this.
my code looks something like this
<div id="fetch">
<?php
//query to fetch data
?>
</div>
<div id="data4">
//dynamic data
//Want to retain this data even after fetch
</div>
In this case you should use AJAX.
Onclick you can send a xmlhttprequest (JS) to a separate php file, which returns the data you need (for example as string / JSON), and insert it into your website with JS.
Example:
function test()
{
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if(xhr.readyState==4 && xhr.status==200)
{
result = xhr.responseText;
document.getElementById("test_field").innerHTML = result;
}
}
xhr.open("GET","your_ajax_file.php",true);
xhr.send();
}
your_ajax_file.php returns the data you want to insert.
You mentioned you have a problem with function call, but you did not give more information. so i will give you an example how to write an ajax request, then you can maybe give me more detailed info on where your problem is.
$.ajax({
url: 'ajax_file.php',
type: 'post',
data: {var1: 'value1', var2: 'value2'},
success: function( data ){
console.log('ajax request successful! data: '+data);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
And in your ajax_file.php do something like this:
<?php
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
echo $var1.', '$var2;
edit: typo, changed val2 to var2 in ajax request
Related
I have a html with some javascript in in, now I want to run another php-file (test.php) without showing or opening this file. It's part of a loop and I tried:
for(i = 1; i < length; i++){
var bname = table.rows[i].cells.item(0).innerHTML;
var bvalue = table.rows[i].cells.item(1).innerHTML;
location.href = "test.php?account="+account+"&key="+key+"&memo="+memo+"&bname="+bname+"&bvalue="+bvalue;
}
But this will redirect the current location and runs only once...
I also tried to use:
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","test.php?account="+account+"&key="+key+"&memo="+memo+"&bname="+bname+"&bvalue="+bvalue);
xmlhttp.send();
But that seems not to work.
I also found the hint to use ajax, but I never used it and don't know how to pass my variables to test.php.
Thanks for your help!
You can do using ajax,
$.post("test.php",
{
account: account,
key: key,
memo:memo,
bname:bname,
bvalue:bvalue
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
use ajax to send data from javascript to a php file
vars="account="+account+"&key="+key+"&memo="+memo+"&bname="+bname+"&bvalue="+bvalue;
var ajaxhr = new XMLHttpRequest();
var url = "test.php";
ajaxhr.open("POST", url, true);
ajaxhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxhr.onreadystatechange = function() {
if(ajaxhr.readyState == 4 && ajaxhr.status == 200) {
var return_data = ajaxhr.responseText;
}
}
ajaxhr.send(vars);
I am posting this for a detailed answer to help PHP and Javascript side.
I would use jQuery + AJAX. Reference: http://api.jquery.com/jquery.ajax/
Ajax is great for sending data to php, reading data from php etc..
Please take time to look at my reference to read up on how it all works for future knowledge!
Lets get into the code!
Ajax (Javascript - Client Side):
var memoData = "Today is beautiful"; //Varible passed for ajax data
$.ajax({
url : '/LocationToTestPHP/test.php', //Location to PHP File
cache: false,
type: 'POST', //Type of method - Remove this line for GET if required
data: {account: "Welcome", key: "ValueHere", memo: memoData, bname: "ValueHere", bvalue: "ValueHere"} //Data to send to PHP
}).done(function(data)
{
//We check if PHP sent us back the correct data required here.
if(data == "Success")
{
alert("Success! Data returned is: " + data);
}
else
{
alert("Error! We didnt get correct data back. Data: " + data);
}
});
Please note, i provided a variable into ajax data for memo, this is
also possible.
PHP (Server Side) - test.php:
<?PHP
//Check for our value and return data
if($_POST['account'] == "Welcome") //Check if account has Welcome passed in..
{
echo "Success";
}
else //Welcome is not provided
{
echo "Account did not equal to Welcome :(";
}
?>
I quickly typed this up so hopefully you get the correct idea! Any help required, comment below :)
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.
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.
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.
one.php:
HTML:
<button value="testValue" name="foo">Click</button>
Javascript:
var keyVals = {foo:"bar"}
$(function() {
$("button").click(function() {
$.ajax({
type:"POST",
url:"two.php",
data: keyVals,
success: function() {
$("#center").append("<p>Data Transfer succeeded! </p>");
}
});
});
});
Now, what actually happens with the data? How can I use it in two.php? Say I want to save it in a file/database, why not save it directly from one.php?
I've tried the following:
two.php:
<?php
var_dump($_REQUEST);
?>
Comes out as empty. So what ACTUALLY happens with the data I sent from one.php? How can I use it?
Strangely enough, I've looked at every similar question to this I could find, and none of them were answered properly, and most of them were downvoted. What's wrong with this question?
send data like this -
data: { value : $(this).val() },
on php access it like this -
$value = $_POST["value"];