How do I get response data from php with ajax (one file)? - php

I'am trying to get php response data with ajax. I want to check if there is a specific string in testing.txt from my input and if the string is found, php should echo "1" but no matter what I try AJAX always says the output isn't 1
This is my code:
<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
if (in_array($_POST['table'], $file)) {
echo "1";
} else {
echo "0";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text);
};
function post(vally) {
var table = vally;
$.post('test.php', {table:table}, function(data) {
})
.done(function (data) {
if (data == 1) {
console.log("the output is 1")
} else {
console.log("the output isn't 1")
}
});
console.log('posted');
}
</script>
</body>
</html>
testing.txt:
abc
def
ghi
The response I get if i console.log(data):
0<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text);
};
function post(vally) {
var table = vally;
$.post('test.php', {table:table}, function(data) {
})
.done(function (data) {
if (data == 1) {
console.log("the output is 1")
} else {
console.log(data)
}
});
console.log('posted');
}
</script>
</body>
</html>
I have tried using .done(), .fail() and .always() but I always get the output isn't 1(I am using JQuery 3.2.1).
Can someone tell me what I'm doing wrong?
EDIT: I would like to point out something I haven't before. I'm looking for a one page solution. I know that it can easily be done with two pages but I was wondering if there was a one page solution.

The problem is the Ajax request is sent to the home page, so it receives everything after '0' or '1'. Split that.
Move your PHP code in anoter file, say 'ajax.php'
And change your $.post() settings to call ajax.php instead of test.php.
So the Ajax request will only receive the '0' or '1' string.

Notice how your AJAX response is the entire page, prepended with the single digit that you're looking for. You don't need to send the whole page to the browser twice. Move your PHP logic into its own file with nothing but that logic. Let's call it checkTable.php for the sake of demonstration:
<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
if (in_array($_POST['table'], $file)) {
echo "1";
} else {
echo "0";
}
}
?>
Then make your AJAX call to that page:
$.post('checkTable.php', {table:table})
Then the response will contain only what that PHP code returns, not the whole page. (It's worth noting that this PHP code will return an empty response if table isn't in the POST data.)
Aside from that, your code is currently returning a 0 for whatever input you're providing, so it's still going to be true that "the output isn't 1". For that you'll need to double-check your input and data to confirm your assumptions.

Because I wanted everything in one file I decided to use data.slice(0, 1); to trim off everything except the first character which will be a 0 or 1, and thanks to David for reminding me that there may be a whitespace issue, which there was. Now I added text.trim() to remove all of the whitespace from the input and array_filter(array_map('trim', $file)); to remove all of the whitespace from the strings written in the file.
This is the finished code:
<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
$file = array_filter(array_map('trim', $file));
if (in_array($_POST['table'], $file) == true) {
echo "1";
} else {
echo "0";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text.trim());
};
function post(vally) {
var table = vally;
console.log(vally);
$.post('test.php', {table:table}, function(data) {
var cut = data.slice(0, 1);
if (cut == 1) {
console.log("the output is 1")
} else {
console.log(cut);
}
});
console.log('posted');
}
</script>
</body>
</html>
I would like to thank everyone who helped me resolve my issue, which has been bugging me for the last 2 days.

Related

jquery $.getScript().. How to get data from external js file into array

I try to put data into js file, through "jquery $.post" and "fwrite php", and get back that data into array. How to do that?
here's the html:
<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function() {
if ($("#nameput").val() != "") {
$.post("processing.php", {
putname: $("#nameput").val()
});
var arr = [$.getScript("talk.js")];
alert(arr[0]);
}
})
})
</script>
</head>
<body>
<input type="text" id="nameput" />
<button id="button">send AJAX req</button>
</body>
</html>
Here's the php, I name it "processing.php" :
<?php
$file = fopen("talk.js","a");
$text = $_POST["putname"];
fwrite($file,'"'.$text.'",');
fclose($file);
?>
And "talk.js" will look like this :
"a","b","c",
Why I can't put that data from "talk.js" into array at " var arr = [$.getScript("talk.js")]; " as in html file above?
Here's what I try after I read comments. I change the scirpt into this:
<script>
$(document).ready(function() {
$("#button").click(function() {
if ($("#nameput").val() != "") {
$.post("processing.php", {
putname: $("#nameput").val()
}, function() {
$.getScript("talk.js", function(data) {
var arr = data.split(",");
alert(arr[0]);
})
})
}
})
})
</script>
And php into this:
<?php
$file = fopen("talk.js","a");
$text = $_POST["putname"];
fwrite($file,$text);
fclose($file);
?>
But it still not work?
here's a simplified version of your button click to help you out:
$("#button").click(function() {
$.getScript("talk.js", function(data){
var arr = data.split(',');
alert(arr[0]);
});
});
If you log the output of $.getScript you will easily see why what you're trying doesn't work.
Using this method you will get the data returned from the script ("a","b","c"), but you'll need to split it on a comma into an array. Then you can reference whichever part of the array you want.
Note that the each element of the array will have quotations around them.

ajax new record count notification in php

iam doing a page in php that if any new record is entered it will notify the users screen with the new record count. Following is the code i did for the same, but its not working fine. Can u pls suggest me as of what iam doing wrong...
alert.php
<?php
require("config.php");
$result = mysql_query("SELECT * FROM marketing_tend_corr");
$res = mysql_num_rows($result);
echo $res;
?>
index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php
define('BASEPATH', true);
require("config.php");
?>
<script>
var count_cases = -1;
setInterval(function(){
$.ajax({
type : "POST",
url : "alert.php",
success : function(response){
if (count_cases != -1 && count_cases != response) echo $count_cases);
count_cases = response;
}
});
},1000);
</script>
The following line of code is not going to work in Javascript:
if (count_cases != -1 && count_cases != response) echo $count_cases);
This line of code contains php code (echo $count_cases) which is server side code.
I've changed the code a bit and replaced the number of records by returning a random value.
// alert.php
<?php
echo rand(1, 1000000);
//index.php
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
setInterval(function(){
$.ajax({
type : "POST",
url : "alert.php",
success : function(response){
$("body").html(response);
}
});
},1000);
</script>
</head>
<body>
</body>
</html>
You can check the index.php file in your browser to see the random numbers being returned. This random number should in your case become the result of your 'mysql_num_rows' function.

Getting JSON value from php using jquery ajax

Hi friends can anyone me for this plz. im new to this chapter..i am trying to get JSON format value from PHP but while im running i got this output "SyntaxError: JSON.parse: unexpected characte".. i think i had done mistake in php conversion ...plz help me friends
my .html file
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<title>Display Page</title>
</head>
<body>
<button type='button' id='getdata'>GetData.</button>
<button type='button' id='get'>sample</button>
<script type='text/javascript'>
$('#get').click(function() {
alert("laksjdflk");
});
$(document).ready(function() {
$('#getdata').click(function() {
$.ajax({
url:'neww.php' ,
dataType:'json' ,
success:function(output_string) {
alert(output_string);
},
error:function(xhr,ajaxOptions,thrownError){
alert(xhr.statusText);
alert(thrownError);
}
});
});
});
</script>
</body>
</html>
generatephp.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("androidlogin");
$sql=mysql_query("SELECT* FROM trysave");
$temp="";
$i=0;
while($row=mysql_fetch_assoc($sql)){
$temp=$row['stringss'];
$temp.=$row['integerr'];
$array[i]=$temp;
i++;
}
echo json_encode($array);// this will print the output in json
?>
This may because of Undefined array variable notice you have to define array in case no records found
Also you missed a $ before variable i which gives error(treated as CONSTANT, and which is undefined in your code), i should be $i like,
$array=array();// define here to prevent from "Notice"
while($row=mysql_fetch_assoc($sql))
{
$temp=$row['stringss'];
$temp.=$row['integerr'];
$array[$i]=$temp;// use $ before i
$i++;// use $ before i
}
echo json_encode($array);// this will print the output in json
One more thing you have mentioned PHP file name as generatephp.php and you are using url:'neww.php' , in $.ajax(), you have to check your code once.
Obvious problems (cough MySQL_*) aside, your PHP file should specify in the response headers that the output will be of type JSON. The output defaults to text/html and Javascript cannot parse it as a valid JSON object.
You can do it like this
<?php
header('Content-type: application/json');
// Rest of the code remains intact
i wold use something different ...
php:
<?php
mysql_connect("localhost","root","");
$sql=mysql_query("SELECT stringss, integerr FROM androidlogin.trysave");
$temp=array();
$i=0;
while($row=mysql_fetch_assoc($sql)){
$temp[] = $row;
}
echo json_encode($temp);// this will print the output in json
?>
//you do not need the $i variable since you will get in java str.length = that $i
<script type='text/javascript'>
$('#get').click(function() {
alert("laksjdflk");
});
$(document).ready(function() {
$('#getdata').click(
function() {
jQuery.getJSON( "neww.php") //no get vars
.done(function(a) {
//console.clear();
console.log(a);
show_data(a);
})
.fail(function(a) {
console.log( "error" );
});
});
});
function show_data(a){
for(var i=0; i<a.length; i++)
var stringss = a[i].stringss;
var integerr = a[i].integerr;
var nuber_temp = i;
//do stuff with them ...
}
</script>
if problem persists ... try http://php.net/manual/ro/function.urlencode.php

How do I send data to my PHP script using AJAX?

I'm new to PHP and Javascript/Ajax so please bear with me.
All I need to do is get a variable from Ajax and set it as a variable in php. I'm trying to do this with a super global GET but something is not right. I don't want to this by submitting the form.
Here's my JS:
function myFunction(){
var hora= document.getElementById("hora").value;
$.ajax({
type : 'GET',
url : 'reservation.php',
data : {hora: hora},
success : function(data) {
console.log(hora);//This is because I was curious as to
// what the console would say. I found
// that this sets the super global if I
// change the url to something else that
// doesn't exist. Console would say
// -GET http://localhost/bus/(somepage).php?hora=4
// 404 (Not Found)-
alert(hora);
}
})
}
Here's my PHP:
Hora:
<select name="hora" id="hora" onchange="myFunction()">
<?php
$query = "SELECT * FROM vans";
$horas_result = mysql_query($query);
while ($horas = mysql_fetch_array($horas_result)) {
echo "<option value=\"{$horas["van_id"]}\">{$horas["time"]}</option>";
}
?>
</select>
Asientos Disponibles:
<?php echo $_GET["hora"]; ?>
//Right now I only want to echo this variable..
As you can see, right now I only want to echo this variable, later on I'll be using this to write a query.
Look at the code i post, ajax is used to post/get data without need to refresh the page but if you just want to post the data and give the result in other page use a form instead.
<?php
if (isset($_GET["hora"]))
{
echo $_GET["hora"];
exit;
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Page title</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function()
{
$("#hora").change(function ()
{
$.ajax(
{
type : 'GET',
url : '',
data : $('select[name=\'hora\']'),
success : function(data)
{
$('#ajax_result').html('Asientos Disponibles: ' + data);
},
error: function(xhr, ajaxOptions, thrownError)
{
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
}
)
}
)
}
)
</script>
<select name="hora" id="hora">
<?php
$query = "SELECT * FROM vans";
$horas_result = mysql_query($query);
while ($horas = mysql_fetch_array($horas_result)) {
echo "<option value=\"{$horas["van_id"]}\">{$horas["time"]}</option>";
}
?>
</select>
<div id="ajax_result">
</div>
</body>
</html>
For example, the following script
$.ajax({
type: "POST",
url: "test.php",
data: {value:1}
}).done(function(msg) {
// msg contains whatever value test.php echoes. Whether it is code, or just raw data.
if(msg=="Success") {
alert("hello world");
} else {
alert("Hello Hell")
}
});
Will set the variable $_POST['value'] to 1
and my test.php looks like:
<?php
if($_POST['value'] == "1") {
echo "Success";
} else {
echo "Failure";
}
?>
If you run that example, the webpage will show you an alert box with the text "Hello World"
If you change the value to any other number, it will show you an alert with the text "Hello Hell"
Hope that answers your question.

Call function in a seperate div tagad from href link

I have two files: index.php and cart.php
In cart.php I have few three functions - products_all(), products_shirts(), products_hoodies(). Those functions get info from my database and outputs it if called.
I want each of those functions to be called by clicking on hyperlinks and then to be outputed in a div tag, so that only the div tag is being refreshed not the whole site.
I read about jQuery/AJAX function load, but I can't get it to work.
If you don't want the whole page to be refreshed, there is no way around using ajax.
But it's not that hard. When using a library like jQuery, you can do it in a few lines.
Your HTNL + javscript code:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function callFunction(yourfunction)
{
$.post('cart.php', { "function": yourfunction }, function(data) {
alert(data);
});
}
$(document).ready(function()
{
$("#functionOne").on("click", function()
{
callFunction(1)
});
$("#functionTwo").on("click", function()
{
callFunction(2)
});
});
</script>
</head>
<body>
<a id="functionOne">function one</a>
<a id="functionTwo">function two</a>
</body>
</html>
And on the server side (cart.php) something like this:
<?php
if (isset($_POST['function']))
{
switch ($_POST['function'])
{
case 1:
functionOne();
break;
case 2:
functionTwo();
break;
}
}
function functionOne()
{
echo "hi, i am func1";
}
function functionTwo()
{
echo "hi, i am func2";
}
This should get you started!

Categories