How do I see what data AJAX is passing - javascript

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.

Related

Show value of select option in html

I have a list with the tag, the item values ​​are obtained through an online spreadsheet. When selecting an option, the value does not appear in the html in real time. can anybody help me? I'm trying to solve it, but I can't find the error.
CODEPEN LINK EXAMPLE
$(document).ready(function() {
var sheetURL =
"https://spreadsheets.google.com/feeds/list/1J0qyxUCCkvcFGZ6EIy9nDOgEuTlpI5ICVG3ZsBd_H-I/1/public/values?alt=json";
$.getJSON(sheetURL, function(data) {
var entryData = data.feed.entry;
console.log(data);
jQuery.each(entryData, function() {
$("#divTax").append(
'<option hidden="hidden" selected="selected" value="0">CHOISE</option><option value="' + this.gsx$values.$t + '">' + this.gsx$names.$t + ' $' + this.gsx$values.$t + '</option>'
);
});
});
});
var totalWithTax = $('#divTax :selected').val();
$('.total').html(totalWithTax);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<select style="width: 80%;" id="divTax"></select>
<br>
Total:<div class="total"></div>
You to put the code that displays the selection in an event listener.
$(document).ready(function() {
var sheetURL =
"https://spreadsheets.google.com/feeds/list/1J0qyxUCCkvcFGZ6EIy9nDOgEuTlpI5ICVG3ZsBd_H-I/1/public/values?alt=json";
$.getJSON(sheetURL, function(data) {
var entryData = data.feed.entry;
jQuery.each(entryData, function() {
$("#divTax").append(
'<option hidden="hidden" selected="selected" value="0">CHOISE</option><option value="' + this.gsx$values.$t + '">' + this.gsx$names.$t + ' $' + this.gsx$values.$t + '</option>'
);
});
});
$("#divTax").change(function() {
var totalWithTax = $(this).val();
$('.total').text(totalWithTax);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<select style="width: 80%;" id="divTax"></select>
<br> Total:
<div class="total"></div>

How to get data from dynamic elements that added to the html page?

In below I write form part of my html page.
<form method="post" enctype="multipart/form-data">
<div>
<label>Brand Name:</label>
<input type="text" asp-for="#Model.Name">
</div>
<div id="divCategory">
</div>
<button type="button" id="btnAddCategory">Add Category</button>
<button>Create new Brand</button>
</form>
and I have two js and jquery function that add a select to divCategory. Whith this select I can add some categories.
function countMyCategories() {
if (typeof countMyCategories.counter == 'undefined') {
countMyCategories.counter = -1;
}
return ++countMyCategories.counter;
}
$(document).ready(function () {
$('#btnAddCategory').on('click', function () {
var catId = countMyCategories();
$('#divCategory').append(
'<select id="selectCategory' + catId + '" asp
for="##Model.CatBrands[' + catId + '].CatId" class="mt-3 form-control
form-control-sm">' +
'<option>---Select---</option>' +
'</select>'
);
$.ajax('/API/GetCats')
.done(function (categories) {
for (var i = 0; i < categories.length; i++) {
$('#selectCategory' + catId).append(
'<option value="' + categories[i].id + '">' +
categories[i].name + '</option>'
)
}
});
});
});
When I click the "Add Category" button one select tag added to the div by id="divCategory", but problem is that when I click "Create New Brand" button, I don't get data from these selects in server, actually CatBrands is null but I got name. I get something like that:
{name = "LG", catBrands = null}
CatBrands is null because you can't dynamically add data from the server in this manner. When the page renders, you need everything you want rendered by asp in the html.
<form method="post" enctype="multipart/form-data">
<div>
<label>Brand Name:</label>
<input type="text" asp-for="#Model.Name">
</div>
<div id="divCategory">
<select id="selectCategory asp-code-goes-here>
<option>---Select---</option>
</select>
</div>
<button type="button" id="btnAddCategory">Add Category</button>
<button>Create new Brand</button>
</form>
I've made a terible mistake. I should change my function like this
$(document).ready(function () {
$('#btnAddCategory').on('click', function () {
var catId = countMyCategories();
$('#divCategory').append(
'<select id="selectCategory' + catId + '"
name = "CatBrands[' + catId + '].CatId" class="mt-3 form-control
form-control-sm">' +
'<option>---Select---</option>' +
'</select>'
);
$.ajax('/API/GetCats')
.done(function (categories) {
for (var i = 0; i < categories.length; i++) {
$('#selectCategory' + catId).append(
'<option value="' + categories[i].id + '">' +
categories[i].name + '</option>'
)
}
});
});
});

jQuery pass object in inline onclick

How can I pass object to inline onclick event. When I try following code I either get undefined or [object object].
also how can I bind click event to h to avoid inline code.
this.get = function(o) {
console.log(o, o.foo);
}
this.somefunction = function(robj) {
for (var i = 0, i <= robj.length; i++) {
var fname = robj[i]['filename']
h += '<div class="checkbox checkbox-success" onclick="get(\'' + robj + '\')">' +
'<input id="' + fname + '" type="checkbox" class="styled"> ' +
'<label for="' + fname + '"><a data-fancybox-next class="button-next" href="#">' + fname + '</a></label>' +
'</div>';
}
}
A few problems I saw with your code,
your loop should be i < robj.length and has a syntax error , should be ;
h was not defined but now not used anymore
The array passed into get() cannot be accessed by using o.foo
Side note: take a look at ES6 template literals to help clean up some of the quoting action you are currently doing, for example id="' + fname + '" can look like id="${fname}"
Here is a full working example with the fixes above on how you can add a listener to your div (by creating DOM element) and with the object as a parameter.
this.get = function(o) {
console.log(o);
console.log(o.foo);
}
this.somefunction = function(robj) {
for (let i = 0; i < robj.length; i++) {
var fname = robj[i]['filename']
var myDiv = document.createElement("div");
myDiv.className = "checkbox checkbox-success";
myDiv.onclick = function(){get(robj[i])};
myDiv.innerHTML =
'<input id="' + fname + '" type="checkbox" class="styled"> ' +
'<label for="' + fname + '"><a data-fancybox-next class="button-next" href="#">' + fname + '</a></label>';
document.getElementById("container").appendChild(myDiv);
}
}
var robj = [{filename: "myFilename", foo: "myFoo"}]
somefunction(robj);
<div id="container"></div>
here is an example of dynamically written onclick . simply keep the function outside of doucment.ready
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function changePath(distinct_inputs)
{
console.log(distinct_inputs);
}
$(document).ready(function(){
var distinct_inputs = 0;
$('.icon1').click( function(){
distinct_inputs = distinct_inputs + 1 ;
$('#insert-file').append('<ul class="ul list-inline"><li style="width:90%"><input onchange="changePath('+distinct_inputs+')" type="file" class="base'+distinct_inputs+' form-control form-input form-style-base"><input type="text" class="fake'+distinct_inputs+' form-control form-input form-style-fake" readonly placeholder="choose your file"><span class="glyphicon glyphicon-open input-place"></span></li><li class="icon fa fa-minus"></li></ul>');
});
});
</script>
</head>
<body>
<div id="insert-file" ></div>
<button type="button" class="icon1">CLick here</button>
</body>
</html>

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);

Display tweets from twitter API from user input

I'm a beginner at javascript/jquery and completely new to API's and I'm wondering if anyone could help me with something
What I'm trying to achieve is to have a user enter a keyword/phrase into a textbox, they click search and the page returns a list of people who have that word in their tweet.
I have so far been able to display results from a hard-coded keyword (which I got from a website) but when trying to change it I am getting nothing back.
Here is the working one with hard code
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('http://search.twitter.com/search.json?q=earthquake&lang=en&callback=?', function (data) {
var data = data.results;
var html = "<ul>";
for (var i = 0; i < data.length; i++) {
html += "<li><a href='http://twitter.com/" + data[i].from_user + "'>#"
+ data[i].from_user + "</a>: " + data[i].text + "</li>";
}
html += "</ul>"
$('.content').html(html);
});
});
</script>
<h2>Twitter</h2>
<div class="content">
</div>
And here is the code I'm working on now
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
var button= document.getElementById('searchTwitter');
button.onclick= function(){
var text = document.getElementById('search').value;
}
var baseUrl = "http://search.twitter.com/search";
var query = document.getElementById('<%=searchTwitter.ClientID%>').value;
$(document).ready(function () {
$.ajax({
url: baseUrl + '&text' + '&lang=en&callback=?',
dataType: "jsonp",
success: showResults
});
});
function showResults(data) {
var data = data.results;
var html = "<ul>";
for (var i = 0; i < data.length; i++) {
html += "<li><a href='http://twitter.com/" + data[i].from_user + "'>#"
+ data[i].from_user + "</a>: " + data[i].text + "</li>";
}
html += "</ul>"
$('.content').html(html);
}
</script>
<asp:TextBox ID="search" runat="server"></asp:TextBox>
<asp:Button ID="searchTwitter" runat="server" Text="Button" />
Any help would be much appreciated as I have been trying to find a way to do this for days.
thanks a lot
Here's a working example of what you are describing: http://jsfiddle.net/ZEjey/. You should be able to adapt it to your ASP code.
Relevant code below.
JQuery
$("#SearchButton").click(function() {
$.getJSON('http://search.twitter.com/search.json?q=' + $('#TextSearch').val() + '&lang=en&callback=?', function (data) {
var data = data.results;
var html = "<ul>";
for (var i = 0; i < data.length; i++) {
html += "<li><a href='http://twitter.com/" + data[i].from_user + "'>#"
+ data[i].from_user + "</a>: " + data[i].text + "</li>";
}
html += "</ul>"
$('.content').html(html);
});
});
HTML
<h2>Twitter</h2>
Search for: <input id="TextSearch" type="text" /> <input type="button" id="SearchButton" value="Go" />
<div class="content"></div>​
​---
EDIT 0
Okay, the code below works. The <asp:Button automatically causes a postback so you don't see anything ever get loaded. You either need to use <input type="button" ... instead or stop the normal events from occurring using event.preventDefault(); as I did below.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Twitter</h2>
<asp:TextBox id="TextSearch" runat ="server"/>
<asp:Button id="SearchButton" runat="server" Text="Search"/>
<div class="content"></div>​
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" ></script>
<script>
$(document).ready(function () {
$("#SearchButton").click(function () {
event.preventDefault(); // ADD THIS LINE TO YOUR CODE
$('.content').html("<em>loading...<em>");
$.getJSON('http://search.twitter.com/search.json?q=' + $('#TextSearch').val() + '&lang=en&callback=?', function (data) {
var data = data.results;
var html = "<ul>";
for (var i = 0; i < data.length; i++) {
html += "<li><a href='http://twitter.com/" + data[i].from_user + "'>#" + data[i].from_user + "</a>: " + data[i].text + "</li>";
}
html += "</ul>";
$('.content').html(html);
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
});
});
</script>
</form>
</body>
</html>
It looks like you're making an ajax request on document ready, rather than when the button is clicked. I also don't see where you're adding the value from the text box to the query. Here's how you could change your code:
//this code will run when the page loads and set up the button so the
//onclick event executes your function
$(document).ready(function () {
var button = document.getElementById('<%=searchTwitter.ClientID%>');
//you need to make the ajax request in this function, because this
//is fired when the search button is clicked
button.onclick = function() {
var text = document.getElementById('search').value;
var baseUrl = "http://search.twitter.com/search.json";
var query = document.getElementById('<%=search.ClientID%>').value;
$.ajax({
//you're building the request url here, with the text from the
//box as the q parameter
url: baseUrl + '?q=' + query + '&lang=en&callback=?',
dataType: "jsonp",
success: showResults
});
};
});
//this function can be defined outside ready()
function showResults(data) {
var data = data.results;
var html = "<ul>";
for (var i = 0; i < data.length; i++) {
html += "<li><a href='http://twitter.com/" + data[i].from_user + "'>#"
+ data[i].from_user + "</a>: " + data[i].text + "</li>";
}
html += "</ul>";
//I'm assuming you have a div with a content class on your page
$('.content').html(html);
}
You might also want to try out the Chrome developer tools (or Firebug in Firefox). You can set breakpoints and see what's happening at each step. You can also see what requests have been sent and the data returned. That will help give you a better handle on what's going on.

Categories