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.
Related
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.
I have a code here
<h2>Click blue button</h2>
<button id="open_btn" class="btn btn-primary">Open dialog</button>
<div id="output"></div>
<script src="src/bootstrap.fd.js"></script>
<script type="text/javascript">
$("#open_btn").click(function() {
$.FileDialog({multiple: true}).on('files.bs.filedialog', function(ev) {
var files = ev.files;
var text = "";
files.forEach(function(f) {
text += f.name + "<br/>";
});
$("#output").html(text);
}).on('cancel.bs.filedialog', function(ev) {
$("#output").html("Cancelled!");
});
});
</script>
its a drag and drop upload using jquery and boostrap layout from http://www.jqueryscript.net/demo/Drag-Drop-File-Upload-Dialog-with-jQuery-Bootstrap. Its working, but the problem is, I don't know how to pass the data uploaded to php for processing and put the file into the server.
Anyone can help me with this?
you can try using ajax. Setup ajax in your project from tons of tutorials available on the net.
After that in your javascript function i suppose you want to pass variable text to php. So here's what you can do when you get a little hang about ajax by going through the tutorials
<script type="text/javascript">
$("#open_btn").click(function() {
$.FileDialog({multiple: true}).on('files.bs.filedialog', function(ev) {
var files = ev.files;
var text = "";
files.forEach(function(f) {
text += f.name + "<br/>";
});
$.ajax({
url: "'your php function name'?name ="+text,
success: function( data ) {
if(data == "retn value") { //return value of the php function
// alert("");
} else {
}
}
});
$("#output").html(text);
}).on('cancel.bs.filedialog', function(ev) {
$("#output").html("Cancelled!");
});
});
</script>
create a function in php which will take your data as an argument.
hope this helps.
I have the following :
<script charset="UTF-8">
function deleter(theid) {
var namme = document.getElementById(theid).id;
$.post( "sql_machine.php", {
selection_name: select_namme
})
}
</script>
using jquery, would it be possible to post a php array too? may be encoding it as json?
like the following?
<script charset="UTF-8">
function deleter(theid) {
var select_namme = document.getElementById(theid).id;
$.post( "sql_machine_tomskus.php", {
selection_name: select_namme,
{ array : dataToSend }
})
}
</script>
Just use JSON.stringify to send the array, and to decode it to array in php, use json_decode.
In JQ:
<script charset="UTF-8">
function deleter(theid) {
var select_namme = document.getElementById(theid).id;
$.post( "sql_machine_tomskus.php", {
selection_name: select_namme,
array : JSON.stringify(yourArrayOrObject)
})
}
</script>
Then, in php just use json_decode($_POST["array"])
thanksGINCHER here it is my final solution :
<script charset="UTF-8">
function deleter(theid) {
var select_namme = document.getElementById(theid).id;
$.post( "sql_machine.php", {
selection_name: select_namme,
array : <?echo json_encode($array);?>
})
}
</script>
I got a page with a form to fill it with custormers info. I got previous custormers data stored in a php array. With a dropdownlist users can fill the form with my stored data.
what i have is a jquery function that triggers when the value changes and inside that function i whould like to update the form values with my stored data (in my php array).
Problem is that i dont know how to pass my php array to the jquery function, any idea ??
this is how i fill the array:
$contador_acompanantes = 0;
foreach ($acompanantes->Persona as $acomp)
{
$numero = $acomp->Numero;
$apellidos = $acomp->Apellidos;
$nombre = $acomp->Nombre;
$ACOMPANANTES[$contador_acompanantes] = $ficha_acomp;
$contador_acompanantes++;
}
got my select object:
<select name="acompanante_anterior" id="acompanante_anterior">
<option value="1" selected>AcompaƱante</option>
<option value="2">acompanante1</option>
<option value="2">acompanante2</option>
</select>
and this is my code for the jquery function (it is in the same .php page)
<script type="text/javascript">
$(document).ready(function()
{
$('#acompanante_anterior').on('change', function()
{
});
});
</script>
var arrayFromPHP = <?php echo json_encode($phpArray); ?>;
$.each(arrayFromPHP, function (i, elem) {
// do your stuff
});
You'll likely want to use json_encode, embed the JSON in the page, and parse it with JSON-js. Using this method, you should be aware of escaping </script>, quotes, and other entities. Also, standard security concerns apply. Demo here: http://jsfiddle.net/imsky/fjEgj/
HTML:
<select><option>---</option><option>Hello</option><option>World</option></select>
<script type="text/javascript">
var encoded_json_from_php = '{"Hello":[1,2,3], "World":[4,5,6]}';
var json = JSON.parse(encoded_json_from_php);
</script>
jQuery:
$(function() {
$("select").change(function() {
$(this).unbind("change");
var val = json[$(this).val()];
var select = $(this);
$(this).empty();
$.each(val, function(i, v) {
select.append("<option>" + v + "</option>");
});
});
});
try this one..
<script type="text/javascript">
$(document).ready(function()
{
$('#acompanante_anterior').on('change', function()
{
my_array = new Array();
<?php foreach($array as $key->val)?>
my_array['<?php echo $key?>'] = '<?php echo $val;?>';
<?php endif; ?>
});
});
</script>
I just get the parameters from PHP GET method and use them using jQuery. There is no output when run the page.
<?php
if (isset($_GET['url'])){
$url = $_GET['url'];
$url = explode(" " , $url);
echo end($url);
exit;
}
?>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript">
$('input[type=text]').change(function (){
if ($(this).val() !== ''){
var url = $(this).val():
$.post('grab.php?url='+url+'', function (data){
window.open(data, 'Download', 'width=10,height=10');
$(this).html('');
});
}
});
</script>
</head>
<body>
<input type="text" style="width:100%;height:20px;"/>
</body>
</html>
I'm new to designs and hope mistake is there.
First of all put your document in standards mode (by using a proper doctype at the beginning, which means HTML 4/XHTML 1 strict or HTML 5). Then you can use error console for debugging.
I found following error
Unexpected token: ':' on line 7,
The colon should be a semicolon.
var url = $(this).val():
And then, the actual reason why nothing is happening is because the input is non-existent when the script is invoked/cached. You need to execute it after the DOM has been constructed.
$(document).ready(function() {
// content
});
Final code.
$(document).ready(function() {
$('input[type=text]').change(function (){
if ($(this).val() !== ''){
var url = $(this).val();
$.post('grab.php?url='+url+'', function (data){
window.open(data, 'Download', 'width=10,height=10');
$(this).html('');
});
}
});
});
put it in $(document).ready() like this:
$(document).ready(function() {
$('input[type=text]').change(function (){
if ($(this).val() !== ''){
var url = $(this).val():
$.post('grab.php?url='+url+'', function (data){
window.open(data, 'Download', 'width=10,height=10');
$(this).html('');
});
}
});
});
I think using a .change event on a text input isn't advisable. Usually .blur and .focus are more appropriate.
$(document).ready(function() {
$('input[type=text]').blur(function(){
var currentInput = this;
if ($(currentInput ).val() != ''){
var url = $(currentInput ).val();
$.post('grab.php?url='+url, function(data){
window.open(data, 'Download', 'width=10,height=10');
$(currentInput).val('');
});
}
});
});