Ajax.stop function with json request issue - javascript

I am trying to read from a database some data but without waiting for the page to load, so I created an ajax post that starts sending data when page is ready, now after ajax completes I need to read the values from another file. The problem is that after the ajax completes, json that is reading the data is running indefinite.
JQUERY
<?php $url = $_GET['url']; ?>
var jQuery_1_11_0 = $.noConflict(true);
jQuery_1_11_0(document).ready(function () {
var domain = '<?php echo $url; ?>';
$.ajax({
type: 'POST',
url: 'lib/ajax.php',
data: {
action: 'get_all_seo_details', // function that collects data
domain: domain // the domain that is being send to the function in order to get data
},
success: function (data) {
// doesn't need to echo anything only to insert the data, which it done properly
}
});
// Below is the second part of the script that starts when ajax stops
$(document).ajaxStop(function () {
$.getJSON('lib/get-details.php', function(data) {
var twitter_followers = data.twitter_followers;
$('#twitter-followers').html(twitter_followers);
});
// data is being read correctly but it loops repeatedly in the console without finishing
});
});
PHP - get-details.php, reading the data from database after getting inserted with ajax
if (!isset($_SESSION)) {
sec_start();
}
global $db;
$domain = isset($_SESSION['domain']) ? $_SESSION['domain'] : '';
if ($domain == '') {
$domain = $db->query("SELECT * FROM seo_data");
} else {
$domain = $db->query("SELECT * FROM seo_data WHERE domain = '$domain'");
}
$domain_now = $domain->fetch_assoc();
$twitter_followers = (int) $domain_now['twitter_followers'];
echo json_encode(array('twitter_followers' => $twitter_followers));

I'm not sure but when the first AJAX request stops
$(document).ajaxStop(function (){....
starts a new one with
$.getJSON('lib/get-details.php', function(data) { ...
When this second one ends, maybe
$(document).ajaxStop(function (){....
is called again which starts again the 2nd request and so on

Related

Loading php file when execute and pass variable through Ajax

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

Passing a PHP variable to JavaScript For AJAX Request

So my workflow is that onClick of an list element, my JS initiates a PHP AJAX request to build a card object. The $content is a card (similar to KickStarter) of topic data. What I'm trying to do is a pass the 'topic_id' of each topic-instance so that I can then use it in the success function, to then initiate ANOTHER AJAX request (but to Discourse).
With attempt 2), I get a null when viewing its value in the web inspector.
The AJAX requests (the console.log() of the variable I want to get returns a blank line in the web console):
$.post( "/wp-content/mu-plugins/topic-search.php", { topicID: $topicFilter, filterBy: $sortByFilter },
function( data ) {
console.log(topic_id);
data = data.trim();
if ( data !== "" ) {
//get the participants data for avatars
$.getJSON('http://ask.example.com/t/' + topic_id + '.json', function() {
The end of topic-search.php, which echoes out the built up card. Script is supposed to return the topic_id variable for use in the success function.
}
//One attempt: echo $content; //
//Another attempt: echo json_encode(array('data' => $content, 'topic_id' => $row['topicid']));//
}
?>
<script>
var topic_id = "<?php echo $row['topicid'] ?>";
</script>
Try this:
In php
$inputJson = file_get_contents('php://input');
$input = json_decode($inputJson, true); //Convert JSON into array
In javascript
var $url = '/wp-content/mu-plugins/topic-search.php';
var $json = JSON.stringify({topicID: $topicFilter, filterBy: $sortByFilter});
$.ajax({
url: $url,
type: "POST",
data: $json,
dataType: "json",
success: function(data){//you will have the body of the response in data
//do something
},
error: function(data){
//do something else
}
});
EDIT:
This will request $url with the $json data. You will have it available on $input on the server side as an array. You can then on the server prepare a response with a json body that you will have available on the success function as the data variable.

Not recieving values sent via AJAX POST to PHP

I'm trying I'm trying to send a specific section of my URL string, to my php file, to then populate my page accordingly. Everything is working fine, except for the AJAX POST method. I've tried doing var_dump of the POST variable in my PHP, and my array is empty (so I know nothing is getting through).
The success DOES return as being passed, so I don't know where the data is going. I'm testing locally on XAMPP, and I've combed through SoF and no luck on any of the fixes. My code is below.
Screen shot of page:
jQuery AJAX Request:
$(document).ready(function() {
str = window.location.href;
pos = str.search("pages/"); //42
send = str.slice(42, -5);
console.log(send);
console.log(pos);
$.ajax({
type: "POST",
url: "retrieve.php",
data: {
tom: send
},
success: function() {
$.get("retrieve.php", function(data, status) {
$("#main").html(data);
}) //ends GET function
},
error: function() {
console.log(arguments)
}
}); //ends POST request
}); //ends DOC-READY function
PHP:
echo "<i>hello</i>";
echo var_dump($_POST);
$url = $_POST['tom'];
json_decode($url);
echo $url;
Try the below,
Also you don't need to json_decode unless you send a json request,And please make sure all the post values are passing.
Ajax:
$(document).ready(function() {
var str = window.location.href;
var pos = str.search("pages/"); //42
var send = str.slice(42, -5);
console.log(send);
console.log(pos);
$.ajax({
type: "POST",
url: "retrieve.php",
data: {
'tom': send//make sure this is not empty
},
success: function(data) {
console.log(data);
},
error: function(arguments) {
console.log(arguments)
}
}); //ends POST request
}); //ends DOC-READY function
PHP:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//echo "<i>hello</i>";
//echo var_dump($_POST);
$url = $_POST['tom'];
json_encode($url);
echo $url;
}

Is this piece of jquery ajax code correct?

I am making a simple web chat application using ajax,php,javascript and mysql.
What I am trying to do here is to avoid fetching the whole database after an interval of 1 sec(which is normally done in basic chat application ) but rather I want to fetch and display(by appending) also those chats which have been newly entered into the database by any user.
To implement this ,First when the user first opens the chat screen the whole database is loaded in the chat window(not shown in this code snippet),and then I am using the variable msgid to fetch the latest value of MSg_ID (which is the auto-increment primary key in my chat table) through an ajax request to the page 'Msg.php' which returns the required value of msg_id.
Now using this value of msgid and comparing it with the max value of Msg_ID every second in the database through the ajax request to the page 'Chat3.php'.
If the Max value of Msg_ID has changed the required rows are returned . After this I m updating the value of 'msgid' using the same earlier ajax request to the page 'Msg.php'
The pages Msg.php and Chat3.php are working perfectly ,as I have tested them thoroughly.
My question here is what is the problem in my code , why is not working?
Can we use an ajax request inside a ajax call back function or not?
What else can be a probable source of error?
Any input will be valuable :)
If you have any problem in understanding the code,leave a comment.
'#yyy' and '#zzz' are random div elements which i am using to test the data value of ajax callback function.
I can even post the rest of the code if it helps.
<script type"text/javascript">
$(document).ready(function() {
var dept = '<?php echo $deptId; ?>';
$.ajax({
url: 'scripts/php/Msg.php',
data: {dept:dept},
success: function(data) {
$('#yyy').html(data);//this displays the correct value
var msgid=data;
}
});
var interval = setInterval(function() {
$.ajax({
url: 'scripts/php/Chat3.php',
data: {dept:dept,msgid:msgid},
success: function(data) {
if(data!='bad'){
//$('#messages').prepend(data);
$('#zzz').html(data);//does not display any value although Chat3.php is returning the correct value.
//below ajax request to update the value of msgid
$.ajax({
url: 'scripts/php/Msg.php',
data: {dept:dept},
success: function(data) {
var msgid=data;
$('#zzz').html(data); //not displaying anything although above one is was displaying
}
});
}
}
});
}, 1000);
});
</script>
Here is my Msg.php
<?php
require '../../includes/database/connect.db.php';
function get_msg($dept){
$query= "SELECT Msg_ID,Sender, Message ,Time_stamp FROM chat WHERE Dept_ID='$dept' ORDER BY Msg_ID DESC" ;
$run=mysql_query($query);
$messages =array();
while($message=mysql_fetch_assoc($run)){
$messages[] =array('msgid'=>$message['Msg_ID'],
'sender'=>$message['Sender'],
'message'=>$message['Message'],
'time_stamp'=>$message['Time_stamp']);
}
return $messages;
}
$dept=$_GET['dept'];
$messages = get_msg($dept);
$x=count($messages);
if($x){
foreach($messages as $message) {
if($x==count($messages)){
echo $message['msgid'];
}
$x--;
}
}
?>
Here is my Chat3.php
<?php
require '../../includes/database/connect.db.php';
function get_msg($dept,$msgid){
$query1= "SELECT MAX(Msg_ID) as msg_id FROM chat" ;
$run1=mysql_query($query1);
$row = mysql_fetch_assoc($run1);
$result =$row['msg_id'];
$messages =array();
if($result>$msgid)
{
$query= "SELECT Sender, Message ,Time_stamp FROM chat WHERE Dept_ID='$dept' AND Msg_ID>'$msgid' ORDER BY Msg_ID DESC" ;
$run=mysql_query($query);
while($message=mysql_fetch_assoc($run)){
$messages[] =array('sender'=>$message['Sender'],
'message'=>$message['Message'],
'time_stamp'=>$message['Time_stamp']);
}
return $messages;
}
else
{
return $messages;
}
}
$dept=$_GET['dept'];
$msgid=$_GET['msgid'];
$messages = get_msg($dept,$msgid);
if(count($messages)){
foreach($messages as $message) {
echo '<strong>'.$message['sender'].' Sent</strong><br>';
echo $message['message'].' <i><small><div align="right">'.$message['time_stamp'].'</i></small></div>';
}
}
else {
echo 'bad';
}
?>
The problem is the msgid
In your first AJAX Request you are setting the variable var msgid=data; which is in local scope.
I think you are trying to access that variable in the second AJAX request while sending the datas
url: 'scripts/php/Chat3.php',
data: {dept:dept,msgid:msgid}, // Trying to access the local variable of previous ajax request
EDIT:
Try removing the var from var msgid=data; in your first AJAX request. Removing var will make the variable GLOBAL, Although its not good to pollute the global scope, but you can definitely try out this for the time being

From a running PHP Code, how to update status in DIV tag

I have a web Page, in which i an downloading data one after another in a loop. After each data download is finished i want to update the status to a DIV tag in the Web Page. How can i do this. Connecting to server and downloading data via php code and the div tag is within the .phtml page.
i have tried
echo "
<script type=\"text/javascript\">
$('#tstData').show();
</script>
";
But the echo statement update will happen at the end only. Refreshing of DIV tag need to happen at the end of each download.
Use jQuery load()
$('#testData').load('http://URL to script that is downloading and formatting data to display');
$("#save_card").submit(function(event) {
event.preventDefault();
var url = "card_save.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
dataType:"json",
data: $("#save_card").serialize(), // serializes the form's elements.
success: function(data)
{
console.log(data);
if(data.msg=="success")
{
$("#submit_msg").html("Thank You !!!");
console.log("Record has been Inserted Successfully!!!");
}
else
{
$("#submit_msg").html(data.er);
console.log("There Is Some Error");
}
$("#submit_msg").show();
setTimeout(function() { $("#submit_msg").hide(); }, 5000);
$("#save_card").get(0).reset();
}
});
return false; // avoid to execute the actual submit of the form.class_master
});
Use This Ajax function to call PHP function to get data. Here
#save_card = Id of the form that you want to submit.
url = action for the form or the location to the php file from where your data is coming.
data: $("#save_card").serialize() = it is sending all the data of the form in serialize form. Data can be created manually to do this repalce this line with data: {'name':name,'year':year}
function(data) = here data is returned from the php code in json formate.
data.msg = It is a way to access different field from data.
$user_email = $_REQUEST['user_email'];
$cat_id = $_REQUEST['category'];
$title = $_REQUEST['title'];
$country = $_REQUEST['country'];
$date = date("Y-m-d H:i:s");
$sql = "INSERT INTO project(title, user_email, cat_id, country, start_date) VALUES ('$title','$user_email','$cat_id','$country', '$date')";
if (mysql_query($sql)) {
$project_id = mysql_insert_id();
echo json_encode(array('project_id' => $project_id, 'msg' => 'Successfully Added', 'status' => 'true'));
} else {
echo json_encode(array('msg' => 'Not Added', 'status' => 'false'));
}
PHP code to send data in json format

Categories