this is my first time writing an ajax below is my structure
submitted.php
<?php $a = $_POST['a']; // an input submitted from index.php ?>
<button>bind to jquery ajax</button> // call ajax
<span></span> // return ajax result here
<script>
$('button').on('click', function() {
event.preventDefault();
$.ajax({
method: "POST",
url: "test.php",
data: { "key" : 'data'}
})
.done(function( msg ) {
$('span').html(msg);
});
});
</script>
test.php
<?php echo $a; // will this work? ?>
ajax return blank... no error, my error_reporting is on.
No, there are a few things wrong with this:
You are posting a key - value pair where the key is key, so you would need $_POST['key'] in your php script;
You should use .preventDefault() if you need to prevent an event like a form submit that is caused by your button. If that is the case, you need to get the event variable from your event handler: $('button').on('click', function(event) {.If there is no event to prevent, you can simply remove that line;
If you do have a form (it seems so from your comment), you can easily send all key - value pairs using: data: $('form').serialize().
form.php
<button>bind to jquery ajax</button> <!-- ajax trigger -->
<span></span> <!-- return ajax result here -->
<script>
// NOTE: added event into function argument
$('button').on('click', function(event) {
event.preventDefault();
$.ajax({
method: "POST",
url: "test.php",
data: { "key" : 'data'}
})
.done(function(msg) {
$('span').html(msg);
});
});
</script>
process.php
<?php
echo (isset($_POST['key'])) ? $_POST['key'] : 'No data provided.';
?>
This is the way to do it:
ubmitted.php
<button>bind to jquery ajax</button> // call ajax
<span></span> // return ajax result here
<script>
$('button').on('click', function() {
// no need to prevent default here (there's no default)
$.ajax({
method: "POST",
url: "test.php",
data: { "key" : 'data'}
})
.done(function( msg ) {
$('span').html(msg);
});
});
</script>
test.php
<?php
if (isset($_POST['key'])
echo $_POST['key'];
else echo 'no data was sent.';
?>
Related
I'm trying to dynamically change a modal's content with the result of a query using PHP.
So far, I've managed to reach the ajax call, but I'm not getting a success nor error message
PHP: get_user.php
<?php
include ("session-connection.php");
session_start();
$result = $_POST['param'];
echo $result;
?>
HTML
<script type="text/javascript">
function view_progress(row){
console.log("id: " + row);
var param = row;
$.ajax({
data: param,
url: 'get_user.php',
type: 'post',
beforeSend: function(){
$("#progressModal").modal('show');
$("#alert_name").html("...");
},
error: function (){
$("#alert_name").html("Error");
},
success: function(resultado){
$("#alert_name").html(resultado);
}
});
}
</script>
If the code is successfull it should change the label alert_name with the id the javascript function recieves.
I am trying to send ajax post javascript variable to php. My code php will only be executed if I press submit in another form.
My code is in one index.php file.
The console shows that this value has been sent, but my php code does not want to pick it up and does not execute the query. Why?
<?php
if (isset($_POST['imie2'])) {
...
if(isset($_POST['item_id']) && !empty($_POST['item_id'])){
$value = $_POST['item_id'];
if ($polaczenie->query("INSERT INTO zamowienia VALUES ('$value')")) {
...
?>
<form method="post">
<input type="text" name="imie2">
...
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
var value = localStorage.getItem('sumalist');
console.log(value);
$.ajax({
url:"index.php",
method:"POST",
data:{
item_id: value,
},
success:function(response) {
console.log('ok'); // console shows ok
},
error:function(){
alert("error");
}
});
});
</script>
You said:
if (isset($_POST['imie2'])) {
but your data looks like this:
data:{
item_id: value,
},
There's no imie2 field so your test will always fail.
main.php:
<SCRIPT type="text/javascript">
$("#btnSubmit").click(function () {
alert("What will i put here!");
});
</SCRIPT>
<input type = "submit" id = "btnSubmit" value = "Try IT!" />
<div id = "show_search2">
</div>
output.php:
<?php $val = $_POST['btnSubmit'];
echo "<H1>$val</H1>"; ?>
What specific jQuery functionality can get the value of the btnSubmit and access it through $_POST and output it to the div show_search2? I used prototype.js but it provides conflict with my other JS scripts in the index.
Note: all my script source is included in index and that's why I didn't include the source in this post.
Do you mean something like this:
$("#btnSubmit").click(function (e) {
e.preventDefault();
var submitVal = $(this).val();
$.ajax({
type: "POST",
url: "url_of_your_output.php",
data: {btnSubmit : submitVal},
success: function(response) {
$("#show_search2").html(response); //response from output.php
}
});
});
I have a div which contains some text for the database:
<div id="summary">Here is summary of movie</div>
And list of links:
Name of movie
Name of movie
..
The process should be something like this:
Click on the link
Ajax using the url of the link to pass data via GET to php file / same page
PHP returns string
The div is changed to this string
<script>
function getSummary(id)
{
$.ajax({
type: "GET",
url: 'Your URL',
data: "id=" + id, // appears as $_GET['id'] # your backend side
success: function(data) {
// data is ur summary
$('#summary').html(data);
}
});
}
</script>
And add onclick event in your lists
<a onclick="getSummary('1')">View Text</a>
<div id="#summary">This text will be replaced when the onclick event (link is clicked) is triggered.</div>
You could achieve this quite easily with jQuery by registering for the click event of the anchors (with class="movie") and using the .load() method to send an AJAX request and replace the contents of the summary div:
$(function() {
$('.movie').click(function() {
$('#summary').load(this.href);
// it's important to return false from the click
// handler in order to cancel the default action
// of the link which is to redirect to the url and
// execute the AJAX request
return false;
});
});
try this
function getmoviename(id)
{
var p_url= yoururl from where you get movie name,
jQuery.ajax({
type: "GET",
url: p_url,
data: "id=" + id,
success: function(data) {
$('#summary').html(data);
}
});
}
and you html part is
<a href="javascript:void(0);" class="movie" onclick="getmoviename(youridvariable)">
Name of movie</a>
<div id="summary">Here is summary of movie</div>
This works for me and you don't need the inline script:
Javascript:
$(document).ready(function() {
$('.showme').bind('click', function() {
var id=$(this).attr("id");
var num=$(this).attr("class");
var poststr="request="+num+"&moreinfo="+id;
$.ajax({
url:"testme.php",
cache:0,
data:poststr,
success:function(result){
document.getElementById("stuff").innerHTML=result;
}
});
});
});
HTML:
<div class='request_1 showme' id='rating_1'>More stuff 1</div>
<div class='request_2 showme' id='rating_2'>More stuff 2</div>
<div class='request_3 showme' id='rating_3'>More stuff 3</div>
<div id="stuff">Here is some stuff that will update when the links above are clicked</div>
The request is sent to testme.php:
header("Cache-Control: no-cache");
header("Pragma: nocache");
$request_id = preg_replace("/[^0-9]/","",$_REQUEST['request']);
$request_moreinfo = preg_replace("/[^0-9]/","",$_REQUEST['moreinfo']);
if($request_id=="1")
{
echo "show 1";
}
elseif($request_id=="2")
{
echo "show 2";
}
else
{
echo "show 3";
}
jQuery.load()
$('#summary').load('ajax.php', function() {
alert('Loaded.');
});
<script>
$(function(){
$('.movie').click(function(){
var this_href=$(this).attr('href');
$.ajax({
url:this_href,
type:'post',
cache:false,
success:function(data)
{
$('#summary').html(data);
}
});
return false;
});
});
</script>
<script>
function getSummary(id)
{
$.ajax({
type: "GET",//post
url: 'Your URL',
data: "id="+id, // appears as $_GET['id'] # ur backend side
success: function(data) {
// data is ur summary
$('#summary').html(data);
}
});
}
</script>
i have the following javascript file named coupon.js -
jQuery(document).ready(function(){
jQuery('.appnitro').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return true;
});
});
sms.php -
<?php
//process form
$res = "message deliverd";
$arr = array( 'content' => $res );
echo json_encode( $arr );//end sms processing
unset ($_POST);
?>
i am calling like this -
<form id="smsform" class="appnitro" method="post" action="sms.php">
...
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit"/>
</form>
<div id="content"></div>
Now i expected that after a successful form submission the div "content" would show the message without any page refresh.
But instead the page redirects to /sms.php and then outputs -
{"content":"message deliverd"}
Please tell where i am going wrong. My javascript is correct . No error shown by firebug. Or please tell some other method to acheive the reqd. functionality.
Even this coupon.js is not working-
jQuery(document).ready(function(e){
jQuery('.appnitro').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
e.preventDefault();
});
});
Not working even if i add return fasle at end. Please suggest some other method to acheive this functionality
The reason why the page is refreshing is because the submit event wasn't suppressed.
There are two ways to do this:
Accept an event object as a parameter to the event handler, then call preventDefault() on it.
return false from the event handler.
Answer to your revised question: You are accepting the e parameter in the wrong function, you should accept it in the submit handler, not the ready handler.
I believe you need to cancel the form submission in your jquery. From the jQuery documentation:
Now when the form is submitted, the
message is alerted. This happens prior
to the actual submission, so we can
cancel the submit action by calling
.preventDefault() on the event object
or by returning false from our
handler. We can trigger the event
manually when another element is
clicked:
So in your code:
//add 'e' or some other handler to the function call
jQuery(document).ready(function(e){
jQuery('.appnitro').submit( function() { $.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
//return false
return false;
//or
e.preventDefault();
});
});