Sending JS object with AJAX not updating PHP script [duplicate] - javascript

I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.

You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.

Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.

This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>

Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP

Related

How to get "$.Post" variable in another site

i search internet for my question and i doesn't found how to get my $_POST on another page. Please help.
game.php:
<?php
session_start();
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
var drzewo = 0;
function save() {
$.post( "save.php", { drzewo: drzewo } );
window.location.href = "save.php"
}
presave.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<?php
session_start();
$_SESSION['drewno'] = $_POST["drzewo"];
echo $_SESSION['drewno']
?>
Undefined array key picture
Your question seems incomplete in my opinion. There are many things missing from your question. From your image I assume you are using it on local server. There are one thing that looks weird is this:
`$.post( "save.php", { drzewo: drzewo } );`
Where is this save.php file stored? Is it stored in your root file? Or along with the operating file. Put a "/" before save.php and see what happens.
There is another thing that seems awkward is your image is showing there is a presave.php file. But I found nothing about that file in your question details.
I can see that you put a redirecting code in your script. JS is not supposed to work like that. What happening here is it is doing an asynchronous operation. That is why PHP can't get the data and showing you a error. If you want to send data send it in a form. Or you can put a redirection in your PHP code after getting the post data. Since it is an AJAX call you can see some reports in your console.log() with the response data.
$.post( "save.php", { drzewo: drzewo } );
window.location.href = "save.php"
Let's analyze these 2 lines of code.
When you send a post request through javascript, it goes through an ajax request and the browser waits till the save.php completes working it's code and returns to the ajax. Here the save.php has received the $_POST data and has processed it.
This processed data by save.php will not output in the browser. It will go to the post (ajax) callback function. If you want to display the data, you need to use a callback function. See this https://www.w3schools.com/jquery/ajax_post.asp for a simple usage of $.post() function.
In the next line of your code you are redirecting your browser to save.php without sending any $_POST data. Since now your save.php does not have any information about $_POST["drzewo"] it throws an error Undefined array key "drzewo" .
Therefore instead of window.location.href page redirect, you need a callback function with your $.post() function. I hope now you understand why you are getting this error.
[Edit]- I have added some code for your better understanding. You can refer to this excellent "JQuery Ajax POST Method" tutorial from freecodecamp.org. https://www.freecodecamp.org/news/jquery-ajax-post-method/
game.php
<?php
session_start();
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<button id="btn" onclick="save();">Click this</button>
<script type="text/javascript">
var drzewo = 0;
function save() {
$.post("save.php", {
drzewo: drzewo
},
function(result) {
alert("This result contains the output from save.php : " + result);
//Write here the code you want to execute after the POST request is successfully completed.
}
);
}
</script>
</body>
</html>
save.php
<?php
session_start();
$_SESSION['drewno'] = $_POST["drzewo"];
echo $_SESSION['drewno'];
If you want to pass data from one URL to another, use query string. $.post() makes a POST request, but it seems like save.php is not an endpoint but actually a page.
In other words, you can do this:
window.location.href = `save.php?drzewo=${drzewo}`;
And then on save.php simply read the value from $_GET:
<?php
session_start();
$_SESSION['drewno'] = $_GET["drzewo"];
echo $_SESSION['drewno']
?>

JSON stringify converting complete array element to key of an array in PHP

I am trying to attach sendBeacon method to one of the page in my web application. I tried to send request using a simple AJAX method and via sendBeacon() method. Both are giving different results and none is usable. Please suggest.
html.php
<body>
<button onclick="setzero();">
click me
</button>
<script>
function setzero(){
var settings = {
"url":"ttstt.php",
"method":"POST",
"data": JSON.stringify({"val":0})
};
$.ajax(settings).done(function(e){console.log(e);});
}
window.addEventListener("unload", function() {
navigator.sendBeacon("ttstt.php", JSON.stringify({"val":1}));
});
</script>
</body>
ttstt.php
$val = ($_POST);
print_r($val);
When I click the button on html.php I get the following result.
!! Please note that the complete array is in the key portion. !!
Array
(
[{"val":0}] =>
)
When I reload the page to initiate the sendBeacon(), I get [] as a result.
I just changed the following in my PHP code
$val = file_get_contents("php://input");
$json = json_decode($val);
echo $json['val']; //This gives output as 0, which I was looking for.
Also same code works with sendBeacon() data also.

PHP echo is not working with JQuery post data [duplicate]

I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP

JQuery to submit PHP not executing

After hours of playing with this, it hit me that my JQuery simply isn't executing.
I have a page that I am trying to submit to a PHP script without refreshing/leaving the page. If I use a typical form action/method/submit, it inserts into my database just fine. But when I use JQuery, the JQuery will not run at all. The alert does not show. (I'm new to JQuery). I have tried to research this, but nothing is working.
Here is my main page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(e) {
$('submitpicks').on('submit','#submitpicks',function(e){
e.preventDefault(); //this will prevent reloading page
alert('Form submitted Without Reloading');
});
});
</script>
</head>
<body>
<form name="submitpicks" id="submitpicks" action="" method="post">
<script language="javascript">
var v=0;
function acceptpick(thepick,removepick){
var userPick = confirm("You picked " + thepick + ". Accept this pick?");
//var theid = "finalpick" + v;
var removebtn = "btn" + removepick;
//alert(theid);
if(userPick==1){
document.getElementById("finalpick").value=removepick;
document.getElementById(removebtn).disabled = true;
document.getElementById("submitpicks").submit();
v=v+1;
}
}
</script>
<?php
include "Connections/myconn.php";
//$setid = $_SESSION["gbsid"];
$setid = 11;
$setqry = "Select * from grabBagParticipants where gbsid = $setid order by rand()";
$setresult = mysqli_query($conn, $setqry);
$u=0;
if(mysqli_num_rows($setresult)>0){
while($setrow = mysqli_fetch_array($setresult)){
//shuffle($setrow);
echo '<input type="button" name="' . $setrow["gbpid"] . '" id="btn' . $setrow["gbpid"] . '" value="' . $u . '" onClick=\'acceptpick("' . $setrow["gbpname"] . '", ' . $setrow["gbpid"] . ');\' /><br />';
$u=$u+1;
}
}
?>
<input type="text" name="finalpick" id="finalpick" />
<input type="submit" value="Save" />
</form>
<div id="results"> </div>
</body>
</html>
Here is my PHP:
<?php
include "Connections/myconn.php";
$theGiver = 1;
$theReceiver = $_POST['finalpick'];
$insertsql = "insert into grabBagFinalList(gbflgid, gbflrid) values($theGiver, $theReceiver)";
mysqli_query($conn, $insertsql);
?>
you can use e.preventDefault(); or return false;
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault();
$.post('submitpick.php', $(this).serialize(), function(data) {
$('#results').html(data);
});
// return false;
});
});
</script>
Note: in your php you not echo out anything to get it back as a data .. so basic knowledge when you trying to use $.post or $.get or $.ajax .. to check the connection between js and php .. so in php
<?php
echo 'File connected';
?>
and then alert(data) in js .. if everything works fine .. go to next step
Explain each Step..
before everything you should check you install jquery if you use
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
from w3schools website.. its totally wrong .. you should looking for how to install jquery ... then
1st to submit form with js and prevent reloading.. and you used <script> in your main page
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault(); //this will prevent reloading page
alert('Form submitted Without Reloading');
});
});
<script>
output : alert with Form submitted Without Reloading ... if this step is good and you get the alert .. go to next step
2nd add $.post to your code
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault(); //this will prevent reloading page
$.post('submitpick.php', $(this).serialize(), function(data){
alert(data);
});
});
});
<script>
and in submitpick.php >>> be sure your mainpage.php and submitpick.php in the same directory
<?php
echo 'File connected';
?>
output: alert with File connected
Have you heard of AJAX(asynchronous javascript and XML). While it may not be something that is easy to learn for someone who is new to JQuery and javascript, it does pretty much what you need. Well, its a bit more complicated than that, but basically AJAX submits information by using HTTP requests (much like normal forms) but without refreshing the page.
Here's a link to a tutorial: http://www.w3schools.com/ajax/ with vanilla javascript.
Here's one with Jquery: http://www.w3schools.com/jquery/jquery_ajax_intro.asp
And here's an example of how you can set it up with Jquery:
$(document).ready(function() {
$.ajax({
method: "POST",
url: "/something.php"
dataType: "JSON",
data: {formData:{formfield1: $('formfield1').val(), formfield2: $('formfield2)'.val()}},
success: function(data){
if (data["somevalue"]) == something {
dosomething;
} else {
dosomethingelse
},
error: function() {
alert("Error message");
}
});
});
This is only a basic example, now what does all this stuff mean anyway. Well, there are several methods, some of them are POST and GET, these are HTTP request methods, which you can use to do several things. I'm no expert on this stuff, but here's what they do:
Method
POST
POST basically works, to submit information to a server, which is then usually inserted to a database to which that server is connected to. I believe most forms utilize POST requests, but don't quote me on that.
GET
GET on the other hand requests data from a server, which then fetches it into the database and sends it back to the client so it can perform an action. For instance, whenever you load a page, GET requests are made to load the various elements of a page. What's important to note here, is that this request is made specifically to retrieve data.
There are other types of HTTP requests you can use such as PUT and DELETE, which I'd say are the most common along with GET and POST. Anyway I'd recommend that you look them up, its useful information.
Url
The url represents the path to which you are making a request, I'm not exactly sure how it works with PHP, I think you just need to call the PHP page in question and it will work properly, but I'm not sure, I haven't used PHP since my last semester, been using Rails and it doesn't work quite the same. Anyway, lets say you have some PHP page called, "Something.php" and lets say that somethihng PHP has the following content:
<?php
$form_data = $_POST['data'];
$array = json_decode(form_data, true);
do something with your data;
$jsonToSendBack = "{status: 1}";
$response = json_encode($jsonToSendBack);
echo $response;
?>
So basically what that file received was a JSON, which was our specified datatype and in turn after we finish interpreting data in the server, we send back a response through echo our echo. Now since our datatype is a JSON, the client is expecting a response with JSON, but we'll get to that later. If you're not familiar with JSON, you should look it up, but in simple terms JSON is a data exchange format that different languages can utilize to pass data to each other, like in this example, where I sent data to PHP through Javascript and vice-versa.
DataType
Data type is basically, the type of information that you want to send to the server, you can specify it through ajax. There are many data types you can send and receive, for instance if you wanted to, you could send XML or Text to the server, and in turn it should return XML or text, depending on what you chose.
Success and Error
Finally, there's the success and error parameters, basically if a request was successful, it returns a status code of 200, though that doesn't mean that other status codes do not indicate success too, nonetheless 200 is probably the one you'd like to see when making HTTP requests. Anyway, success basically specifies that if the request succeeded it should execute that function code I wrote, otherwise if there is an error, it will execute the function within error. Finally, even if you do have a success on your request, that doesn't mean everything went right, it just means that the client was successful in contacting the server and that it received a response. A request might be successful but that doesn't generally mean that your server-side code executed everything perfectly.
Anyway, I hope my explanation is sufficient, and that you can take it from here.

Get php variable to javascript from laravel controller

Im trying to send a variable from a controller to a JavaScript, I have my controller, and I can send an array:
public function index()
{
$casa = new Casa(true);
$result = $casa->where(['show'=>true])->get();
return view('casa', array('casa' => $result));
}
If i go to my HTML and I make and echo:
<html>
<body>
<?php echo $casa ?>
</body>
</html>
I can show my array in the body, I was thinking about make an invisible element and get the array with document.getElementById().innerHTML, but I think this is not the best way.
Also, I think that I could make an Ajax petition sending a post and get the result, but I dont know if I can get my variable in a simpler way.
I tried to make and echo in Javascript and doesn´t work. some ideas?
Can I have 2 method post to get request in my controller? I already have one to get data from a form, and if I set the Ajax request I will have two post request. I would like have just one.
Jeffrey Way created a package for that. He also made a video explaining it in laracasts.com.
The package can be found here: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
You can simply get PHP variable in JavaScript like this:
<script>
var casa = '<?php echo $casa ?>';
</script>
you can use alert to see the result in popup dialog too:
<script>
var casa = alert('<?php echo $casa ?>');
</script>

Categories