Simple Ajax Post to PHP echo - php

I have the following code on product.php .. can't seem to echo post variable from ajax post. Alert displays fine. Please help
JQUERY
document.getElementById("LBTest").onchange = function(){
var lbtest = $('#LBTest :selected').val();
$.ajax({
type: "POST",
url: "product.php",
data: {test: lbtest},
success: function()
{
alert("Successful");
}
});
}
PHP
if(isset($_POST['test'])){
$data = $_POST['test'];
echo $data;
}

You need to do something with the data you receive from the ajax call. For example, to put the result into a <div> called resultDiv:
success: function(data)
{
$('#resultDiv').html(data);
alert("Successful");
}

$.ajax({
type: "POST",
url: "product.php",
data: {test: lbtest},
success: function(data)
{
alert("Successful");
}
});
You need to add the data to the success function that is called. You can do this locally or reference another function meant to handle responses coming back from the server.
success: function(data)
{
console.log(data);
alert(data + " was returned from the server");
}
It is a good idea on the server side to json_encode the objects that are being returned and using error codes that can be more appropriately handled on the client.
handleResponse(data) {
var data = $.parseJSON(data);
if(data.code >= 200 || data.code < 300) {
// modify the dom, add data to a model, take over the world with your web app.
}
}

Related

How delay ajax call by few seconds

I'm not sure this is the best way to send 2 ajax togheter for facebook api.
But it works, the problem is that sometimes i get the second ajax (result_flow.php) before the first (result.php)
Will be helpful delay second ajax (url:result_flow.php) for 3 seconds or change this code in someway to give a order.
I tried setTimeout but didn't work.
$('#sub').click(function () {
var data = $("input#dataInput").val();
console.log(data);
var total = $("input#totalInput").val();
var subscriber_id = $("input#subscriber_id").val();
var res_name = $("input#res_name").val();
var dataString = 'data='+ data + '&total=' + total + '&subscriber_id=' + subscriber_id+ '&res_name=' + res_name;
console.log(dataString);
$.ajax({
type: "POST",
url: "result.php",
data: dataString,
success: function(data) {
console.log(data);
if(data==='success'){
//localStorage.clear();
MessengerExtensions.requestCloseBrowser(function success() {
console.log("Webview closing");
}, function error(err) {
console.log(err);
});
}
}
});
$.ajax({
type: "POST",
url: "result_flow.php",
data: dataString,
success: function(data) {
setTimeout(function(){
console.log(data);
if(data==='success'){
}
},3000);
}
});
}
I would suggest to use async/await nowadays, it is quite easy to use AJAX calls sequencially:
$('#sub').click(async () => {
...
try {
let data = await $.post({
url: "result.php",
data: dataString
});
if (data === 'success') {
...
}
data = await $.post({
url: "result_flow.php",
data: dataString
});
if (data === 'success') {
...
}
} catch (err) {
console.log(err);
}
});
Not tested, as i donĀ“t work with jQuery - but it should give you the idea. Since $.ajax/$.post supports Promises, it should work with async/await. Be aware that you may need to transpile your code with Babel for older browsers, but i suggest using Babel anyway.
If you want to use both AJAX calls in parallel, use Promise.all (because they do not depend on each other) - the results will be in order, so you can make sure the callback code is called in order.
First, setTimeout() is not working because you put it inside the callback, which means it will be executed when the request is already done. Anyway that's not a proper way to handle such a task, you should put the second request inside the first's callback, so that it will be executed as the first one finishes.
The code looks like this:
$('#sub').click(function() {
var data = $("input#dataInput").val();
console.log(data);
var total = $("input#totalInput").val();
var subscriber_id = $("input#subscriber_id").val();
var res_name = $("input#res_name").val();
var dataString = 'data=' + data + '&total=' + total + '&subscriber_id=' + subscriber_id + '&res_name=' + res_name;
console.log(dataString);
$.ajax({
type: "POST",
url: "result.php",
data: dataString,
success: function(data) {
console.log(data);
if (data === 'success') {
//localStorage.clear();
MessengerExtensions.requestCloseBrowser(function success() {
console.log("Webview closing");
}, function error(err) {
console.log(err);
});
$.ajax({
type: "POST",
url: "result_flow.php",
data: dataString,
success: function(data) {
console.log(data);
}
});
}
}
});
}
Note that in my code the second request is sent just if the first one is successful because it's placed within the if (data === 'success') {...} statement.
You should call them in chain. Success... then... using promise is the best way.
Never trust the order you receive if is not explicitly written by you.
JQuery Ajax
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete()
callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(),
and jqXHR.always() instead.
You can do something like this:
// First Ajax call
$.ajax({
// Do the request
// Remove success to use new promise
})
.done(function( data ) {
// Add the success here
// Add the Second Ajax call here or create a function to call it, whatever you want
});

Ajax post not appending data to URL

I am trying to get my search bar working, however I am having issues with an ajax post.
For whatever reason, none of the data is being appended to the URL. I have tried various things with no success. I am attempting to send the data to the same page (index.php).
Here is my jquery:
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ searchTerm: text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: postData,
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
});
And here is the php which I have with index.php:
<?php
require('course.php');
if(isset($_POST['searchTerm'])) {
echo $_POST['searchTerm'];
}
?>
No matter what I try, I am unable to get anything to post. I have checked the network tab in chrome, and I'm not seeing anything that indicates it's working correctly.
Any ideas?
EDIT:
I've changed my code to this, and it seems I'm getting closer:
$(document).on({
click: function () {
$("TABLE").remove()
var text = $('#searchBar').val();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'text',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
And:
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo $_GET['searchTerm'];
}
?>
Now I am getting ?searchTerm=theTextIEnter as expected, however it's still not being echoed in index.php.
Do not use JSON.stringify() to convert object to string. data passed to $.ajax must be an object and not JSON.
For whatever reason, none of the data is being appended to the URL.
You are making a POST request. POST data is sent in the request body, not in the query string component of the URL.
If you change it to a GET request (and inspect it in the correct place, i.e. the Network tab of your browser's developer tools and not the address bar for the browser) then you would see the data in the query string.
This will work for you use data: { postData } on place of data:postData and you will receive your data in $_POST['postData']
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ 'searchTerm' : text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { postData },
success: function(data) {
alert(data.searchTerm);
}
});
}
}, "#searchButton");
});
In index.php
<?php
if(isset($_POST['postData'])) {
echo $_POST['postData'];
die;
}
?>
If you want to send data via the URL you have to use a GET request. To do this, change the type of the request to GET and give the object directly to the data parameter in your jQuery, and use $_GET instead of $_POST in your PHP.
Finally note that you're not returning JSON - you're returning text. If you want to return JSON, use json_encode and get the value in the parameter of the success handler function.
Try this:
$(document).on({
click: function () {
$('table').remove();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'json',
data: { searchTerm: $('#searchBar').val() },
success: function(response) {
console.log(response.searchTerm);
}
});
}
}, "#searchButton");
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo json_encode(array('searchTerm' => $_GET['searchTerm']));
}
?>
Remove dataType: 'json', from your AJAX. That is all.
Your response type is not JSON, yet by setting dataType: 'json' you're implying that it is. So when no JSON is detected in the response, nothing gets sent back to the method handler. By removing dataType it allows the API to make an educated decision on what the response type is going to be, based on the data you're returning in the response. Otherwise, you can set dataType to 'text' or 'html' and it will work.
From the manual:
dataType: The type of data that you're expecting back from the server.
This is NOT the type of data you're sending/posting, it's what you're expecting back. And in your index.php file you're not sending back any JSON. This is why the success() method is not satisfying. Always set the dataType to the type of data you're expecting back in the response.
With POST Request:
Please comment below line in your code:
//var postData = JSON.stringify({ searchTerm: text });
And use below ajax code to get the post-data:
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
With GET Request:
You can convert your data to query string parameters and pass them along to the server that way.
$.ajax({
type: 'GET',
url: 'index.php?searchTerm='+text,
dataType: 'json',
success: function(response) {
alert(response);
}
});
In response, You can get the data with alert, so you may get idea about the same.

Trying to pass a variable from JQuery to PHP

So, I've looked at several questions and answers here, and they all seem to point in the same direction, but I just can't make it work. . .
I want to read a variable from a file in JQuery, add one to it, then pass it to php to write the new value to the file. I have separate HTML/JavaScript and PHP files.
In the Javascript, I have:
$(document).ready(function(){
var data
$.get('scoredir/data.txt', function(data) {
count = parseInt(data);
count = count +1;
});
$.ajax({
type: 'POST',
url: 'savedata.php',
data: { 'numberOfPlays' : count },
success: function (response) {
//alert (response);
}
});
});
In the php file (savedata.php), I have:
<?php
$data = $_POST['numberOfPlays'];
file_put_contents("scoredir/data.txt", $data);
?>
It seems like the php file just isn't getting the variable. Anyone know what's wrong?
You're having typical asynchronous AJAX issues. You're $.ajax command is running before your $.get command has completed it's request.
For a quick-fix, try something like this instead:
$(document).ready(function(){
var data;
$.get('scoredir/data.txt', function(data) {
count = parseInt(data);
count = count +1;
$.ajax({
type: 'POST',
url: 'savedata.php',
data: { 'numberOfPlays' : count },
success: function (response) {
//alert (response);
}
});
});
});
Also, look into deferred objects and promises.
I think behavior of ajax is async so one is getting completed and other is not or may be vice-versa, so you can do this:
$(document).ready(function(){
$.get('scoredir/data.txt', function(data) {
var count = parseInt(data); // you can declare your variable here
count = count + 1;
$.ajax({
type: 'POST',
url: 'savedata.php',
data: { 'numberOfPlays' : count },
success: function (response) {
//alert (response);
}
});
});
});
One thing I noticed is, $.get is just a shorthand, it is already an asynchronous ajax call. Therefore, in order to work with the result (e.g. count) of that request, your second ajax call needs to go inside the callback of $.get like so:
$(document).ready(function(){
var count;
$.get('http://echo.jsontest.com/key/22', function(data) {
count = parseInt(data.key);
count = count +1;
$.ajax({
type: 'POST',
url: 'savedata.php',
data: { 'numberOfPlays' : count },
success: function (response) {
//alert (response);
}
});
});
});
Demo: http://jsfiddle.net/3Pykx/

Getting JSON in PHP from jQuery .ajax()

I'm having trouble getting JSON data sent from JavaScript to PHP. Here is my Javascript:
var noteData = {
nData: {
"postID": $postID,
"commentPar": $commentPar,
"commentValue": $commentValue
}
}
var sendData = JSON.stringify(noteData);
$.ajax({
type: "POST",
url: templateUrl+"/addnote.php",
data: sendData,
dataType : 'json',
success: function(data) {
alert(data);
console.log(sendData);
},
error: function(e) {
console.log(e.message);
console.log(noteData);
console.log(sendData);
alert("error");
}
});
Here is how I just test if the data is even being passed to PHP, it always returns back null.
<?php
$nData = json_decode($_POST['nData']);
echo json_encode($nData);
?>
What am I doing wrong?
You are sending the data as raw JSON to PHP, not as POST parameter.
There are two alternatives. The first one leaves your PHP intact:
var noteData = {
nData: {
"postID": $postID,
"commentPar": $commentPar,
"commentValue": $commentValue
}
}
var sendData = JSON.stringify(noteData);
$.ajax({
type: "POST",
url: templateUrl+"/addnote.php",
data: {
nData: sendData
},
dataType : 'json',
success: function(data) {
alert(data);
console.log(sendData);
},
error: function(e) {
console.log(e.message);
console.log(noteData);
console.log(sendData);
alert("error");
}
});
The second one modifies the PHP side alone. You need to read the input stream directly to obtain the raw data.
<?php
$nData = json_decode(file_get_contents('php://input'));
echo json_encode($nData);
This one might be slightly different depending on the server configuration. See the documentation on the input stream wrappers.
Tell your post request that you are sending json object
contentType: "application/json"

Jquery AJAX response not working

For some reason this jQuery function is not working properly. Here's my code... the response div is not updating with my response.
WHEN AJAX FUNCTION IS CALLED
if ($action == 'sort') {
echo 'getting a response';
return 0;
}
JQuery FUNCTION
function sort() {
$.ajax({
type: "POST",
url: "contributor_panel.php?action=sort",
data:"sort_by=" + document.getElementById("sort_by").value +
"&view_batch=" + document.getElementById("view_batch").value,
success: function(html){
$("#ajaxPhotographSortResponse").html(html);
}
});
}
DIV TO REPLACE
<div id="ajaxPhotographSortResponse"></div>
Move the action=sort into the data property of the $.ajax function. You're making a POST request, but appending data onto your query string like a GET request. Data only appends to the query string if it's a GET request.
Example:
$.ajax({
type: "POST",
url: "contributor_panel.php",
data: {action:'sort', sort_by: $('#sort_by').val(), view_batch: $('#view_batch').val()},
success: function(html){
$("#ajaxPhotographSortResponse").html(html);
}
});
http://api.jquery.com/jQuery.ajax/
Instead of concatenating the arguments you are passing to your server side script I would recommend you using the following syntax. Also if you already use jQuery you no longer need the document.getElementById function:
$.ajax({
type: "POST",
url: "contributor_panel.php?action=sort",
data: { sort_by: $("#sort_by").val(), view_batch: $("#view_batch").val() },
success: function(html){
$("#ajaxPhotographSortResponse").html(html);
}
});
or even shorter using the .load() function:
$('#ajaxPhotographSortResponse').load('contributor_panel.php?action=sort',
{ sort_by: $("#sort_by").val(), view_batch: $("#view_batch").val() });

Categories