Whay I can't pass a variable from js to php
$("#btnpage").click(function(){
path = $('#spantwrap').html();
$.ajax({
url: 'plus-page.php',
type: 'post',
data: {'path': path},
success: function() {
console.log(path);
}
});
location.href = 'plus-page.php';
});
plus-page.php
<form id="form1" action="?" method="post">
<input type="hidden" name="path" value="<?php echo $_POST['path'];?>" // line 46
</form>
Error: Undefined index: path on line 46...
Have you tried this?
$("#btnpage").click(function(){
path = $('#spantwrap').html();
$.ajax({
url: 'plus-page.php',
type: 'post',
success: function() {
location.href = 'plus-page.php?path=' + path;
}
});
});
so that you can use this?
<input type="hidden" name="path" value="<?php echo $_POST['path'];?>">
What would be the value of your path?
Why don't you use form post method with this solution ??? ?
First Ajax post it completed when success: function called... In new window you doesn't have any post data, I don't know any solution post data by javascript to new window.. only one you can send data by GET request ..
You can see variable posted by ajax and open url by new window.. please use
With out using ajax ,to achieve what you required.
$(document).on('click', '#button', function(){
var my_data = 'Test Test Tes';
window.open('plus-page.php?my_data='+my_data);
});
plus-page.php
<?php
if(isset($_GET['my_data'])){
$data=$_GET['my_data'];
echo $data;
}
?>
Related
I have this code for example
<?php
if(isset($_POST['goose'])){
echo '<div>goose</div>';
}
?>
<form action="goose.php" method="POST">
<input type="submit" name="goose" />
</form>
How can I write something like this but in AJAX? I don't know this language.
I recommend using jQuery.
$.ajax({ // begins our async AJAX request
type: "POST", // defining as POST
url: "goose.php", // page to request data from
data: ["goose":$("input[name=goose]").val()], // define POST values
success: function(output){
alert(output);
},
error: //do something else
});
Because we have set the type to POST our data will need to be in the form of an associative array with "goose" being equivalent to $_POST["goose"].
data: ["goose":$("input[name=goose]").val()],
The success is what will happen if the data is able to be sent correctly with output being what is returned. In our case output = <div>goose</div>.
success: function(output){
alert(output);
}
error can also have a function but here you will want to tell the script what do do if say goose.php is un-reachable.
No need for extra frameworks. Just use fetch api.
<form action="goose.php" method="POST" onsubmit="submit(event, this)">
<input type="submit" name="goose" />
</form>
Javascript:
function submit(event, form) {
event.preventDefault();
fetch(form.action,{
method: 'post',
body: new FormData(form)
}).then((data) => {
console.log(data);
});
}
I use this to pass an argument (fullname).
<script type="text/javascript">
function listbox_update(){
var fullname = document.getElementById("listboxid").value;
document.location.href="{$_SERVER["PHP_SELF"]}?fullname="+fullname;}
</script>
Is there a way to pass the argument such that it can NOT be seen in the http URL?
I know about POST.
$listboxselected = $_POST['listbox'];
I would use POST instead, so that the argument is not present in the URL, but I can't, because I'm using the javascript as an On Click event.
<select id="listboxid" name=listbox onChange="listbox_update()"></br>
The On Click event works perfectly. But I don't like seeing all my variables in the URL.
If you want to do that only by JS then you can go with Ajax.
function listbox_update(){
var fullname = document.getElementById("listboxid").value;
$.ajax({
data: { fullname: fullname },
url: <?php echo $_SERVER["PHP_SELF"]; ?>,
type: "POST",
success: function(msg){
//some function here
}
});
}
Wrap the <select> in a <form> and then in onchange submit the form.
<form id="form" method="post" action="<?=$_SERVER["PHP_SELF"]?>">
<select id="listboxid" name="fullname" onChange="listbox_update()">
<option>here the options</option>
</select>
</form>
and the listbox_update
function listbox_update () {
document.getElementById('form').submit();
}
Another option would be to use Ajax, but since your original script reloads the page, then the first approach follows this way.
You have only 2 solutions for this:
1) Either you must implement AJAX like below:
function listbox_update()
{
var fullname = $("#listboxid").val();
$.ajax({
data: "fullname="+fullname,
url: <?php echo $_SERVER["PHP_SELF"]; ?>,
type: "POST",
success: function(msg){
console.log("Message :"+msg);
}
});
}
2) Or go with form submission.
function listbox_update()
{
$('#your_form_id').attr('action', <?php echo $_SERVER["PHP_SELF"]; ?>);
$('#your_form_id').submit();
}
I need to use a localStorage value in a PHP file to update values in my database. I know that I need ajax to achieve this, I can't get it to work.
My localStorage item is named option and it exists (checked in browser and stored the value in a div)
$(document).ready(function(){
$.ajax({
type: "POST",
url: "activity.php",
data: { storageValue: localStorage.getItem('option') },
success: function(data){
alert('success');
}
});
});
PHP Example:
$option = $_POST['storageValue'];
mysql_query("...SET x = '".$option."'...");
echo 'Update complete';
I dont see any post data nor do I get a response.
Thank you!
Your page:
<form>
<input type="hidden" value="thedatayouwanttopost" id="option"/>
</form>
<script src="Your_Js_File.js"></script>
Your JS file:
document.getElementById('option').submit(); // This submits the form
var storageValue = $('#option').val(); // This gets the value of the form once it has been posted to the .php file
$(document).ready(function(){
$.ajax({
type: "POST",
url: "activity.php",
data: { storageValue:storageValue },
success: function(data){
alert('success');
}
});
return false; // This stops the page from refreshing
});
Your PHP file to callback the data to AJAX and display the alert (activity.php):
...
$option = $_POST['storageValue']; // This is the post value of your hidden input on your page
mysql_query("...SET x = '".$option."'...");
?><input type="hidden" id="option" value="<?php echo $option; ?>"><?
// The input above posts the value of 'option' on your page back to your Ajax and spits out the request.
...
This is my jQuery-Ajax code:
<script>
$('#sbmt').click( function(){
$.ajax({
type: 'post',
data: $("#ajxfrm").serialize(),
url: "postdata.php",
cache: false,
success: function (data)
{
alert('updated table');
}
});
});
</script>
HTML CODE:
<form id="ajxfrm" method="post" action="">
<label>HIGH : </label> <input type="text" name="hi" id="hi"><br><br>
<label>LOW : </label><input type="text" name="lo" id="lo"><br><br>
<label>OPENING STOCK : </label><input type="text" name="opn" id="opn"><br><br>
<label>CLOSING STOCK : </label><input type="text" name="cls" id="cls">
<input type="submit" value="Submit" id="sbmt">
</form>
AND PHP CODE ON postdata.php file is :
require_once 'config.php';
$hi = $_POST['hi'];
$lo = $_POST['lo'];
$opn = $_POST['opn'];
$cls = $_POST['cls'];
echo $hi;
$postdata = "INSERT INTO htmdem ( high,low,open,close ) VALUES('$hi','$lo','$opn','$cls');";
mysql_query($postdata);
When posting via form without ajax the table is getting updated as it should, but while using AJAX its not. Please suggest what's wrong here. Many Thanks
Try this : Dont forget to set the form action to postdata.php
jQuery(function($) {
$('#ajxfrm').submit( function(e){
$.ajax({
type: 'post',
data: $(this).serialize(),
url: $(this).attr("action")
})
.done(function (data){
alert('updated table');
});
e.preventDefault();
});
});
Modify your html to add action to form:
<form id="ajxfrm" method="post" action="postdata.php">
Try handling form submit event instead:
$('#ajxfrm').submit(function(event){
$.ajax({
type: 'post',
data: $(this).serialize(),
url: $(this).attr("action"),
cache: false,
success: function (data)
{
alert('updated table');
}
});
return false; //to prevent form submission
//or event.preventDefault();
});
BTW, using success callback is deprecated and post requests are not cached so we also don't need cache:false
$('#ajxfrm').submit(function(event){
$.ajax({
type: 'post',
data: $(this).serialize(),
url: $(this).attr("action")
})
.done(function (data){
alert('updated table');
});
return false; //to prevent form submission
//or event.preventDefault();
});
change your input type="submit" to input type="button". that should do the trick I guess.
Assuming you have included the jquery library in your page,
First, run your page with with your firefox/chrome and use their firebug/console to verify that your ajax is actually posting data to your php page.
Second, modify your query execution in your php file, to catch query errors:
mysql_query($postdata) or die(mysql_error());
One of these cases will help you determine your problem
For Firefox: get the Firebug addon from https://getfirebug.com/
After installing it and restarting firefox, press F12. A console will open.
Run your ajax call and check in the console if data are being posted.
Apologies if this has been answered before (I couldn't find the answer when I searched the archives)
I've got a page protected by a password:
<?php
if($_POST['pw'] == 'pw')
{
//Page content
} else
{
//Display password form
}
?>
Within the page content, I've got another form, which I want to submit using jQuery, and have the following code:
<script type='text/javascript'>
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function()
{
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
</script>
<form name='form1' id='form1' action=''>
<fieldset>
<label for='input1' id='input1_label'>Input 1</label>
<input type='text' name='input1' id='input1' size='30' />
<input type='submit' value='Update / reset' id='submit' class='buttons' />
</fieldset>
</form>
<div id='#testResult'></div>;
However, clicking submit then sends the form to p1.php?input1=test (i.e., the data string is being sent to p1.php, not p2.php). If I edit the code and remove dataType:html and the 2 references of data2, then this doesn't happen (infact, nothing happens, so I assume that jQuery is submitting the data to the form). I've also changed the type to 'GET', incase the 2 POST requests on the same page were causing problems, but this didn't change the result.
What am I missing to get the information from p2.php (i.e. data2) and displaying it?!
EDIT
Thanks to a comment pointing out a typo, I've changed dataType: html to dataType: 'html' - this now doesn't cause the page to redirect to p1.php?input1=test, but once again, it doesn't do anything (when it should still be returning the value of data2)
EDIT 2
I've updated the code so dataString is now:
var dataString = $('input#input1').val();
dataString = 'var1='+dataString;
but this hasn't made any difference
For clarification, my p2.php just contains the following:
<?php
echo "<p>HELLO!</p>";
?>
EDIT 3
I made the changes to my code has suggested by Damien below; I get the alert of "works!" but still nothing seems to be returned from p2.php, and nothing is inserted into the #testResult div.
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function(evt)
{
evt.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: "someval="+dataString,
dataType: 'html',
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
$(function() {
$('#submit').click(function()
{
var dataString = $('#form1').serialize();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
success: function(data2) {
alert('works!'); // ADDED AFTER UPDATE
$('#testResult').html(data2);
},
/* ADDED AFTER UPDATE */
error:function(obj,status,error)
{
alert(error);
}
});
return false;
});
});
Edit:
In p2.php:
<?php
var_dump($_POST['pw']);
?>
In p2.php you then need to output ( using echo, for example) what you want to be returned as 'data2' in your ajax success call.
UPDATE:
Since you're Ajax request fires succesfully, that means either your post is not passed correctly, or you're not outputting anything. I've re-looked at your code and I saw this:
<input type='text' name='input1' id='input1' size='30' />
that means you're fetching the wrong $_POST variable!
Do this:
Since you're sending a name="input1", in your p2.php try with:
<?php
if(isset($_POST['input1'])
{
echo $_POST['input1'];
}
else
{
echo 'No post variable!';
}
And in your jquery success:
success: function(data2) {
alert(data2);
$('#testResult').html(data2);
},
That oughta work, if you follow it literally. In the remote possibility it won't work, forget AJAX, remove the javascript and do a normal post submitting with p2.php as an action of your form :)
I think you have to prevent the default action of the form.
Try this:
$('#submit').click(function(e)
{
e.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
The data should be formatted like this:
variable1=value1&variable2=varlue2
I also think you can remove the dataType property.