Getting Undefined when reading back a POST from AJAX - javascript

If this is a re-post of an already existing. I looked a bunch of different issue already posted about this but didn't feel any matched my issue. If there is one please link it.
I'm trying to learn AJAX and have a form that takes two inputs a serverName, and a isLive. As well as a button to add a server to the list. I already made a json file that has two servers in it and when I GET info from it to update the list it lists the server's serverName and isLive fine. When I go to POST information all I get back when the list is updated is undefined.
Using console logs I know that the information is being passed from the form to Object to be sent by AJAX and that it seems to trigger the success function, but when I look there is nothing added to the Json and it says the fields are undefined.
index.php
<!DOCTYPE html>
<html>
<head>
<title>Ajax</title>
</head>
<body>
<h1>Server List</h1>
<ul id="servers">
</ul>
<h4>Add a Server</h4>
<p>Server Name: <input type="text" id="serverName"></p>
<p>Offline or Online: <input type="text" id="isLive"></p>
<button id="add-server">Add!</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="main.js"></script>
</body>
</html>
main.js
$(function() {
var $servers = $('#servers');
var $serverName = $('#serverName');
var $isLive = $('#isLive');
$.ajax({
type : 'GET',
url: 'servers.json',
success: function(servers) {
$.each(servers, function(i, server) {
$servers.append('<li>Server: '+ server.serverName +', Status: '+server.isLive+'<li>');
});
},
error: function() {
alert('Error loading server status!');
}
});
$('#add-server').on('click', function() {
var server = {
serverName: $serverName.val(),
isLive: $isLive.val(),
};
console.log(server);
$.ajax({
type: 'POST',
url: 'servers.json',
data: server,
success: function(newServer) {
$servers.append('<li>Server: '+ newServer.serverName +', Status: '+newServer.isLive+'<li>');
},
error: function(){
alert('error saving server');
}
});
});
});
servers.json
[{"serverName":"vanilla","isLive":"offline"}, {"serverName":"SkyFactory","isLive":"Online"}]

You can't modify a file in the server with JavaScript. Check this may help:
Use JQuery to Modify external JS File

Related

Can't get AJAX and PHP working

So here is the scenario:
I have HTML, JS, and PHP Files. Within the PHP File is an associative array of default values to fill out various form elements on the HTML file. I am attempting to use AJAX to take the files from the PHP Files, and put them in the corresponding form elements. However nothing is working.....
Below is the code for the corresponding files. Any help figuring this out is greatly appreciated :)
HTML
<html>
<body>
<h1>Form Validation</h1>
<form id="PersonForm">
Name: <input type="text" id="name" name="name"> <br>
Postal Code: <input type="text" id="postal" name="postal"> <br>
Phone Number: <input type="text" id="phone" name="phone"> <br>
Address: <input type="text" id="address" name="address"> <br>
<input type="submit">
</form>
Refresh
<a id="InsertDefault" href="">Insert Default Data</a>
<br>
<ul id="errors"></ul>
<p id="success"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
PHP
<?php
// Return JSON default data if requested
if ($_REQUEST['act'] == 'default')
{
$defaultData = array('name' => "Jane",
'postal' => "L5B4G6",
'phone' => "9055751212",
'address' => "135 Fennel Street");
echo json_encode($defaultData);
}
?>
JAVASCRIPT
$(document).ready(function()
{
$("#InsertDefault").click(function()
{
// make an AJAX call here, and place results into the form
$.post('backend.phps',
{ act: 'default' },
function(data) {
for (var key in data) {
document.getElementById(key).value = data[key] }
},
'json');
// prevents link click default behaviour
return false;
});
});
As a side note, I always have trouble with web development stuff because I have no idea how to properly debug what I am doing. If anyone has any tips on what are some useful tricks/tools to use for debugging web code, I'd be more than happy to get some input on that too.
Thanks for your time.
For ajax code request use:
$("#InsertDefault").click(function(){
$.ajax({
type: "POST",
url: "backend.phps",
data: "act=default&name=test&phone=test", //Something like this
success: funtion(msg){
console.log(msg);
},
beforeSend:function(dd){
console.log(dd)
}
});
});
and in your backend.php file
if ($_REQUEST['act'] == 'default'){
//echo $_REQUEST['name'];
}
And for simple debugging use browsers' console, right click on the page and click Inspect Element. (Simple)
You can also install Firebug extension on Mozilla Firefox and then right click on the page and click on inspect Element with firebug. after this click on the Console tab there.
These are the basic and simple debugging for simple ajax request.
Per the newest Ajax documentation your ajax should include the Success and Failure callbacks where you can handle the response being sent from your PHP.
This should work with you existing PHP file.
Ajax
$(document).ready(function () {
//look for some kind of click below
$(document).on('click', '#InsertDefault', function (event) {
$.ajax({
url: "/backend.phps",
type: 'POST',
cache: false,
data: {act: 'default'},
dataType: 'json',
success: function (output, text, error)
{
for (var key in output.defaultData) {
document.getElementById(key).value = data[key]
}
},
error: function (jqXHR, textStatus, errorThrown)
{
//Error handling for potential issues.
alert(textStatus + errorThrown + jqXHR);
}
})
})
preventDefault(event);
});

JQuery AJAX call to php function

I am trying to replace page reloading PHP scripts in a web page with AJAX calls.
I am using JQuery to run the AJAX scripts but it doesn't seem to be doing anything so I attempted to write an incredibly basic script just to test it.
My directory is as follows
public_html/index.php
/scripts/phpfunctions.php
/jqueryfunctions.js
index.php contains
<!DOCTYPE html>
<html>
<head>
<!-- jquery functions -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="scripts/jqueryfunctions.js"></script>
<!-- php functions -->
<?php include 'scripts/phpfunctions.php' ?>
</head>
<body>
<button type="button" id="testButt">TEST</button>
</body>
</html>
Then the phpfunctions.php page which I am trying to call contains just an echo if an argument is set
<?php
if(isset($_GET["action"])) {
echo "test has been run";
}
?>
The jqueryfunctions.js script I am trying to run is
$(document).read(function () {
$('#testButt').on('click', function () {
console.log("jquery call worked"); // this bit does run when button is clicked
$.ajax({ // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php?action=run_test',
type: 'GET',
success: function (data) {
$('#ajaxdata').html(data);
},
error: function (log) {
console.log(log.message);
}
});
});
});
I see that the jqueryfunctions.js function is being called by the first console.log but it doesn't seem to be calling my phpfunctions.php function.
I was expecting to see the php echo "test has been run" but this doesn't happen.
Did I miss something?
You should use isset() method:
<?php
if(isset($_GET["action"])) {
if($_GET["action"] == "run_test") {
echo "test has been run";
}
}
?>
and if you are using ajax then why do you need to include it on index page:
<?php include 'scripts/phpfunctions.php' ?>
and i can't find this element $('#ajaxdata') on your index page.
Also you can check the network tab of your inspector tool to see the xhr request to the phpfunctions.php and see if this gets successfull or there is any error.
I think problem is here:
$(document).read(function() {
$('#testButt').on('click', function() {
console.log("jquery call worked"); // this bit does run when button is clicked
$.ajax({ // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php',
type: 'GET',
data: {action:'run_test'}, // <------ Here
success: function(data) {
$('#ajaxdata').html(data);
},
error: function(log) {
console.log(log.message);
}
});
});
});
jQuery says:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting.
So you should set data: {key:'value'}
Most things look fine, but your data attribute is designed for "POST" requests, try to add the data to the url as follows:
$( document ).read( function ()
{
$( '#testButt' ).on( 'click', function ()
{
console.log( "jquery call worked" ); // this bit does run when button is clicked
$.ajax( { // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php?action=run_test', // Add the GET request to the end of the URL
type: 'GET',
//data: 'action=run_test', Unrequired noise :P (this is for post requests...)
success: function ( data )
{
$( '#ajaxdata' ).html( data );
},
error: function ( log )
{
console.log( log.message );
}
} );
} );
} );
And also (as mentioned in my comments), you need to finish your bodys closing tag:
</body> <!-- Add the closing > in :P -->
</html>
I hope this helps :)
Where do you load ajaxfunctions.js? It look like in your code you never load the resource
And change
<button id="xxx">
In
<button type="button" id="xxx">
So the page isn't reloaded

how to print data sent by ajax post method in javascript

I need to post data and display it also. I am using ajax post method. I am able to get the event Id where data is saved, but not able to display the data. I searched a lot and got some answer also. I tried it in my code, but didn't got the result. My code is:
<!DOCTYPE html>
<html>
<head>
<title>POST API</title>
<script type="text/javascript" src="http://ajax.googleapis.com /ajax/libs /jquery/1.2.6/jquery.js"></script>
</head>
<body>
<button id="btn1">Check HTTP POST</button>
<p>Display sample output from POST API:</p>
<p id="one" />wEventId :
<p id="two" />
<script>
$(document).ready(function() {
$("#btn1").click(function() {
$.ajax({
url: 'url',
dataType: 'json',
type: 'POST',
crossDomain: true,
contentType: 'application/json',
data: {},
success: function(data) {
console.log(data);
document.getElementById("two").innerHTML = data.result.wEventId;
},
failure: function(errMsg) {
console.log(errMsg);
}
var myData = data;
myData = new Array;
});
});
});
</script>
</body>
</html>
Anyone please help me how to modify the code to print the data saved. I have not given the url as it is an internal server and supposed not to disclose it. Thanks in advance.
First I need to know, what is the structure of your json data.
Assuming that it is in a format like given below:
{"field_A":"value_a","field_b":"value_b"}
your code where you are trying to print as innerHTML should be like this:
success: function(data)
{
console.log(data);
document.getElementById("two").innerHTML = data.field_A;
},
Try to adjust accordingly.
I am still surprised from where are you getting the result of data.result.wEventId

AJAX post data to PHP file and redirect to the same file to echo post data

I have a php file with a bunch of <a></a> elements containing user names. Upon clicking one of these links, the link's data attributes are stored and posted to the second php file via AJAX. However, once I redirect to that file, the value I posted is not being displayed, instead I get the error: Undefined index userid.
Here's my code:
Index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Post Test</title>
</head>
<body>
User 1
User 2
User 3
User 4
User 5
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$('.user-staff').on('click',function(){
var userid = $(this).data('user-id');
var renderView = $(this).data('render-view');
$.ajax({
url: "users.php",
type: "POST",
data: {userid:userid},
success: function(data, textStatus, jqXHR){
window.location = renderView;
},
error: function (jqXHR, textStatus, errorThrown){
alert('Error!')
}
});
});
</script>
</body>
</html>
Users.php
<?php
$userIdExchanged = $_POST['userid'];
echo '<h1>user profile page</h1>';
echo $userIdExchanged; //Nothing is outputted here.
?>
Yes thats really what happened, basically, first step, you sent an ajax request, sending that value user-id.
Then after that you redirect. This means that you have two separate requests.
The first request was successful. After redirection (here comes the second) your values aren't there anymore since the data on the first request did not persist.
I don't know why do you have to make an ajax request. Might as well submit the form normally.
But if you really want to stay on this course, on the first request (the ajax request), you could save it in the session.
So that value that you sent will be saved. Then after redirection, you still have it for access:
<script type="text/javascript">
// maybe you mean `.user-name` not `.user-staff`
$('.user-name').on('click',function(){
var userid = $(this).data('user-id');
var renderView = $(this).data('render-view');
$.ajax({
url: "users.php",
type: "POST",
data: { userid: userid, setid: true }, // add a flag
success: function(data, textStatus, jqXHR){
window.location = renderView;
},
error: function (jqXHR, textStatus, errorThrown){
alert('Error!')
}
});
});
</script>
Then in PHP:
<?php
session_start();
// if the set flag is used, set it
if(isset($_POST['setid'])) {
$_SESSION['userid'] = $_POST['userid'];
}
// if no flag is set, then this will just continue and echo the value currently set
$userIdExchanged = $_SESSION['userid'];
echo '<h1>user profile page</h1>';
echo $userIdExchanged;
?>
Your class name in the html tags is "user-name" but you are listening for clicks on a class name of "user-staff" in your .js. Unsure if that is just a typo...
<a href="#" class="user-name" ......
$('.user-staff').on('click',function(){....

How to send large data using jquery post without redirect page?

I'd like to know how to send large data using jquery POST without redirect page?
I have a project to create a mobile chat, and to connect between user app and server, i use JSON.
this is jquery get json script looks like, as we know jsonGet can't deal with large data.
note: bigNumber has 8000 characters.
$.getJSON('process.php?input='+bigNumber, function(data) {
$.each(data.Chats, function(i,output)
{
$("#data").append(output.chat);
});
});
this is what i get when using getJSON for sending big number: 414 (Request-URI Too Large)
So, after i send bigNumber, i'll get a response from process.php as json data and adding to the body of html.
//---
now this is my code.
html file
<script src="jquery.min.js"></script>
<script>
$(function(){
$("#senddata").click(function() {
$.ajax({
dataType: "json",
url: "process.php",
data: { input:$("#bigNumber").val() },
success: function(data) {
$.each(data.Chats, function(i,output)
{
$("#data").append(output.key);
});
},
method: "POST"
});
});
});
</script>
<div id="data"></div>
<input type="text" id="bigNumber"/>
<button id="senddata">Send</button>
and this is process.php
header('Content-type: application/json');
$key = $_POST["input"];
$simpan_array = array();
$chat = array();
$chat["key"] = $key;
array_push($simpan_array, $chat);
echo json_encode(array("Chats" => $simpan_array));
and when i fill the textbox and press the "Send" button, nothing happens.
what's wrong?
Just found out what the problem is, it was an error in json format, which is displayed on process.php
You need to use a POST request instead. And since getJSON() is just a facade for ajax(), it is pretty easy to convert:
$.ajax({
dataType: "json",
url: "process.php",
data: { input:bigNumber },
success: function(data) {
$.each(data.Chats, function(i,output)
{
$("#data").append(output.chat);
});
},
method: "post"
});
use $.post
$.post('process.php',{input: bigNumber}, function(data) {
$.each(data.Chats, function(i,output)
{
$("#data").append(output.chat);
});
},'JSON');
Why cant you try to use websockets for chat application refer this page
Web Socket Server or Introduction to HTML5 WebSocket

Categories