Get data from php script in javascript - php

I try to receive a PHP response in my JavaScript.
My PHP looks like this:
some code
if(...) echo "1";
else echo "2";
JavaScript:
function GetChoice() {
var returned="";
$.ajax({
async: false,
cache: false,
url: "http://mydomain.com/script.php",
type: "POST",
dataType:"text",
success: function(data) {
returned = data;
}
});
return returned;
}
var r = GetChoice();
alert(r);
But GetChoice() returns nothing. What's wrong?
UPD: It works if javascript and php script are on the same server. My scripts in different domains.

Try this :
temp1.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function GetChoice() {
var returned = "";
$.ajax({
async: false,
cache: false,
type: "POST",
url: "http://localhost/temp2.php",
data: { name: "John"}
}).done(function( msg ) {
returned = msg;
});
return returned;
}
var r = GetChoice();
alert(r);
</script>
temp2.php
<?php
echo $_REQUEST["name"];
?>
its working....!

try this:
function GetChoice() {
var returned = "";
$.ajax({
async:false,
cache:false,
url:"http://mydomain.com/script.php",
type:"POST",
dataType:"text",
success:function (data) {
alert(data);
}
});
}

The problem is, in your example, $.ajax returns immediately and the next statement, return result;, is executed before the function you passed as success callback was even called.
Here is explanation.
How do I return the response from an asynchronous call?
Luck,

GetChoice() will return nothing before the callback in success runs.
The callback, which is the function you define as the success paramater will not fire until the data have been requested from the server.
This is asyncronous (the A in AJAX) so the rest of the code with continue causing the GetChoice() function to return before the callback has been run

this is the script
<script type="text/javascript">
$.ajax({
async:false,
cache:false,
url:"http://path.com/to/file",
type:"POST",
dataType: "html",
data: 'data',
success: function(data){
alert(data);
}
});
and in your PHP file write this code
<?php
function test()
{
$str = 'This is php file';
return $str;
}
echo test();
?>
Make sure the path to the php file is correct AND add the script in another PHP file. Basically you need 2 files. Just tested this in my editor and works ..

function GetChoice() {
var returned="";
$.ajax({
url: "../script.php",
type: "POST",
success: function(data) {
returned = data;
}
});
return returned;
}
var r = GetChoice();
alert(r);

Related

Ajax post not sending data to PHP file

So I am working on a project in which I have to pass some form data to a database without reloading the page using Ajax. But the $_POST variable in the PHP file is always empty. I do know that I am actually getting the data from the form since I can print and it looks okay in the javascript code:
$(document).ready(function () {
$('form').on('submit', function (event) {
// prevent page from refreshing
event.preventDefault();
$.ajax({
url: 'post.php',
type: 'POST',
data: {name: 'tony'},
dataType: 'json',
success: function (response) {
$('#message').html(response);
}
});
//return false;
});
});
And this is the php code:
<?php
//var_dump($_POST);
if (isset($_POST['name'])) {
$name = $_POST['name'];
echo $name;
} else {
echo "error";
}
?>
Use this code instead, you won't need to manually define the parameters to be sent because it will be automatically set by FormData():
$('#form').submit(function(event) {
event.preventDefault();
var data = new FormData(this);
$.ajax({
url: "post.php",
type: "POST",
data: data,
contentType: false,
processData: false,
success: function(result) {
console.log(result);
}
});
});
So, turns out I am just stupid.. It was actually working properly after all but I was checking if it works the wrong way. I was actually navigating to the php file by entering the url expecting to see my data printed on the php page. Finally, I checked the response of the POST request and it was working just fine.Thank you for your answers and I apologize for wasting your time.
try this,
$('form').on('submit', function (event) {
// prevent page from refreshing
event.preventDefault();
$.ajax({
url: 'post.php',
method: 'POST',
data: {name: 'tony'},
success: function (response) {
$('#message').html(response);
}
});
});

Simple Ajax Post to PHP echo

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.
}
}

jquery json request failed

I'm trying to make a json call with jquery but noting happened. My code:
javascript:
<script type="text/javascript" charset="utf-8">
$(document).ready(function()
{
$("#TwImport").click(function()
{
$.ajax({
type: "POST",
url: "https://<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
dataType: 'json',
success: function (data)
{
alert(data.percentage);
}
});
});
});
</script>
PHP
$output = array(
'percentage' => "50"
);
echo json_encode($output);
Any suggestions?
The code looks fine to me,
EDITED
Also try removing the protocol and use url: "//<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
$("#TwImport").click(function()
{
$.ajax({
type: "POST",
url: "https://<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
dataType: 'json',
success: function (data)
{
alert(data.percentage);
},
error: function (jqXHR,textStatus,errorThrown)
{
//Check for any error here
}
});
});
if you add and error callback to the ajax call you should get some error printouts to let you know what is going on
$.ajax({
type: "POST",
url: "https://<?php echo $_conf['siteurl']; ?>/files/connect/import/customers.php",
dataType: 'json',
success: function (data)
{
alert(data.percentage);
},
error : function (e1, e2, e3) {
console.log(e1);
console.log(e2);
console.log(e3);
}
});
EDIT:
i just had a thought, if i remember correctly jquery ajax doesnt like using full url's if possible try using a relative path

Passing a variable from JavaScript to PHP through AJAX

I'm trying to pass the a variable from JavaScript to PHP using AJAX, but I'm unable to do so. Whenever I try to var_dump($_POST['winner_id']) it returns NULL. I've tried to check the AJAX call with Developer Tools in Chrome and it showed winner_id:0 - which is right.
Here is my code:
JavaScript
function ajaxCall() {
alert("To AJAX: the winnerid is: "+winner_id);
$.ajax
( {
type: "POST",
url: "ajax.php",
data: {winner_id : winner_id},
success: function(response)
{ alert("The winner was passed!")}
}
);
};
ajaxCall();
PHP Code
<?php
session_start();
if(isset($_POST['winner_id']))
{
$winner_id = $_POST['winner_id']."";
var_dump($winner_id);
}
var_dump($_POST['winner_id']);
?>
If I do a var_dump($_POST) in the beginning of the PHP script then it gives me array(0) { }
I'm new to web development and have been trying to figure this out for hours now. Any hints would be much appreciated. Thanks!
Where are you intializing the winner_id.Either you have to pas it as an argument or intitialize it as aglobal variable.
function ajaxCall(winner_id) {
alert("To AJAX: the winnerid is: "+winner_id);
$.ajax
({
type: "POST",
url: "ajax.php",
data: {"winner_id" : winner_id},
success: function(response)
{
alert("The winner was passed!");
}
});
};
ajaxCall(winner_id);
Where did you initiate value to winner_id? like
function ajaxCall() {
var winner_id = '123';
...
or if you initiated winner_id before calling ajaxCall() ,you should call ajaxCall() with parameters like ajaxCall($winnerid), which $winnerid is from your PHP
and then
function ajaxCall(winner_id) {
...
i guess you have to convert your winner_id to a string because php read zero (0) as null
function ajaxCall() {
alert("To AJAX: the winnerid is: "+winner_id);
$.ajax
( {
type: "POST",
url: "ajax.php",
data: {winner_id : winner_id.toString()},
success: function(response)
{ alert("The winner was passed!")},
dataType: "json"
}
);
};
ajaxCall();

Pass Value from jQuery AJAX to PHP

Let's say I have this script for example:
<script type="text/javascript">
function getdata() {
var referenceNumber = $("#reference_number").val();
$.ajax({
url: 'getlistofsomething.php',
type: 'POST',
dataType: 'json',
data: 'referenceNumber=' + referenceNumber,
success: function (output_string) {
$("#name").val(output_string[0]);
$("#address").val(output_string[1]);
}
});
}
</script>
Is there a way I can pass the value in $("#address").val(output_string[1]); into the PHP file this script above is in?
Thanks.
The easiest way is just to send it to the server using GET. Only do this if the data isn't very sensitive...
<script type="text/javascript">
function getdata()
{
var referenceNumber = $("#reference_number").val();
$.ajax({
url: 'getlistofsomething.php?address=' + $("#address").val(output_string[1]),
type: 'POST',
dataType: 'json',
data: 'referenceNumber='+referenceNumber,
success: function(output_string)
{
$("#name").val(output_string[0]);
$("#address").val(output_string[1]);
}
});
}
</script>
This can then be accessed in your php script with:
$address = $_GET['address'];

Categories