i'm trying to do a simple php chat application that receives data from the client via ajax and writes that data to a text file for storage. But i keep getting anundefined index error on the lines where i try to get the 'name' and the 'message' after parsing the json.
this is the chat.php file:
<?php
if (isset($_POST['data']))
{
$data = $_POST['data'];
$chat = json_decode($data);
$name = $chat->name;
$msg = $chat->msg;
$file = "chat.txt";
$fh = fopen($file, 'w') or die("Sorry, could not open the file.");
if (fwrite($fh, $name + ":" + $msg))
{
$response = json_encode(array('exists' => true));
} else {
$response = json_encode(array('exists' => false));
}
fclose($fh);
echo "<script type='text/javascript'>alert ('" + $name + $msg + "')</script>"
}
?>
this is the javascript:
<script type="text/javascript">
$(document).ready(function() {
$("#btnPost").click(function() {
var msg = $("#chat-input").val();
if (msg.length == 0)
{
alert ("Enter a message first!");
return;
}
var name = $("#name-input").val();
var chat = $(".chat-box").html();
$(".chat-box").html(chat + "<br /><div class='bubble'>" + msg + "</div>");
var data = {
Name : name,
Message : msg
};
$.ajax({
type: "POST",
url: "chat.php",
data: {
data: JSON.stringify(data)
},
dataType: "json",
success: function(response) {
// display chat data stored in text file
}
});
});
});
</script>
Probably your $chat variable
$chat = json_decode($data);
Does not contains these fields but Name and Message as you delcared here:
var data = {
Name : name,
Message : msg
}
name and msg are valuse and Field names are Name and Message.
Please try to print_r($chat) to see what it contains.
Related
I want to send two values to my PHP script that is being called from an AJAX request. Somehow my data is not being passed to the PHP script.
Maybe I am doing something wrong somewhere. Can I have some insight?
$(function() {
$(".delbutton").click(function() {
var viewed_comments = $("#viewed_comments").val();
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
var comments = 'comm=' + viewed_comments;
var tr = $(this).closest('tr');
if (confirm("Are you sure to mark this as viewed?")) {
$.ajax({
type : "POST",
url : "update_entry.php",
dataType: "json",
data: {info:info, comments:comments },
success : function(response) {
if(response=="updation success"){
console.log('inside');
}
}
});
}
return false;
});
});
And my PHP where the AJAX request is going,
$id = $_POST['id'];
$viewed_comments = $_POST['comm'];
$level_code = $_SESSION['level_code'];
$action = 'view';
$viewed_date = date("Y-m-d");
$viewed_by = $_SESSION['session_admin_id'] ;
if($action == 'view')
{
$viewed_date = date('Y-m-d h:i:s');
$nots = $db->idToField("tbl_table","notes",$id);
if ($nots == "")
{
$date_string = "last viewed on|".$viewed_date."|" ;
}
else {
$date_string = $nots."last viewed on|".$viewed_date."|" ;
}
$fnc->update_is_viewed_for("tbl_table",$id, "$viewed_date", $viewed_by);
$notes_data = array("notes"=>$date_string,"viewed_comments"=>$viewed_comments);
$db->query_update("tbl_table", $notes_data, "id=$id");
}
if($db->query_update("tbl_table", $notes_data, "id=$id")){
http_response_code();
echo json_encode('updation success');
}else{
http_response_code(204);
}
Isn't it a name thing? You send two POST variables:
data: {
info: info,
comments: comments
},
but you retrieve them with different names:
$id = $_POST['id'];
$viewed_comments = $_POST['comm'];
What do you get if you var_dump($_POST);?
Use seriliaze form values it will solve your data missing problem, change #frm to your form id
$(document).ready(function(){
$('#frm').submit(function(event){
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
url:"update_entry.php",
method:"POST",
data:formValues,
dataType:"JSON",
success:function(data){
if (data == 'updation success') {
console.log('success');
}
}
});
});
});
I am having trouble getting the success call to fire in my ajax request. I know the communication is working fine, but the last call in my PHP script, which is a return json_encode($array); will fire as if it is a part of the onprogress object. I would like to "break" the onprogress call and run the success function on the last data sent via return json_encode when the PHP script has terminated...
Here is my AJAX call:
$( document ).ready(function(e) {
var jsonResponse = '', lastResponseLen = false;
$("#btn_search").click(function(e){
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
$.ajax({
type: "POST",
url: 'search.php',
data: $('#search_fields').serialize(),
dataType: "json",
xhrFields: {
onprogress: function(e) {
var thisResponse, response = e.currentTarget.response;
if(lastResponseLen === false) {
thisResponse = response;
lastResponseLen = response.length;
} else {
thisResponse = response.substring(lastResponseLen);
lastResponseLen = response.length;
}
jsonResponse = JSON.parse(thisResponse);
document.getElementById('progress').innerHTML = 'Progress: '+jsonResponse.msg;
}
},
success: function(data) {
console.log('done!');
document.getElementById('progress').innerHTML = 'Complete!';
document.getElementById('results').innerHTML = data;
}
});
e.preventDefault();
});
});
And here is the basic PHP server script:
<?php
function progress_msg($progress, $message){
echo json_encode(array('progress' => $progress, 'msg' => $message));
flush();
ob_flush();
}
$array = array('msg' => 'hello world');
$count = 0;
while($count < 100){
progress_message($count, "working....");
$count += 10;
sleep(2);
}
return json_encode($array);
?>
I made your code work, there were 2 errors. First, in your while loop, your function name is incorrect, try this:
progress_msg($count, "working... ." . $count . "%");
Secondly, the very last line outputs nothing, so technically you don't get a "successful" json return. Change the last line of your server script from:
return json_encode($array);
to:
echo json_encode($array);
UPDATE: Full working code with hacky solution:
Ajax:
$( document ).ready(function(e) {
var jsonResponse = '', lastResponseLen = false;
$("#btn_search").click(function(e){
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
$.ajax({
type: "POST",
url: 'search.php',
data: $('#search_fields').serialize(),
xhrFields: {
onprogress: function(e) {
var thisResponse, response = e.currentTarget.response;
if(lastResponseLen === false) {
thisResponse = response;
lastResponseLen = response.length;
} else {
thisResponse = response.substring(lastResponseLen);
lastResponseLen = response.length;
}
jsonResponse = JSON.parse(thisResponse);
document.getElementById('progress').innerHTML = 'Progress: '+jsonResponse.msg;
}
},
success: function(data) {
console.log('done!');
dataObjects = data.split("{");
finalResult = "{" + dataObjects[dataObjects.length - 1];
jsonResponse = JSON.parse(finalResult);
document.getElementById('progress').innerHTML = 'Complete!';
document.getElementById('results').innerHTML = jsonResponse.msg;
}
});
e.preventDefault();
});
Search.php:
<?php
function progress_msg($progress, $message){
echo json_encode(array('progress' => $progress, 'msg' => $message));
flush();
ob_flush();
}
$array = array('msg' => 'hello world');
$count = 0;
while($count <= 100){
progress_msg($count, "working... " . $count . "%");
$count += 10;
sleep(1);
}
ob_flush();
flush();
ob_end_clean();
echo json_encode($array);
?>
The problem with the "success" method of the ajax call was that it couldn't interpret the returning data as JSON, since the full return was:
{"progress":0,"msg":"working... 0%"}{"progress":10,"msg":"working... 10%"}{"progress":20,"msg":"working... 20%"}{"progress":30,"msg":"working... 30%"}{"progress":40,"msg":"working... 40%"}{"progress":50,"msg":"working... 50%"}{"progress":60,"msg":"working... 60%"}{"progress":70,"msg":"working... 70%"}{"progress":80,"msg":"working... 80%"}{"progress":90,"msg":"working... 90%"}{"progress":100,"msg":"working... 100%"}{"msg":"hello world"}
Which is not a valid JSON object, but multipje JSON objects one after another.
I tried removing all previous output with ob_end_clean(); , but for some reason I can't figure out, it didn't work on my setup. So instead, the hacky solution I came up with was to not treat the return as JSON (by removing the dataType parameter from the AJAX call), and simply split out the final Json element with string operations...
There has got to be a simpler solution to this, but without the use of a third party jQuery library for XHR and Ajax, I couldn't find any.
I am using jquery, php and json to store and update the clicks on a single download button. It's working flawlessly but now I need to be able to store and update the clicks from multiple download buttons and display them individually.
Can you guys give me a hand with this?
What I have so far is:
jQuery:
$('.download').click(function(event) {
event.preventDefault();
ga('send', 'event', 'Button', 'Clicks', 'Downloads');
var redirectUrl = $(this).attr('href');
$.ajax({
url: "downloads.php",
success: function(response) {
if (response = 'success') {
// The counter file has been updated in the background, but we should update the results on screen to tell the user
var count = $('.small').html();
$('.small').html(parseFloat(count) + 1);
// Then redirect so that file can download
$("#cover").fadeIn(600);
$("body").addClass("hidescroll");
window.location.href = "download/imagins_._ro_free_files_format_icons.rar";
}
}
});
return true;
});
$.ajax({
url: "get-downloads.php",
success: function(data) {
var data = JSON.stringify(data, null, 4);
var data = $.parseJSON(data);
$('.small').html(data.count);
}
});
downloads.php
<?php
$file = "downloads.json";
$json = json_decode(file_get_contents($file), true);
$json['count'] = $json['count'] + 1;
file_put_contents($file, json_encode($json));
echo 'success';
?>
get-downloads.php
<?php
$file = "downloads.json";
$json = json_decode(file_get_contents($file), true);
header('Content-Type: application/json');
echo json_encode($json);
?>
and the downloads.json
{"count":174}
try like this
for example for 3 button
<input type='button' name='btn1' class='download'/>
<input type='button' name='btn2' class='download'/>
<input type='button' name='btn3' class='download'/>
send name of button to server and show count in different .smallbtn1،.smallbtn2،.smallbtn3
$('.download').click(function(event) {
event.preventDefault();
ga('send', 'event', 'Button', 'Clicks', 'Downloads');
var redirectUrl = $(this).attr('href');
//get name of button
var name= $(this).prop('name');
//==================
$.ajax({
url: "downloads.php",
data:{buttonName:name},
method: "POST",
success: function(response) {
if (response = 'success') {
//get count download
$.ajax({
url: "downloadsCount.php",
data:{buttonName:name},
method: "POST",
success: function(response){
$('.small'+name).html(response);
$("#cover").fadeIn(600);
$("body").addClass("hidescroll");
window.location.href = "download/imagins_._ro_free_files_format_icons.rar";
}
});
//===================
}
}
});
return true;
});
in downloads.php open json file
<?php
$buttonName=$_POST["buttonName"];
$file = "downloads.json";
$json = json_decode(file_get_contents($file), true);
$json['count'.$buttonName] = $json['count'.$buttonName] + 1;
file_put_contents($file, json_encode($json));
echo 'success';
?>
downloadsCount.php
<?php
$buttonName=$_POST["buttonName"];
$file = "downloads.json";
$json = json_decode(file_get_contents($file), true);
echo $json['count'.$buttonName] ;
?>
downloads.json
{"countbtn1":0,"countbtn2":0,"countbtn3":0}
this is my test and working for me
I'm trying to retrieve a json object through a ajax request from a php file. My ajax request looks like the following:
function validateForm() {
var name = $('#usernameLogIn').val();
var password = $('#passwordLogIn').val();
$.ajax({
type: 'GET',
url: '../webroot/login/validateForm/',
data: {name: name, password: password},
dataType: 'json',
success: function(result) {
var data = JSON.stringify(result);
var b = $.parseJSON(data);
alert(b);
},
error: function(a,b,c) { console.log(a,b,c); }
});
}
and my php file looks like this:
$form = $this->form;
$status = false;
$name = preg_replace("/[^A-Za-z0-9]/", " ", $_GET['name']);
$formPassword = preg_replace("/[^A-Za-z0-9]/", " ", $_GET['password']);
$now = date(DATE_RFC2822);
$user = $this->user->findName($name);
if(isset($user->name))
{
$password = $user->password;
$status = password_verify($formPassword, $password);
}
if ($status === true)
{
$this->session->set('loggedIn', $this->user->name);
}
else if ($status === false) {
$this->session->clearSession('loggedIn');
}
$sessionLog = $this->session->get('loggedIn');
$advert = array(
'session' => $sessionLog,
'name' => $name,
'password' => $formPassword,
);
echo json_encode($advert);
exit;
Finally when it passes the values back to my Ajax request it goes straight into the error function and prints the following into the console:
Object "parsererror" SyntaxError
message: Unexpected Token <"
Is it any way to tell where this goes wrong and why?
thankfull for answers, cheers.
I think you have verbose set to true in you config file.
how to return URL built in php as json object to ajax to open it in the new tab?
so far all my attempts to do so were unsuccessful. Please help
here is my JS file
$(document).ready ( function() {
$('.promoCode').click(function() {
// Store values in variables
var form = $(this).closest('form');
var name = form.find('input[name=name]');
var id = form.find('input[name=id]');
var submitted = form.find('input[name=submitted]');
var visitor = form.find('input[name=visitor]');
// Organize data
var data = 'name=' + name.val() + '&id=' + id.val() + '&submitted=' + submitted.val() + '&visitor=' + visitor.val();
var request = $.ajax({
type: "POST",
url: "/includes/_db_get_promo_code.php",
data: data,
cache: false,
success: function (html) {
myWindow = window.open(encodeURIComponent(true),
"_blank");
myWindow.focus();
if (html == "true") {
} else {
form.find('.error').fadeIn(500).delay(4000).fadeOut(500);
}
},
error: function(jqXHR, textStatus, error) {
alert("Form Error: " + error);
}
});
return false;
});
});
and here is my PHP file
<?php
require_once($_SERVER['DOCUMENT_ROOT']."/includes/sitewide-variables.php");
// Check if form was submitted
if ($_POST['submitted'] && $_POST['visitor'] == '') {
// Check if all required fields are filled in
if (empty($_POST['name']) && empty($_POST['id'])) {
echo "Error: You must fill in all required fields.";
// If not, exit!
exit();
}
// If valid, store values in variables
$id = stripslashes($_POST['id']);
$name = stripslashes($_POST['name']);
if($name){
$query = 'SELECT * FROM files_paid WHERE parentpageID = :promoproductID';
$res = $db->prepare($query);
$res->execute(array(':promoproductID' => $id));
foreach ($res as $info);
if($info['promoCode'] == $_POST['name']){
$redirect_link = 'http://'.$info['promobuylinkID'].'.myid.pay.clickbank.net';
$todayis = date("l, F j, Y, g:i a") ;
$to = "My Email Address";
$subject = "Promotional Purchase";
$message = "$todayis [EST] \n
Promo Code: $name \n
";
// Send email
$sent = mail($to, $subject, $message);
if($sent) {
echo json_encode($redirect_link);
} else {
echo "Error: Mail could not be send.";
exit();
}
} else {
echo "Error: There was a problem with submitting the form";
exit();
}
}
}
?>
I am only getting true in the new window.
Thanks in advance
I have have found the problem.
First, I was missing dataType: "json", in ajax.
and after that I only had to return html to get to the point where I needed to get.
So the JS file now looks like this
$(document).ready ( function() {
$('.promoCode').click(function() {
// Store values in variables
var form = $(this).closest('form');
var name = form.find('input[name=name]');
var id = form.find('input[name=id]');
var submitted = form.find('input[name=submitted]');
var visitor = form.find('input[name=visitor]');
// Organize data
var data = 'name=' + name.val() + '&id=' + id.val() + '&submitted=' + submitted.val() + '&visitor=' + visitor.val();
var request = $.ajax({
type: "POST",
url: "/includes/_db_get_promo_code.php",
data: data,
dataType: "json",
cache: false,
success: function (html) {
if (html) {
window.open(decodeURIComponent(html),"_blank").focus();
} else {
form.find('.error').fadeIn(500).delay(4000).fadeOut(500);
}
},
error: function () {
alert("Your Coupon Code is not valid");
}
});
return false;
});
});
All works just fine.