How to put the ajax response/result into variable php - javascript

Can I put the ajax response into variable? So that I can echo the variable into php?
ajax.php
<script>
function random_no(){
$.ajax({
url: "test.php",
success: function(result){
$("#random_no_container").html(result);//the result was displayed on this div
}
});
}
</script>
On my sample code above, i call the query result from test.php and the result was displayed on the div but i want to put that on the variable and echo the variable. something like the code below
<?php echo $variable;?>
Can this possible? please help me. Thank you so much.

You can't PHP is executed on server and Ajax from the client so you cannot assign PHP variable an ajax response.
Once a PHP is rendered on the client side it is just HTML no PHP code.

function random_no(){
$.ajax({
url: "test.php",
success: function(result){
var result_val=result;
alert(result);
}
});
}

As #dev answered , you need to execute server and client code differently ! I answered here for your need variable only .But in developing website, should not use javascript in php tag <?php ?>
ajax.php
<div id="random_no_container">
<?php
if(isset($_GET['variable'])) {
$variable = $_GET['variable'];
echo $variable;
} else {
echo "<script>sessionStorage.setItem('stopped',0);</script>";
}
?>
</div>
<script>
var stopped = sessionStorage.getItem("stopped");
if(stopped == 0) {
random_no();
}
function random_no(){
$.ajax({
url: "test.php",
success: function(result){
sessionStorage.setItem("stopped",1);
//$("#random_no_container").html(result);//the result was displayed on this div
location.href = "ajax.php?variable="+result;
}
});
}
</script>

Related

Print response from php scrip through ajax call

I want to call a remote php script and that php script will echo any string and then I want to alert that string back to ajax. but when I am alerting that string, I am getting this
Following is my ajax code:
$(document).ready(function(){
var response= $.ajax({
type:"POST",
dataType:'text',
url:"http://mySiteURL.com/evote.php?checkVote="+voterId+"&fingerPrint="+fingerPrint,
async:true,
success:function(result){alert(result);},
error: function(result){alert(result);}
});
});
and following is my php script code
<?php
if(isset($_POST['checkVote'])){
$voterId=$_POST['checkVote'];
$fingerPrint=$_POST['fingerPrint'];
echo "Output from php";
}
?>
before this I searched many questions on stack overflow but problem persisted.
Change the reponse into string : JSON.stringify(result)
var response= $.ajax(
{
type:"POST",
dataType:'html', // <-----
url:"http://mySiteURL.com/evote.php?checkVote="+voterId+"&fingerPrint="+fingerPrint ,
// async:true, // <--- no need
success:function(result){alert(JSON.stringify(result));},
error: function(result){alert(JSON.stringify(result));} })
For the PHP
<?php
if(isset($_GET['checkVote'])){
$voterId=$_GET['checkVote'];
$fingerPrint=$_GET['fingerPrint'];
echo "Output from php";
} else {
echo "No POST";
}
?>

ajax function on change dropdown Value

Hie Everyone!
In PHP page1 my code is here..
<html>
.
...
<select id="customer">...</select>
..
....
<div id="show"></div>
//and Java script function (ajax call)
<script>
$('#customer').change(function(){
var Id = $(this).val();
$.ajax({
type: "GET",
url: "page2.php",
data: "ID="+id,
success: function( data ) {
document.getElementById("show").innerHTML = data;
}
});
});
</script>
</html>
In php page2 as code..
<?php
$ID=$_GET['ID'];
...
//db connection code
..
$sql="select * from Table1 where id='$ID'";
//result code..
//while loop..
//echo something..
// all working without error..
?>
So, when I was trying to do this.It does not showing the success data or may be Ajax function not work.I had check with alert(data);
but does not Alert anything.
please help.
You will give echo infront of the $get_id variable. But you will make sure only one echo in the page2.php page.
<?php
echo $get_id=$_GET['pass_id'];
...
//db connection code
..
$sql="select * from Table1 where id='$get_id'";
//result code..
//while loop..
//echo something..
// all working without error..
?>
Then in page1.php check your ajax response. using alert function.
<script>
$('#customer').change(function(){
var id = $(this).val();
$.ajax({
type: "GET",
url: "page2.php",
data: "pass_id="+id,
success: function( data ) {
alert(data);
document.getElementById("show").innerHTML = data;
}
});
});
</script>

Wordpress ajax call is returning an entire page of html

I have the following piece of javascript which runs in my wordpress site :
var PostData = "Action=refresh-cart";
jQuery.ajax({
dataType: "text",
type: 'POST',
url : location.href,
cache: false,
data : PostData,
complete : function() { },
success: function(data) {
// jQuery("#loading-img").hide();
// jQuery("#join-class-div-3").html(data);
}
});
The php is :
<?php
if(isset($_POST['Action'])) {
$Action = $_POST['Action'];
if($Action == "refresh-cart") {
echo '<div id="stuff"><p> done LOL </p></div>';
}
}
?>
So I expect to be sent back :
<div id="stuff"><p> done LOL </p></div>
But instead I receive an entire page of html!? Why!?
It will return all contents from the page rendered at your url "location.href"
Try adding a exit() to your php code to stop it after your echo.
<?php
if(isset($_POST['Action'])) {
$Action = $_POST['Action'];
if($Action == "refresh-cart") {
echo '<div id="stuff"><p> done LOL </p></div>';
exit;
}
}
?>
<div>html content here will not be displayed</div>
The problem was occuring because location.href was a high level URL, so wordpress was injecting loads of html around the ajax request.
Through altering location.url to a call to plugins.url() which is part of the wordpress PHP API - the AJAX call goes directly to my PHP page and I get the correct response :)

javascript array in php using Ajax on submit not working

I have an array that i pass from javascript to php and in php page i am trying to put it in session to be used in the third page. The code is as below
JavaScript:
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
var jsonString = JSON.stringify(table_row);
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: jsonString},
success: function(data) {
alert("It is Successfull");
}
});
test1.php
<?php
session_start();
$check1 = $_POST['myJSArray'];
$_SESSION['array']= $check1;
echo $check1;
?>
test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
on submit i call the function in javascript and the form takes me to test2.php. It is giving error on test2.php page Notice: Undefined index: array in C:\xampp\htdocs\test\test2.php on line 13
Any suggestions please do let me know.
You don't need to stringify yourself, jquery does it for you, if you stringify it, jQuery will believe you want a string instead
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: table_row},
success: function(data) {
alert("It is Successfull");
}
});
However, on the php side, you still need to decode it as it is always a string when you get it from $_POST. use json_decode to do it.
$check1 = json_decode($_POST['myJSArray']);
look at your test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
if it's only the code in the file then the error you got C:\xampp\htdocs\test\test2.php on line 13 is mindless, because there is not line 13,
but if you have something about the code you show us, may there be something echoed before?
because session has to be started before any output,
otherwise I've tested whole script and works fine...
To check if session really started (otherwise $_SESSION will not work), try this:
if(session_id())
{
echo "Good, started";
}
else
{
echo "Magic! strangeness";
}
if problem not found in test2.php you can check test1.php echo $_SESSION['array'] after saving it, and in your javascript callback function alert data param itself,
I'm sure you can catch the problem by this way.
i got it to work, the code is below
Javascript file: in page index.php
Either you can call this function and pass parameter or use code directly
var table_row = []; //globally declared array
var table_row[0]=["123","123","123"];
var table_row[1]=["124","124","124"];
var table_row[2]=["125","125","125"];
function ajaxCode(){
var jsonArray = JSON.stringify(table_row)
$.ajax
({
url: "test1.php",
type: "POST",
dataType: 'json',
data: {source1 : jsonArray},
cache: false,
success: function (data)
{
alert("it is successfull")
}
});
}
Page: test1.php
session_start();
unset($_SESSION['array']);
$check1 = $_POST['source1'];
$_SESSION['array']= $check1;
echo json_encode(check1);
Page: test2.php //final page where i wanted value from session
if(session_id())
{
echo "Session started<br>";
$test = $_SESSION['array'];
echo "The session is".$test;
}
else
{
echo "Did not get session";
}
?>
In index page i have a form that is submitted and on submission it calls the ajax function.
Thank you for the help, really appreciate it.

JQuery, Ajax submit with Mysqli validation

How can I submit a form dynamically where I run mysqli to check if an email exists. If it exists, echo an error ALL DYNAMICALLY.
I would like to run a jquery ajax submit but echo out php errors. I can submit but nothing will echo.
function DYNAMIC_CHECK(X)
{
$.ajax(
{
url:'<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>',
type:'POST',
data:X,
});
}
X is the formdata. It all works, but the PHP echo will not show up nor will any vars that are created and echoed out throughout the page as errors.
if(isset($_POST['REGISTER']))
{
$COUNT = mysqli_num_rows(mysqli_query($CON, "SELECT * FROM USER WHERE EMAIL='$EMAIL'"));
if($COUNT == 1) { $EMAIL_ERROR='EMAIL ALREADY EXISTS'; }
}
echo $EMAIL_ERROR;
Is this possible to dynamically show $EMAIL_ERROR?
You can use the shorthand function jQuery.post() which sends the serialized data of the form and returns the result into a variable.
$.post( "test.php", $( this ).serialize(), function ( data ) {
...what to do with data (returns the result of test.php)...
});
You can modify your ajax function to display result from the request.
$.ajax(
{
url:'<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>',
type:'POST',
data:X,
success: function(data) {
alert(data);
}
});
The echo of the request will be returned in the data variable in the success: function. Use the alert(data) to see what info is returned from the request.

Categories

Resources