Not printing results from AJAX - javascript

I am working on a script to send data to a mysql table and I have it all working properly but the success part of the call, it is not loading my results in to my results column on my page. My code is below.
Any suggestions on what I can do to fix that? I am guessing the problem is within my "success:" option in my AJAX call.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Facebook like ajax post - jQuery - ryancoughlin.com</title>
<link rel="stylesheet" href="css/screen.css" type="text/css" media="screen, projection" />
<link rel="stylesheet" href="css/print.css" type="text/css" media="print" />
<!--[if IE]><link rel="stylesheet" href="css/ie.css" type="text/css" media="screen, projection"><![endif]-->
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
/* <![CDATA[ */
$(document).ready(function(){
$('p.validate').hide();
$.getJSON("readJSON.php",function(data){
$.each(data.posts, function(i,post){
content = '<div id="post-'+ post.id +'">\n';
content += '<h3>' + post.author + '</h3>\n';
content += '<p class="small quiet">' + post.date_added + '</p>\n';
content += '<p>' + post.post_content + '</p>';
content += '<hr/>';
$("#contents").append(content).fadeIn("slow");
});
});
$(".reload").click(function() {
$("#posts").empty();
});
$("#add_post").submit(function() {
$('p.validate').empty();
// we want to store the values from the form input box, then send via ajax below
var author = $('#author').attr('value');
var post = $('#post').attr('value');
if(($('#author').val() == "") && ($('#post').val() == "")){
$("p.validate").fadeIn().append("Both fields are required.");
$('#author,#post').fadeIn().addClass("error");
}else{
$.ajax({
type: "POST",
url: "ajax.php",
data: "author="+ author + "&post=" + post,
success: function(result){
$('#contents').after( "<div>" +result +"</div>" );
}
});
}
return false;
});
});
/* ]]> */
</script>
<style type="text/css">
h3{margin:10px 0;}
p{margin:5px 0;}
#posts{display:none;}
</style>
</head>
<body>
<div class="container">
<div class="span-24">
<div id="post-container" class="span-9 colborder">
<h2>Posts loaded via Ajax:</h2>
<div id="contents"></div>
</div>
<div id="form" class="span-11">
<h2>New Post:</h2>
<form name="add_post" id="add_post" action="">
<label>Author:</label><br />
<input type="text" name="author" id="author" size="15" class="text" /><br />
<label>Post:</label><br />
<textarea name="post" id="post" rows="5" cols="5" class="text"></textarea><br />
<input type="submit" value="Post" id="submit" /><br />
</form><br />
<p class="validate error"></p>
</div>
</div>
<div class="span-24">
Reload
</div>
</div>
</body>
</html>

Questions to ask yourself...
Does jQuery even run your success callback?
If so is the response data well formed markup?
To begin I would add a "debugger;" statement to your success function (assuming you have firefox and firebug). This will enable you to break into the script console and get a better understanding of what is happening.
The debugger statement will cause the script execution to pause and break into the firebug console. Try the following
success: function(result){
debugger;
$('#contents').after( "<div>" +result +"</div>" );
}
If your script hits this I suspect your response markup is not well formed and jQuery is having issues parsing into the div but you can check all this when your at that breakpoint in firebug.
Another easy thing to check and dismiss in your debugging is
does your web server serve a valid (status 200) response (check the console or net tab in firebug to see this, or use the likes of fiddler if running in ie)
Let me know how you get on.

You might be getting an error try adding a debug statement to your ajax call using the error setting
$.ajax({
type: "POST",
url: "ajax.php",
data: "author="+ author + "&post=" + post,
error: function(XMLHttpRequest, textStatus, errorThrown)
{ alert(errorThrown); },
success: function(result){
$('#contents').after( "<div>" +result +"</div>" );
}
});

Related

Sending data using Ajax to PHP

I am trying to send a string via ajax using the GET method but whenever that string contains some punctuation characters those characters do not appear when I use the echo in php.
For example if I send a string "sub + 12" the php will echo "sub 12"
If I send "&()*", php will echo an empty string.
Why does this happen?
Are there any special characters that the string cannot contain?
you encodeURIComponent(). this is demo code which you can check
something like this encodeURIComponent(yourtext)
first this html code . in text filed enter your text and check this output, this is onkeyup so enter text and check result
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>PHP, jQuery search demo</title>
<link rel="stylesheet" type="text/css" href="my.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("input").keyup(function () {
$('#results').html('');
var searchString = $("#search_box").val();
var data = 'search_text=' + encodeURIComponent(searchString);
if (searchString) {
$.ajax({
type: "GET",
url: 'edit.php',
data: data,
dataType: 'text',
async: false,
cache: false,
success: function (result) {
$('#results').html(result);
//window.location.reload();
}
});
}
});
});
</script>
</head>
<body>
<div id="container">
<div style="margin:20px auto; text-align: center;">
<form method="post" action="do_search.php">
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button"/><br/>
</form>
</div>
<div>
<div id="searchresults">Search results :</div>
<ul id="results" class="update">
</ul>
</div>
</div>
</body>
</html>
then create edit.php file
<?php
$searchquery = $_GET['search_text'];
echo $searchquery;
?>
then check result . which is working
Output is
Search results :
&()*
Use encodeURI() before sending the request.

php login only works after refresh [duplicate]

This question already has answers here:
PHP session variables not preserved with ajax
(6 answers)
Do AJAX requests retain PHP Session info?
(8 answers)
Set php session via ajax
(3 answers)
Closed 5 years ago.
I'm working with a simple login system with php/sql.
used it several weeks working on localhost, but now that the site is actually online, my login page doesn't work (only if i refresh the page)
working with session.
Are there any tips/things i can try to make it actually go to my index.php instead of manually refreshing the page? As i said it worked locally, nothing changed when going online.
LOGIN.JS
$(document).ready(function () {
"use strict";
$("#submit").click(function () {
var username = $("#myusername").val(), password = $("#mypassword").val();
if ((username === "") || (password === "")) {
$("#message").html("<div class=\"alert alert-danger alert-dismissable\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>Please enter a username and a password</div>");
} else {
$.ajax({
type: "POST",
url: "checklogin.php",
data: "myusername=" + username + "&mypassword=" + password,
dataType: 'JSON',
success: function (html) {
//console.log(html.response + ' ' + html.username);
if (html.response === 'true') {
windows.location.assign("http://kdlk.heijsgroep.nl/heijs/index.php");
window.location.reload(true);
return html.username;
} else {
$("#message").html(html.response);
}
},
error: function (textStatus, errorThrown) {
console.log(textStatus);
console.log(errorThrown);
},
beforeSend: function () {
$("#message").html("<p class='text-center'><img src='images/ajax-loader.gif'></p>");
}
});
}
return false;
});
});
main_login.php
<?php
session_start();
if (isset($_SESSION['username'])) {
header("location:../index.php");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="../css/bootstrap.css" rel="stylesheet" media="screen">
<link href="../css/main.css" rel="stylesheet" media="screen">
<link href="../style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<form class="form-signin" name="form1" method="post" action="checklogin.php">
<h2 class="form-signin-heading">Please sign in</h2>
<input name="myusername" id="myusername" type="text" class="form-control" placeholder="Username" autofocus>
<input name="mypassword" id="mypassword" type="password" class="form-control" placeholder="Password">
<!-- The checkbox remember me is not implemented yet...
<label class="checkbox">
<input type="checkbox" value="remember-me"> Remember me
</label>
-->
<button name="Submit" id="submit" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
<div id="message"></div>
</form>
</div> <!-- /container -->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/jquery-2.2.4.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script type="text/javascript" src="js/bootstrap.js"></script>
<!-- The AJAX login script -->
<script src="js/login.js"></script>
</body>
</html>
login header
<?php
//PUT THIS HEADER ON TOP OF EACH UNIQUE PAGE
session_start();
if (!isset($_SESSION['username'])) {
header("location:login/main_login.php");
}
?>

Use JQuery to get data from JSON file

Overflow!
I'm currently working on a little application I have to finish for school monday. I didn't have a lot of time to make something big. So I decided, why not retrieve information of Steam's Web Api and get the stats of players.
The url to the steam api:
http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=76561198263871727
The last parameter &steamid= represents the id of the player. Now I have found out how to get the steamid into a variable, but when trying to add the id to the rest of the url (http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=id should be here and fetching the data with the Ajax.getJson method.. It just doesn't work.. I'm for very experienced with JSON btw.. Can someone help me out with this?
My Web Page:
<!DOCTYPE html>
<html lang="en">
<head>
<!--Meta Information-->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--JQuery Mobile-->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<!--FontAwesome-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<!--Custom Styles-->
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div data-role="page" id="index">
<div data-role="header">
<h1>CS:GO Stats</h1>
</div>
<div data-role="main" class="ui-content">
<div class="search">
<label for="search">Enter SteamID:</label>
<input type="search" name="search" id="inputSearch" />
<input type="submit" id="butSearch" data-inline="true" value="Search SteamID">
</div>
<div id="result">
</div>
</div>
</div>
<!--getSteamUserId function-->
<script src="js/getSteamUserId.js"></script>
</body>
</html>
My Javascript Code:
$(document).ready(function() {
$('#butSearch').click(function(event) {
var input = $('#inputSearch').val();
$.getJSON( "http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=" + input, function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "#result" );
});
})
})
Now what I want is to get the stats data from the JSON file into my web page. Would anyone know how to do this? I can also see the JSON is not only a flat JSON file.. Like it has different layers (if that's a good explenation)..
Thanks in advance!
Work with jsonP like here:
$.ajax({
url: url,
dataType: 'JSONP',
type: 'GET',
jsonp: 'jsonp',
success: handler
});
Working example here
I'm not entirely sure about the first part. It gives me an error which after googling led me to "No 'Access-Control-Allow-Origin' header is present on the requested resource" which advises using CORS. Error:
XMLHttpRequest cannot load http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=&76561198263871727. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 400.
Once you have the JSON it's easier. If it's stringified you can turn it into a javascript object with
steamObject = JSON.parse(steamJsonData);
and then navigate through it like a normal javascript object. Cycle through playerstats.stats[i] with a for loop and you can add the data to your page using normal DOM manipulation.

Basic POST with JQuery Mobile from form using php

Firstly I apologize for posting another one of these questions, but I've dove through a ton of SO questions related to this topic and haven't be able to figure out my problem. I'm new to PHP and an amature at best using Jquery mobile and the like.
I'm attempting to post to a .php file and get a response back. Eventually this will evolve into a database posting yada yada. For now, I can't seem to get my response back from my post. I'm running Xampp to host the php, Jquery Mobile is being used in other functions so it does work properly,
HTML:
<form>
<p>Username: </p><input type="text" id="username" value="" />
<p>Password: </p><input type="text" id="password" value="" />
<input type="button" onclick="submitLogIn()" value="Log In" />
</form>
Javascript:
function submitLogIn() {
alert("Submitting: " + $('#username').val() + $('#password').val());
var dbURL = "http://localhost/testerpage.php";
$.post(dbURL, {
//These are the names of the form values
Username: $('#username').val(),
Password: $('#password').val()
}, function (data,status) {
alert(status); //Won't fire
alert(html); //Won't fire
var response = html;
alert(response); //Won't fire
if (response == "Success")
{
alert("Success!"); //Won't fire
//testlog.innerHTML = "Success";
}
else
{
alert("Failure!");//Won't fire
//testlog.innerHTML = "Failure";
}
});
alert("Finished"); //Fires
};
PHP
<?php
// VARS
$Username=$_GET["Username"]; //Also tried _POST
$Password=$_GET["Password"]; //Also tried _POST
//VALIDATION
if(
$Username=="" ||
$Password==""
) {
echo "Error";
} else {
echo "Success";
}
?>
My best guess is that something is wrong with the .php because all of the questions I've looked at seem to confirm my JavaScript is right. All of my alerts fire except the ones in the call back function. The username and password are also correctly being set so that isn't the problem. I tried using _POST and _GET in my .php, I originally was using _POST because I was posting data but I was following this question: (Phonegap contact form not working over PHP) and it did the opposite so I changed it. No difference. My .php is actually hosted for sure (I can navigate to it without an error). I also tried using the $.ajax function but had the same issues.
Thanks in advance.
EDIT: Added more of the HTML (all that should be relevant) per request, can't add it all as it is too long.
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<!-- Stylesheets -->
<link rel="stylesheet" href="css/snctfy2/snctfy2.css" />
<link rel="stylesheet" href="css/snctfy2/jquery.mobile.icons.min.css" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<link href="jquerymobile/jquery.mobile.structure-1.4.2.min.css" rel="stylesheet" type="text/css" /> <!-- Add .structure after theme-->
<!-- Jquery core -->
<script src="js/jquery.js" type="text/javascript"></script>
<!-- Jquery mobile library file -->
<script src="jquerymobile/jquery.mobile-1.4.2.min.js" type="text/javascript"></script>
<!-- DateBox -->
<link rel="stylesheet" type="text/css" href="css/jqm-datebox.css" />
<script type="text/javascript" src="js/datebox/jqm-datebox.core.js"></script>
<script type="text/javascript" src="js/datebox/jqm-datebox.mode.calbox.js"></script>
<script type="text/javascript" src="js/datebox/jqm-datebox.mode.datebox.js"></script>
<script type="text/javascript" src="js/datebox/jquery.mobile.datebox.i18n.en_US.utf8.js"></script>
<!-- Scripts (pre-load)-->
<script src="js/scripts.js" type="text/javascript"></script>
<!-- CSS Override -->
<link rel="stylesheet" type="text/css" href="css/override.css" />
<title>SNCTFY</title>
</head>
<body>
<!--there is some more <div> tags here unrelated-->
<!--------------------------------------------------------Login Page---------------------
-------------------------------------------->
<div data-role="page" id="login" data-theme="a" class="bPage">
<div data-role="content">
<form>
<p>Username: </p><input type="text" id="username" value="" />
<p>Password: </p><input type="text" id="password" value="" />
<input type="button" onclick="submitLogIn()" value="Log In" />
</form>
Register
<button onclick="showAlert()">Test</button>
<p id="testlog">Results</p>
</div>
</div>
<!-- more <div> pages -->
<!-- Scripts (post-load)-->
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
EDIT2: Changed JavaScript to one of the answers to test
function submitLogIn() {
alert("Submitting: " + $('#username').val() + $('#password').val());
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
type: "POST",
url: "http://localhost/testerpage.php",
data: { "Username": username, "Password": password },
success: function (data) {
if (data) {
alert(data);
}
else {
alert('Successfully not posted.');
}
}
});
};
Just try jquery Ajax
<body>
<form>
<p>Username: </p><input type="text" id="username" value="" />
<p>Password: </p><input type="text" id="password" value="" />
<input type="button" onclick="submitLogIn()" value="Log In" />
</form>
<script>
function submitLogIn() {
alert("Submitting: " + $('#username').val() + $('#password').val());
var username =$('#username').val();
var password = $('#password').val();
$.ajax({
type: "POST",
url: "http://localhost/testerpage.php",
data:{"Username":username,"Password":password},
success: function(data) {
if (data) {
alert(data);
}
else {
alert('Successfully not posted.');
}
}
});
}
</script>
</body>
</html>
in PHP
<?php
$Username=$_POST["Username"]; //Also tried _POST
$Password=$_POST["Password"]; //Also tried _POST
//VALIDATION
if(
$Username=="" ||
$Password==""
) {
echo "Error";
} else {
echo "Success";
}
?>
Try this:
function submitLogIn() {
alert("Submitting: " + $('#username').val() + $('#password').val());
var dbURL = "http://localhost/testerpage.php";
//These are the names of the form values
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url: dbURL,
type:'post',
data:'&username='+username+'&pass='+password,
success:function(response){
alert(response);
}
});
};
<?php
// VARS
$Username=$_POST["username"]; //Also tried _POST
$Password=$_POST["pass"]; //Also tried _POST
//VALIDATION
if(
$Username=="" ||
$Password==""
) {
echo "Error";
} else {
echo "Success";
}
?>
try this code
script
<script>
function submitLogIn() {
alert("Submitting: " + $('#username').val() + $('#password').val());
var dbURL = "http://localhost/testerpage.php";
$.post(dbURL, {
//These are the names of the form values
Username: $('#username').val(),
Password: $('#password').val()
}, function (data,status) {
if (data == "Success")
{
alert("Success!"); //Won't fire
//testlog.innerHTML = "Success";
}
else
{
alert("Failure!");//Won't fire
//testlog.innerHTML = "Failure";
}
});
alert("Finished"); //Fires
};
</script>
PHP
// VARS
$Username=$_POST["Username"]; //Also tried _POST
$Password=$_POST["Password"]; //Also tried _POST
//VALIDATION
if(
$Username=="" ||
$Password==""
) {
echo "Error";
} else {
echo "Success";
}

My Javascript Ajax request works in Phonegap index.html but not in any other pages, how can I fix this?

The request I have made works in the index.html file but not in any others which is greatly frustrating. I think it is to do with the onDeviceReady function but I am not sure how to change or fix this?
Here is the separate page (not index.html) code:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0;" />
<script src="cordova-1.8.1.js"></script>
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/load-whites.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>
</head>
<body>
<div data-role="page" id="whites">
<div data-role="header" data-position="fixed">
<h1>White Wines</h1>
</div>
<div data-role="content">
<div data-role="collapsible-set" data-theme="c" data-content-theme="d">
<div id="whites"></div>
</div>
</div>
</div>
</body>
Here is the request that works for the index.html file but not for any other .html files in my phonegap project (Cordova 1.8.1). How could I change it so that it does work? the file below is load-whites.js:
$(document).ready(function(){
$(document).bind('deviceready', function(){
onDeviceReady();
});
function yourCallback(button) {
if (button == 2) {
dataRequest();
}
}
function dataRequest() {
var output = $('#whites').text('Loading white wines and their deta1ils, please wait...');
$.ajax({
url: 'http://localhost/whites.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
output.empty();
$.each(data, function(i,item){
var whites = '<div data-role="collapsible"><h3>'+item.Name+'</h3>'
+'<b>Price:</b> £'+item.Price+'<br />'
+'<b>Vintage:</b> '+item.Vintage+'<br />'
+'<b>Country:</b> '+item.Country+'<br />'
+'<b>Grape:</b> '+item.Grape+'<br />'
+'<b>Alcohol:</b> '+item.Alcohol+'%<br /><br />'
+item.Description+'</p></div>';
output.append(whites);
$('#whites').trigger('create');
});
},
error: function(){
output.text('The Wines could not be loaded at this time.');
navigator.notification.confirm(
'Please check your internet connection. Would you like to retry?',
yourCallback,
'Something went wrong',
'No,Yes'
);
}
});
}
dataRequest();
});
Any help would be greatly appreciated. Thanks again.
I see you are using JQuery mobile. Its possible it could be similar to a problem I had today and JQuery mobile was the culprit. http://jquerymobile.com/demos/1.1.1/docs/pages/page-scripting.html
If you are declaring the Javascript file in the header another page other than the index, it will ignore it. If this is your problem, declare the JS file load-whites.js in the index then..
$( document ).delegate("#PAGENAME", "pageinit", function() {
//do work here
});
Not sure if this is your problem, but could be!

Categories

Resources