jQuery don't work on phonegap - javascript

This code works perfectly in different browser (Chrome, Firefox, Safari), but in PhoneGap, when I click the button 'login' the logme function does not work.
I have tried to replace click by vclick,
or //ajax.gooogleapis.com/.... by file://ajax.goo.... but it does not work.
Do you have an idea of the problem?
thanks
<!DOCTYPE html>
<html>
<head>
<style>
* { font-family: Verdana, Geneva, sans-serif; line-height: 30px }
.title { background:#333; color: white; }
.success { color: #060; font-weight: bold; }
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var apiURL = "localhost/wordpress/api/";
var noncestring = "get_nonce/?";
var authstring = "user/generate_auth_cookie/?";
var poststring = "posts_auth/create_post/?";
var username, password;
var nonce, cookie;
$('document').ready(function(){
$('#logme').click(function() {
jQuery(function($) {
username = document.forms["logme"].elements["username"].value;
password = document.forms["logme"].elements["password"].value;
});
getNonce("user", "generate_auth_cookie");
function getNonce(controller, method) {
$.getJSON(apiURL + noncestring + "controller=" + controller + "&method=" + method, function(data) {
var items = [];
$.each(data, function(key, val) {
if (key == "nonce") {
nonce = val;
$('.status').append("<br>Nonce acquired for controller '" + controller + "', method '" + method + "': " + val);
// Add additional methods here. Could make this a switch statement.
if (method == "generate_auth_cookie")
createAuthCookie();
if (method == "create_post")
createPost();
getid();
}
});
});
}
function createAuthCookie() {
$('.status').append("<br>creating -> auth cookie with nonce " + nonce);
var authCookieURL = apiURL + authstring + "nonce=" + nonce + "&username=" + username + "&password=" + password;
$.getJSON(authCookieURL, function(data) {
var items = [];
$.each(data, function(key, val) {
if (key == "cookie") {
cookie = val;
$('.status').append("<br>Auth cookie -> acquired! value: " + val);
// Get a new nonce to create the post:
getNonce("posts_auth", "create_post");
}
});
});
}
function getid() {
$('.status').append("<br>Get -> id");
var authCookieURL = apiURL + authstring + "nonce=" + nonce + "&username=" + username + "&password=" + password;
$.getJSON(authCookieURL, function(data) {
var items = [];
$.each(data, function(key, val) {
if (key == "user") {
user = val;
$('.status').append("<br>id -> acquired! value: " + user.id + "<br>username -> acquired! value: " + user.username + "<br>nicename -> acquired! value: " + user.nicename + "<br>email -> acquired! value: " + user.email + "<br>avatar url -> acquired! value: " + user.avatar);
// Get a new nonce to create the post:
getNonce("posts_auth", "create_post");
}
});
});
}
function createPost() {
$('.status').append("<br>creating -> post with nonce: " + nonce);
var cookiepart = "&cookie=" + cookie;
var postContent = "&status=publish&title=NonceTest&content=test+test&author=Alex&categories=Demos&tags=test,api,json";
$.getJSON(apiURL + poststring + "nonce=" + nonce + cookiepart + postContent, function(data) {
var items = [];
$.each(data, function(key, val) {
if (key == "status") {
console.log("status value: " + val);
if (val == "ok") {
$('.status').append("<br><span class='success'> -> A new post was successfully created.</span>");
}
}
});
});
}
});
});
</script>
</head>
<body>
<div id="wrapper">
<div class="title">Json Test 3</div>
<form id="loginForm" method="get" accept-charset="utf-8" name="logme">
<fieldset>
<div data-role="fieldcontain">
<label for="email"> Username </label>
<input type="text" name="username" id="email" value="">
</div>
<div data-role="fieldcontain">
<label for="password"> Password </label>
<input type="password" name="password" id="password" value="">
</div>
<input type="button" data-theme="g" name="submit" id="logme" value=" Login ">
</fieldset>
</form>
<div class="status">Getting nonce for auth cookie...</div>
</div>
</body>
</html>

Load jquery as 'http://'. I had this problem too when trying to load remote files with Phonegap (or Ionicframework), just '//' does not seem to work.

Your jquery works 100%. The problem is your apiURL is not from external server, its just from localhost. try test on external server. don't use localhost.

Related

How to create a clone of Search field?

I have a search field in my app. I need to clone this search field with the same functions. One search field at the left side of the page and another, the same search field, at the right side of the page.
How I can make the clone using JS?
Below my JS code
document.querySelector('#city').addEventListener(click,'keyup', function(e) {
if (e.keyCode === 13) {
var city = $(this).val();
if (city !== '') {
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" +
"&APPID=bb037310921af67f24ba53f2bad48b1d",
type: "GET",
dataType: "json",
success: function (data) {
var widget = show(data);
$("#show").html(widget);
$("#city").val(' ');
}
});
} else {
$("#error").html("<div class='alert alert-danger text-center'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>Field cannot be empty</div>");
}
};
});
function show(data) {
return "<h2>Current Weather for " + data.name + "," + data.sys.country + "</h2>" +
"<h3><strong>Wind Speed</strong>: " + data.dt + "</h3>" +
"<h3><strong>Weather</strong>: <img src='http://openweathermap.org/img/w/" + data.weather[0].icon + ".png'>" + data.weather[0].main + "</h3>" +
"<h3><strong>Description</strong>: " + data.weather[0].description + "</h3>" +
"<h3><strong>Temperature</strong>: " + data.main.temp + "°C</h3>" +
"<h3><strong>Wind Direction</strong>: " + data.wind.deg + "°</h3>";
}
and part of HTML code
<body>
<div class="jumbotron" id="jumbo">
<h2 class="text-center" id="th2">Weather</h2>
</div>
<div class="container" id="cont">
<div class="row">
<h2 class="text-center text-primary">Your City</h2>
<span id="error"></span>
</div>
<div class="row form-group form-inline" id="rowDiv">
<input type="text" name="city" id="city" class="form-control" placeholder="City Name">
<button id="submitWeather" class="btn btn-primary">Search City</button>
</div>
<div id="show"></div>
</div>
As an option, I would suggest to create some function or class that creates input and description nodes and append to whatever container id (or class) you pass to it. In html you would only need element with rowDiv id. Obviously you can tailor it to your needs, but it's just an idea.
I thought something like this:
// rough example based of your code
class citySearch {
constructor(parentContainerId) {
this.searchField;
this.displayArea;
this.setStage(parentContainerId);
this.hookListener();
}
setStage(parentContainerId) {
this.searchField = document.createElement('input');
this.displayArea = document.createElement('div');
var parentContainer = document.getElementById(parentContainerId)
parentContainer.appendChild(this.searchField);
parentContainer.appendChild(this.displayArea);
}
show(data) {
return "<h2>Current Weather for " + data.name + "," + data.sys.country + "</h2>" +
"<h3><strong>Wind Speed</strong>: " + data.dt + "</h3>" +
"<h3><strong>Weather</strong>: <img src='http://openweathermap.org/img/w/" + data.weather[0].icon + ".png'>" + data.weather[0].main + "</h3>" +
"<h3><strong>Description</strong>: " + data.weather[0].description + "</h3>" +
"<h3><strong>Temperature</strong>: " + data.main.temp + "°C</h3>" +
"<h3><strong>Wind Direction</strong>: " + data.wind.deg + "°</h3>";
}
hookListener() {
this.searchField.addEventListener('keypress', this.onClick.bind(this));
}
onClick(e) {
if (e.keyCode === 13) {
var city = this.searchField.value;
if (city !== '') {
fetch('http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" + "&APPID=bb037310921af67f24ba53f2bad48b1d")
.then( async(res) => {
const data = await res.json();
var widget = this.show(data);
this.displayArea.innerHTML = widget;
this.searchField.value = '';
})
} else {
this.displayArea.innerHTML = "<div class='alert alert-danger text-center'><a href='#' class='close' data-dismiss='alert' aria-label='close'>×</a>Field cannot be empty</div>";
}
}
}
}
var firstSearch = new citySearch('rowDiv');
var secondSearch = new citySearch('rowDiv');
Html
<div class="row form-group form-inline" id="rowDiv"></div>
Here is some sample code that allows 1 code base, 2 search boxes and keeps the two search boxes in sync.
const searchBoxes = () => document.getElementsByClassName('searchbox');
document.addEventListener('DOMContentLoaded', function() {
Array.from(searchBoxes()).forEach(element => {
console.log(element.id);
element.addEventListener('keyup', function(event) {
let text = event.target.value;
// This is just a demo
document.getElementById("searchResult").innerHTML = text;
// Loop other search boxes
Array.from(searchBoxes()).forEach(e => {
if (e.id != event.target.id) e.value = text;
});
// ANY CODE HERE TO APPLY SEARCH
});
});
});
.searchbox {
border: 1px solid black;
background-color: wheat;
}
#searchResult {
height: 100px;
width: 100px;
background-color: yellow;
font-weight: bold;
}
<div>
<span>Some Text Here</span>
<input id="search1" class="searchbox" type="text" />
</div>
<div id="searchResult">ALL MY PAGE STUFF</div>
<div>
<span>Some Text Here</span>
<input id="search2" class="searchbox" type="text" />
</div>

Javascript: return false from asynchronous function

I'm having some real trouble trying to get this form to work properly. The form should validate each field and successfully charge a credit card before submitting.
The issue is that I can't pass my return value to the parent function to prevent the form from submitting. I read this post and tried using deferred objects, a callback function, and placing return statements all over the place but I'm missing something. I've been at this for about a week and the frustration is getting to me. Could anyone help me with this? I would greatly appreciate it and thanks!
HTML:
<form onSubmit="return billingfunction1();" name="form5" method="post" action="" id="newform">
</form>
JS: (trimmed to size)
function billingfunction1() {
var first_name = $.trim($("#first_name").val());
var last_name = $.trim($("#last_name").val());
var cardtype = $.trim($("#cardtype").val());
var maxlen = 16;
var digits = cardnumber.toString().length;
var submiteval;
if (cardtype == '') {
// alert("Enter Card Type");
$('#cardtype_msg').html('Enter Card Type.');
$('#cardtype').css('border','1px solid #28a616');
$('#cardtype').css('box-shadow','0 0 3px 0 #28a616');
return false;
} else if (nameoncardfirst == '') {
//alert("Enter Name On Card");
$('#nameoncardfirst_msg').html('Enter First Name On Card.');
$('#nameoncardfirst').css('border','1px solid #28a616');
$('#nameoncardfirst').css('box-shadow','0 0 3px 0 #28a616');
return false;
} else if (nameoncardlast == '') {
//alert("Enter Name On Card");
$('#nameoncardlast_msg').html('Enter Last Name On Card.');
$('#nameoncardlast').css('border','1px solid #28a616');
$('#nameoncardlast').css('box-shadow','0 0 3px 0 #28a616');
return false;
} else {
function foo(callback) {
return $.ajax({
url: 'edit_billing2.php',
data: "nameoncardfirst=" + nameoncardfirst+ "&nameoncardlast=" + nameoncardlast + "&street_address2=" + street_address2 +"&city2=" + city2 +"&state=" + state +"&zip=" + zip + "&cardnumber=" + cardnumber + "&expirationdate=" + expirationdate + "&cvv=" + cvv + "&cardtype=" + cardtype+ "&amount=" + amount + "&gender=" + gender + "&first_name=" + first_name + "&last_name=" + last_name + "&address=" + address + "&address2=" + address2 + "&city=" + city + "&post_code=" + post_code + "&country=" + country + "&mobile=" + mobile + "&email=" + email + "&newsletter=" + newsletter + "&make=" + vehicle + "&model=" + model + "&model_year=" + model_year,
success: callback
});
}
function myCallback(response) {
console.log("Success response. Attempting to authorize payment.");
//alert(response);
result = response.split('_');
//alert("Successfully Saved");
alert(result[0]);
if(result[0]=="Your Payment has completed successfully")
{
console.log("Payment Success");
submiteval = true;
}
else
{
console.log("Payment Failed, Aborting form submission.");
submiteval = false;
}
return submiteval;
}
console.log("Valid inputs: attempting to pass via AJAX");
foo(myCallback).done(function(response) {
return submiteval;
});
}
EDIT:
I tried using event.preventDefault() to stop the submission and handle the submission manually, but then the form would reload the current page and skip over some PHP I had before the form code that I neglected to mention:
if (isset($_POST[Submit]))
{
// do registration things
}
I ended up changing the $_POST[Submit] to
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
// do registration things
}
removing the onsubmit attribute from my form:
<form name="form5" method="post" action="" id="newform">
and moving it to my submit button:
<input onClick="return billingfunction1();" type="submit" value="Submit"
name="Submit" class="submit_btn">
My new callback function will submit the form manually under the success condition:
function myCallback(response) {
console.log("Success response. Attempting to authorize payment.");
result = response.split('_');
alert(result[0]);
if(result[0]=="Your Payment has completed successfully") {
console.log("Payment Success");
document.forms["form5"].submit();
} else {
console.log("Payment Failed, Aborting form submission.");
}
}
Everything seems to be working as it should. Thanks so much for your help!
You can just add a submit listener to the form
$("#newform").submit(function(){...})
Prevent the default action
event.preventDefault()
And submit the form manually
$("#newform").submit()
if the condition is meet when the response to the AJAX call comes back.
emphasized text
function billingfunction1() {
var first_name = $.trim($("#first_name").val());
var last_name = $.trim($("#last_name").val());
var cardtype = $.trim($("#cardtype").val());
var maxlen = 16;
var digits = cardnumber.toString().length;
var submiteval;
if (cardtype == '') {
// alert("Enter Card Type");
$('#cardtype_msg').html('Enter Card Type.');
$('#cardtype').css('border','1px solid #28a616');
$('#cardtype').css('box-shadow','0 0 3px 0 #28a616');
return false; //show error to the user instead of returning false
} else if (nameoncardfirst == '') {
//alert("Enter Name On Card");
$('#nameoncardfirst_msg').html('Enter First Name On Card.');
$('#nameoncardfirst').css('border','1px solid #28a616');
$('#nameoncardfirst').css('box-shadow','0 0 3px 0 #28a616');
return false; //show error to the user instead of returning false
} else if (nameoncardlast == '') {
//alert("Enter Name On Card");
$('#nameoncardlast_msg').html('Enter Last Name On Card.');
$('#nameoncardlast').css('border','1px solid #28a616');
$('#nameoncardlast').css('box-shadow','0 0 3px 0 #28a616');
return false; //show error to the user instead of returning false
} else {
$.ajax({
url: 'edit_billing2.php',
data: "nameoncardfirst=" + nameoncardfirst+ "&nameoncardlast=" + nameoncardlast + "&street_address2=" + street_address2 +"&city2=" + city2 +"&state=" + state +"&zip=" + zip + "&cardnumber=" + cardnumber + "&expirationdate=" + expirationdate + "&cvv=" + cvv + "&cardtype=" + cardtype+ "&amount=" + amount + "&gender=" + gender + "&first_name=" + first_name + "&last_name=" + last_name + "&address=" + address + "&address2=" + address2 + "&city=" + city + "&post_code=" + post_code + "&country=" + country + "&mobile=" + mobile + "&email=" + email + "&newsletter=" + newsletter + "&make=" + vehicle + "&model=" + model + "&model_year=" + model_year,
success: myCallback
});
function myCallback(response) {
console.log("Success response. Attempting to authorize payment.");
//alert(response);
result = response.split('_');
//alert("Successfully Saved");
alert(result[0]);
if(result[0]=="Your Payment has completed successfully")
{
console.log("Payment Success");
submiteval = true;
document.forms["form5"].submit();
}
else
{
console.log("Payment Failed, Aborting form submission.");
submiteval = false; //show error to the user instead of returning false
}
return submiteval;
}
}
<form name="form5" method="post" action="" id="newform">
<input type="button" value ="submit" onClick="billingfunction1();" />
</form>
Assign billingfunction1 to onclick event instead of submit.
use document.forms["form5"].submit() to manually submit the form after validating the response from server.
$.ajax has a option named beforeSend(func). U can validate ur data in this func, and return false to cancel ajax.

Weird JS Behavior With Bootstrap Sliders

So I recieved help from an internet saint to vastly improve my code to create a bootstrap slider per list item within a JS for loop, but now it is behaving erratically.
Sometimes it works perfectly, others it creates new items but not sliders (just a text input field), and others it only creates one item per list.
Any great minds see where I'm going wrong?
var proArray = [];
function addPro() {
var val = document.getElementById("proInput").value.trim();
document.getElementById("proForm").reset();
if (val.length == 0) {
return;
}
if (document.getElementById('proInput' + val) == null) {
proArray.push({id: val, slider: null});
} else {
return;
}
for (var i = 0; i < proArray.length; i++) {
var ele = document.getElementById('proInput' + proArray[i].id);
if (ele == null) {
var newItem = "<li><p>" + proArray[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='proInput" +
proArray[i].id + "' data-slider-id='SIDproInput" + proArray[i].id
+ "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
document.getElementById("proList").innerHTML += newItem;
proArray[i].slider = new Slider('#proInput' + proArray[i].id, {
formatter: function(value) {
return 'Current value: ' + value;
}
});
} else {
(function(i) {
setTimeout(function() {
var val = proArray[i].slider.getValue();
proArray[i].slider.destroy();
document.getElementById('SIDproInput' + proArray[i].id).remove();
proArray[i].slider = new Slider('#proInput' + proArray[i].id, {
formatter: function (value) {
return 'Current value: ' + value;
}
});
proArray[i].slider.setValue(val);
}, 100);
})(i);
}
}
}
var conArray = [];
function addCon() {
var valCon = document.getElementById("conInput").value.trim();
document.getElementById("conForm").reset();
if (valCon.length == 0) {
return;
}
if (document.getElementById('conInput' + valCon) == null) {
conArray.push({id: valCon, slider: null});
} else {
return;
}
for (var i = 0; i < conArray.length; i++) {
var ele = document.getElementById('conInput' + conArray[i].id);
if (ele == null) {
var newItem = "<li><p>" + conArray[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='conInput" +
conArray[i].id + "' data-slider-id='SIDconInput" + conArray[i].id
+ "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
document.getElementById("conList").innerHTML += newItem;
conArray[i].slider = new Slider('#conInput' + conArray[i].id, {
formatter: function(value) {
return 'Current value: ' + value;
}
});
} else {
(function(i) {
setTimeout(function() {
var valCon = conArray[i].slider.getValue();
conArray[i].slider.destroy();
document.getElementById('SIDconInput' + conArray[i].id).remove();
conArray[i].slider = new Slider('#conInput' + conArray[i].id, {
formatter: function (value) {
return 'Current value: ' + value;
}
});
conArray[i].slider.setValue(valCon);
}, 100);
})(i);
}
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/css/bootstrap-slider.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/bootstrap-slider.min.js"></script>
<div class="col-sm-6">
<h2>Pros</h2>
<p>The Good Stuff</p>
<form id="proForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="proInput" placeholder="Add New Benefit"/>
<div onclick="addPro()" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Benefits</h3>
<ul class="text-left" id="proList">
</ul>
</div> <!-- pros -->
<div class="col-sm-6">
<h2>Cons</h2>
<p>The Bad Stuff</p>
<form id="conForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="conInput" placeholder="Add New Benefit"/>
<div onclick="addCon()" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Costs</h3>
<ul class="text-left" id="conList">
</ul>
</div> <!-- cons -->
Because you have two lists you can use two arrays:
var proArray = [];
var conArray = [];
The inline functions can be changed in order to pass the list prefix as parameter:
newAdd('pro')
newAdd('con')
And so you can adjust the addPro function to these changes.
From comment:
If I type in "#" or "?" as an item in your snippet above it shows the error. Not for you?
In order to solve such an issue you need to escape those chars when creating the slider:
arr[i].slider = new Slider('#' + listIdPrefix + 'Input' +
arr[i].id.replace(/#/g, '\\#').replace(/\?/g, '\\?').....
The snippet:
var proArray = [];
var conArray = [];
function newAdd(listIdPrefix) {
var val = document.getElementById(listIdPrefix + "Input").value.trim();
document.getElementById(listIdPrefix + "Form").reset();
if (val.length == 0) {
return;
}
var arr;
if (document.getElementById(listIdPrefix + 'Input' + val) == null) {
if (listIdPrefix == 'pro') {
proArray.push({id: val, slider: null});
arr = proArray;
} else {
conArray.push({id: val, slider: null});
arr = conArray;
}
} else {
return;
}
for (var i = 0; i < arr.length; i++) {
var ele = document.getElementById(listIdPrefix + 'Input' + arr[i].id);
if (ele == null) {
var newItem = "<li><p>" + arr[i].id + "</p><input class='bootstrap-slider' type='text' value='' id='" + listIdPrefix + "Input" +
arr[i].id + "' data-slider-id='SID" + listIdPrefix + "Input" + arr[i].id
+ "' data-slider-min='0' data-slider-max='10' data-slider-value='5'/></li>";
document.getElementById(listIdPrefix + "List").innerHTML += newItem;
arr[i].slider = new Slider('#' + listIdPrefix + 'Input' + arr[i].id.replace(/#/g, '\\#').replace(/\?/g, '\\?').replace(/\./g, '\\.'), {
formatter: function (value) {
return 'Current value: ' + value;
}
});
} else {
(function (i, arr) {
setTimeout(function () {
var val = arr[i].slider.getValue();
arr[i].slider.destroy();
document.getElementById('SID' + listIdPrefix + 'Input' + arr[i].id).remove();
arr[i].slider = new Slider('#' + listIdPrefix + 'Input' + arr[i].id.replace(/#/g, '\\#').replace(/\?/g, '\\?').replace(/\./g, '\\.'), {
formatter: function (value) {
return 'Current value: ' + value;
}
});
arr[i].slider.setValue(val);
}, 100);
})(i, arr);
}
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/css/bootstrap-slider.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.3/bootstrap-slider.min.js"></script>
<div class="col-sm-6">
<h2>Pros</h2>
<p>The Good Stuff</p>
<form id="proForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="proInput" placeholder="Add New Benefit"/>
<div onclick="newAdd('pro')" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Benefits</h3>
<ul class="text-left" id="proList">
</ul>
</div> <!-- pros -->
<div class="col-sm-6">
<h2>Cons</h2>
<p>The Bad Stuff</p>
<form id="conForm" onkeypress="return event.keyCode != 13;">
<input class="form-control text-left pro-con-input" id="conInput" placeholder="Add New Benefit"/>
<div onclick="newAdd('con')" class="btn pro-con-btn">Add</div>
</form>
<h3 class="text-left">Costs</h3>
<ul class="text-left" id="conList">
</ul>
</div>

How do I see what data AJAX is passing

I want to be able to see if the data that AJAX is passing is the correct data at the function sendToServer.
When the user submits the data that s/he wants, the submit function sends it to next.php. I want to see what next.php is receiving, how do I do this? It should be receiving the same as here:
$("#result").html(JSON.stringify(arr));
So that I can insert the data into a MySQL database.
next.php:
<?php
$data = json_decode(stripslashes($_POST['arr']));
foreach($data as $item){
echo $item;
// insert to db
}
?>
The code that I have so far is in the code snippet:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr);
$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function() {
}
});
}
</script>
</body>
</html>
Your js is sending a post request therefore you should receive the sent data just as you receive a normal html form post.
try var_dump($_POST); to see under what index names are your data then you can use those index names to manipulate your data as you want.

AJAX is not passing data via POST to its intended URL

I want to pass an array through AJAX but I am not getting any feed back on what it is I am sending. I tried to do a var_dump($_POST); on the PHP side (next.php) but nothing is showing up. I'm guessing there is something wrong with my code.
function sendToServer(data) {
$.ajax({
type: "POST",
data: { arr: JSON.stringify(data) },
url: "next.php",
success: function() {}
});
}
next.php:
<?php
var_dump($_POST);
$data = json_decode(stripslashes($_POST['arr']));
foreach ($data as $item) {
echo $item;
// insert to db
}
?>
Full snippet of my code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr);
//$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function() {
}
});
}
</script>
</body>
</html>
The problem is when you try to echo the item. As $item is an object (stdClass), and the echo command expects a string, the echo command fails with "stdClass could not be converted to a string". You can either change to:
echo print_r($item, true);
or:
var_dump($item);

Categories