Longpolling : Sending extra variable - php

I am doing a simple longpolling using jquery and php.. It's going on great.. but when I am sending and extra variable.. then the longpolling is not showing the current value that it's supposed to show... My code is below..
The one which is working :
function getContent(time)
{
var queryString = {'time': time};
$.ajax(
{
type: 'GET',
url: 'test.php',
data: queryString,
success: function(data){
var obj = jQuery.parseJSON(data);
$('#response').html(obj.data_from_file);
getContent(obj.time);
},
error : function(){
getContent(time);
}
}
);
}
$(document).ready(function(){
getContent();
});
The one which is working on page refresh.. but longpolling is not happening...
function getContent(time)
{
var name = '<?php echo $name; ?>';
var queryString = {'time': time, 'name':name};
$.ajax(
{
type: 'GET',
url: 'test.php',
data: queryString,
success: function(data){
var obj = jQuery.parseJSON(data);
$('#response').html(obj.data_from_file);
getContent(obj.time);
},
error : function(){
getContent(time);
}
}
);
}
$(document).ready(function(){
getContent();
});
PHP side...
while (true) {
$last_ajax_call = isset($_GET['time']) ? (int)$_GET['time'] : null;
$name = $_GET['name'];
//rest of the code...............
}
else{
sleep(1);
continue;
}

Related

Ajax send javascript variable to php

I am trying to send a JS variable to a PHP file but it does not seem to be working. In the console its showing an error as an show.php file. I am not able to understand What I am doing wrong.
function details(id) {
var id = id;
// alert(id);
$.ajax({
type: 'POST',
url: 'show.php',
data: id,
success: function(data) {
alert("hi");
}
});
}
<button onclick="details(<?php echo $id ; ?>)" class="btn btn-rounded btn-primary">Details</button>
show.php:
<?php
if (isset($_POST['id']))
{
$uid = $_POST['id'];
echo json_encode($uid);
}
?>
Write data in json object
see code below
function details(id)
{
var id = id;
// alert(id);
$.ajax({
type: 'POST',
url: 'show.php',
data: {id:id},
success: function(data)
{
alert("hi");
}
});
}
Check your network tab and check the sending parameters list . You have to mention datatype json
Try this
function details(id)
{
var id = id;
// alert(id);
$.ajax({
type: 'POST',
url: 'show.php',
dataType: 'json',
data: {'id':id},
success: function(data)
{
alert("hi");
}
});
}
In your show.php
<?php
if (isset($_POST['id']))
{
$uid = $_POST['id'];
echo json_encode($uid);
}
?>

pass arrays and variables from jquery to php at the same time

I want to pass arrays and other variables from jquery code to php using post request but I don't know how to pass arrays and variables at the same time.
I tried this code:
var new_location_name = "";
var new_location_id = "";
var old_location_name = [];
var selected_name = [];
var selected_id = [];
var user = '<?php echo $current_user ;?>';
$(document).ready(
$("#transfer").click(function(){
$.ajax({
type: "POST",
url: "update.php",
data: "username="+user+"&new_location_name="+new_location_name+"&new_location_id"+new_location_id+"&"+{ old_location_name : old_location_name }+"&"+{ selected_name : selected_name }+"&"+{ selected_id : selected_id },
});
return false;
});
});
Create an object, serialize it and send it:
var obj = {
key1: 'value1',
key2: ['one','two','three'],
key3: {
key3_0: 'value3_0'
}
}
var jsonData = JSON.stringify(obj);
$.ajax({
method: "POST",
url: "update.php",
data: jsonData
});
JQuery Data:
data:
{
username: user,
new_location_name: new_location_name,
new_location_id: new_location_id,
old_location_name: old_location_name,
selected_name : selected_name,
selected_id : selected_id
}
In your PHP Script
<? $oldLocationName = $_REQUEST['old_location_name']; ?>
and so on.
You can pass multiple parameters as arrays or strings the same. The left hand side of the data is the value that the API is expecting as the parameter name.
var new_location_name = "";
var new_location_id = "";
var old_location_name = [];
var selected_name = [];
var selected_id = [];
var user = '<?php echo $current_user ;?>';
$(document).ready(
$("#transfer").click(function(){
$.ajax({
type: "POST",
url: "update.php",
data: {username: user,
new_location_name: new_location_name,
old_location_name: old_location_name
}
});
return false;
});
});
You can read more in this question: Pass Multiple Parameters to jQuery ajax call
Try this snippet
var array = [];
$.ajax({ url: 'update.php',
data: {'array' : array},
type: 'post',
dataType:'json',
success: function(output) {
alert(output);
},
error: function(request, status, error) {
alert("Error");
}
});
First time Check file, this script must be in .php file, not .js file;

PHP variable not echoing on page via ajax jquery

I am having a problem with my code as my php variable is not being echoed on page when using ajax jquery. Here is my code...
<script>
function refresh_div() {
$('.loader').show();
var username = "<?php echo $user; ?>";
jQuery.ajax({
type: "POST",
url: "load.php",
data:{user : username},
success:function() {
jQuery("#load_msgs").append(response+'<br>');
},
complete: function(){
$('.loader').hide();
}
});
}
t = setInterval(refresh_div,1000);
</script>
i am trying to send "username" to page url "load.php"... i called it this way but nothing is being echoed...
if(isset($_POST['user'])) {
echo $_POST['user'];
}
pls help out thanks... :)
edited...
when i tried using this code i.e adding passing response as parameter in success function like this ...
<script>
function refresh_div() {
$('.loader').show();
var username = "<?php echo $user; ?>";
jQuery.ajax({
type: "POST",
url: "load.php",
data:{user : username},
success:function() {
jQuery("#load_msgs").append(response+'<br>');
},
complete: function(){
$('.loader').hide();
}
});
}
t = setInterval(refresh_div,1000);
</script>
.... the data (username) gets displayed every second.. like a blink toggling on and off the page... how do i make the data display static in order to use the variable on the ajax page. Thanks :)
Where the response variable you get? Should be :
success : function( response ) {
jQuery("#load_msgs").append(response+'<br>');
},
please take a datatype as json in ajax call
and in loads.php function add two line as below..
if(isset($_POST['user'])) {
$data['user'] = $_POST['user'];
}
echo json_encode($data);
also change in success function.
success:function(response) {
jQuery("#load_msgs").append(response.user);
}
A bit more simplified would be:
$.post(URL, { data: somefield }, function(result) {
result = JSON.parse(result);
If(result && result.status === 'true'){
}
)};
Depends a bit on the return at server side.
You missed response in success function.
Try this:
<script>
function refresh_div() {
$('.loader').show();
var username = "<?php echo $user; ?>";
jQuery.ajax({
type: "POST",
url: "load.php",
data:{user : username},
success:function(response) {
$("#load_msgs").append(response+'<br>');
},
complete: function(){
$('.loader').hide();
}
});
}
t = setInterval(refresh_div,1000);
</script>

serializeArray not sending the data

This is a sample of the php and javascript.
<form id="image-comment" method="post" action="includes/insert_image_comment.php">
<textarea id="comment-area" name="comment-area"></textarea>
</form>
// javascript
$("#image-comment").submit(function(event) {
event.preventDefault();
var action_url = event.currentTarget.action;
var id = 4;
var params = $("#image-comment").serializeArray();
params.push({imageid: id});
$.ajax({
url: action_url,
type: 'post',
data: params,
success: function(data) {
alert(data);
}
});
});
// insert_image_comment.php
echo $get_image = $_POST['imageid'];
$comment = $_POST['comment-area'];
When echoing $_POST['imageid'] i get an error 'Undefined index: imageid'.
When echoing $_POST['comment-area'] it's ok.
Why one works and the other not?
Thanks
Try to use the format that serializeArray uses: Example:
$("#image-comment").submit(function(event) {
event.preventDefault();
var id = 4;
var params = $("#image-comment").serializeArray();
params.push({name: 'imageid', value: id}); // this one
$.ajax({
url: document.URL,
type: 'POST',
data: params,
success: function(data) {
alert(data);
}
});
});

Can't pass a value from jquery to php

What is wrong:
$('#click01').click(function(){
$a = 14;
$.ajax({
url : 'msg.php',
type : 'post',
data : {a:$a}
});
window.location = 'msg.php';
});
msg.php contains:
var_dump($_POST['a']); // NULL, but expected: 14
$('#click01').click(function(){
var a = 14;//not $a since this is javascript
$.ajax({
url : 'msg.php',
type : 'post',
data : {'a':a}
});
window.location = 'msg.php';
});
$('#click01').click(function(){
var a = 14
$.ajax({
type: "POST",
url: "msg.php",
data: {a:a},
beforeSend: function () {
// do action
},
success: function(html){
window.location = 'msg.php';
}
});
});
Rather than set the window.location you want to set a 'success' function on the ajax call so that when it finishes it takes the response and puts it into your page.
E.g. something like:
$('#click01').click(function(){
$a = 14;
$.ajax({
url : 'msg.php',
type : 'post',
data : {a:$a},
success: function(data, textStatus, jqXHR) {
$('#placeToPutTheResponse').append( data );
}
});
});
The above assumes that you have added an HTML node with the id="placeToPutTheResponse"
It is worth reading this other post on SO for a decent overview: jQuery Ajax POST example with PHP
It uses done rather than success, and slightly different syntax, but it's a great overview.
$(document).on('click','#click01',function () {
var a = 14;
$.ajax({
url: 'msg.php',
type: 'post',
data: {a: a},
success: function(e){
console.log(e);
},
error: function(e) {
console.log(e);
}
});
});
Try this
$('#click01').click(function(){
var a = 14;
$.ajax({
url : 'msg.php',
type : 'POST',
data : {a:a},
complete: function (data) {
console.log( data ); // this will tell you the output of var_dump.
window.location.href = 'msg.php';
}
});
// window.location = 'msg.php';
});
also this line window.location.href = 'msg.php'; in function complete will actually redirect you to the msg.php, so if you dont want any redirects remove those lines..

Categories