My objective with this code is when an user click in edit button, is sent this all=<?php echo $arr; ?> to the page edit.php .
This code simply does nothing (no ajax call in firebug).
<?php
$arr = array("one", "two", "three")
?>
<div id="content">
<input class="edit" type="submit" value="Edit" />
</div>
<script type="text/javascript">
$(document).ready(function () {
$(".edit").submit(function () {
$.ajax({
url: "edit.php",
type: "post",
dataType: "html",
data: "<?php echo json_encode( $arr ); ?>",
success: function (data) {
$('#ad').html(data);
}
});
});
});
</script>
Edit As #MilanJaric showed, you do need to operate on the click of the submit button. In addition, however, you should prevent the default action of the click as well. End Edit
You need to echo the data json_encoded and wrapped in quotes:
<div id="content">
<input class="edit" type="submit" value="Edit" />
</div>
<script type="text/javascript">
$( function()
{
$( '.edit' ).click( function( e )
{
$.ajax( {
url: 'edit.php;,
type: 'post',
dataType: 'html',
data: '<?php echo json_encode( $arr ); ?>',
/* It's hard to tell based on your code, but if you wanted a var at the server named "all" use this instead of the above line:
data: {
all: '<?php echo json_encode( $arr ); ?>'
},
*/
success: function( data )
{
$( '#ad' ).html( data );
}
} );
e.preventDefault();
} );
} );
</script>
IMO, however, it gets real ugly to echo PHP inside your JS especially if you have to do a lot of it, so when the need arises, I use an IIFE to inject PHP data into the code as a JS var. This allows me to isolate all PHP echoing within the parens of the invocation of the IIFE:
<?php
$arr = array("one", "two", "three")
?>
<div id="content">
<input class="edit" type="submit" value="Edit" />
</div>
<script type="text/javascript">
( function( arr )
{
$( function()
{
$( '.edit' ).click( function( e )
{
$.ajax( {
url: 'edit.php;,
type: 'post',
dataType: 'html',
data: arr,
/* It's hard to tell based on your code, but if you wanted a var at the server named "all" use this instead of the above line:
data: {
all: arr
},
*/
success: function( data )
{
$( '#ad' ).html( data );
}
} );
e.preventDefault();
} );
} );
}(
'<?php echo json_encode( $arr ); ?>'
) );
</script>
In addition to what the other folks pointed out regarding the need to json_encode() your $arr, the jQuery documentation for .submit() points out the following:
The submit event is sent to an element when the user is attempting to
submit a form. It can only be attached to <form> elements.
So I believe the reason the AJAX isn't even being submitted is that your <input> element is not within a <form> element. Try the following:
<?php
$arr = array("one", "two", "three");
?>
<form id="content">
<input class="edit" type="submit" value="Edit" />
</form>
<script type="text/javascript">
$(document).ready(function () {
$(".edit").submit(function () {
$.ajax({
url: "edit.php",
type: "post",
dataType: "html",
data: "all=<?php echo json_encode($arr); ?>",
success: function (data) {
$('#ad').html(data);
}
});
});
});
</script>
The JavaScript submit event only occurs on a <form> not on individual <input>s.
You need the following HTML:
<div id="content">
<form id="whatever">
<input class="edit" type="submit" value="Edit" />
</form>
</div>
And in the JavaScript change:
$( '.edit' ).submit( function()
to
$( '#whatever' ).submit( function()
<script type="text/javascript">
$(document).ready(function () {
$(".edit").click(function () {
$.ajax({
url: "edit.php",
type: "post",
dataType: "html",
data: "all=<?php echo $arr; ?>",
success: function (data) {
$('#ad').html(data);
}
});
});
});
</script>
Use a json_encode to encode php array to json string
http://php.net/manual/en/function.json-encode.php
You're echoing an Array, which will make PHP echo something like Array(), in stead of the true values.
Try var_dump($arr); to dump the array, and eventually try serialising the array, easier to retrieve its state later.
If the ajax call does work with static data, then this is where you should start looking.
Related
My ajax successfully return the value but my problem is I can't use the value to my function. How do I convert this div to a value?
<?php
echo $ajax_user_id = '<div id="result"></div>'; //value can display here
getName($ajax_user_id); //value wont work here
?>
<form method="post" id="registerSubmit">
<input type="text" name="user_id" id="user_id">
<button id="submit" type="submit">Submit</button>
</form>
<script>
$(document).ready(function(){
$("#registerSubmit").submit(function( e ) {
e.preventDefault();
$.ajax({
url: "test.php",
method: "post",
data: $(this).serialize(),
dataType: "text",
success: function(Result) {
$('#result').text(Result)
}
})
});
});
</script>
You can't use it that way.because jQuery is a scripting language which runs in browser when DOM is fully loaded and elements are available to make selectors.While php is server side language which runs on server way before page load.anyway to fulfill your need you can try something like this.
<form method="post" id="registerSubmit">
<input type="text" name="user_id" id="user_id">
<button id="submit" type="submit">Submit</button>
</form>
<script>
$(document).ready(function(){
$("#registerSubmit").submit(function( e ) {
e.preventDefault();
$.ajax({
url: "test.php",
method: "post",
data: $(this).serialize(),
dataType: "text",
success: function(Result) {
$('#result').text(Result);
getNameAjax(Result);
}
})
});
});
function getNameAjax(val)
{
$.ajax({
type: "POST",
url: GetNameAjax.php,
data:{'user_id':val},
success: function(res){
$('#name').html(res);
}
});
}
</script>
GetNameAjax.php file you can write like this
$ajax_user_id=$_POST['user_id'];
function getName($ajax_user_id)
{
return "name on the basis of id";
}
I want to use the first 3 result of my Json array in 3 different divs.
The array returned from ajax.php look like this:
'{"res":["106"],"base":["190220"]}'
So I want the first value "res":["106"] in the div id: Response1 and "base":["190220"] in the div id : Response2.
My knowledge of this is only 1% so I need some help from you guys :)
html and ajax:
<!DOCTYPE html>
<html>
<form id="resource">
<input type="number" id="base" name="base" placeholder="Base ID" value="170143" />
<input type="number" id="lot" name="lot" placeholder="Lot ID" value="110"/>
</form>
<div id="response1"></div>
<div id="response2"></div>
<div id="response3"></div>
<script src="../vendor/jquery/jquery.min.js"></script>
<script>
(function($){
function processForm( e ){
$.ajax({
url: 'ajax.php',
dataType: 'html',
type: 'post',
data: $(this).serialize(),
success: function( data ){
$('#response1').html( data );
console.log( data );
}
});
e.preventDefault();
}
$('#resource').change( processForm );
})(jQuery);
</script>
</body>
</html>
Here my ajax.php file:
<?php
require_once('background.php');
if(isset($_POST['base']) and isset($_POST['lot'])){
$base = $_POST['base'];
$lot = $_POST['lot'];
$baseSql = "SELECT * FROM QBS_ABL_VMSCHRP1_SIM where WORKORDER_BASE_ID = '".$base."' AND WORKORDER_LOT_ID = '".$lot."'";
$baseSTH = $pdo->prepare($baseSql);
$baseSTH->execute();
while($row = $baseSTH->fetch(PDO::FETCH_ASSOC)){
$resArray['res'][] = $row['RESOURCE_ID'];
$resArray['base'][] = $row['WORKORDER_BASE_ID'];
}
if(isset($resArray)){
json_encode($resArray);
}
}
?>
Solved it by changing this:
(function($){
function processForm( e ){
$.ajax({
url: 'ajax.php',
dataType: 'json',
type: 'post',
data: $(this).serialize(),
success: function( data, textStatus ){
res = (data['res']);
base = (data['base']);
$('#response1').html( res );
$('#response2').html( base );
//console.log( data );
}
});
e.preventDefault();
}
$('#resource').change( processForm );
})(jQuery);
As the title says, i have try many times to get it working, but without success... the alert window show always the entire source of html part.
Where am i wrong? Please, help me.
Thanks.
PHP:
<?php
if (isset($_POST['send'])) {
$file = $_POST['fblink'];
$contents = file_get_contents($file);
echo $_POST['fblink'];
exit;
}
?>
HTML:
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
</head>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</html>
Your Problem is that you think, that your form fields are automatic send with ajax. But you must define each one into it.
Try this code:
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: {
send: 1,
fblink: fbvideo
},
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
Instead of define each input for itself, jQuery has the method .serialize(), with this method you can easily read all input of your form.
Look at the docs.
And maybe You use .submit() instead of click the submit button. Because the user have multiple ways the submit the form.
$("input#invia").closest('form').submit(function(e) {
You must specify the url to where you're going to send the data.
It can be manual or you can get the action attribute of your form tag.
If you need some additional as the send value, that's not as input in the form you can add it to the serialized form values with formSerializedValues += "&item" + value;' where formSerializedValues is already defined previously as formSerializedValues = <form>.serialize() (<form> is your current form).
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("#invia").click(function(e) {
e.preventDefault();
if (!confirm('Are you sure?')) {
return false;
}
// Now you're getting the data in the form to send as object
let fbvideo = $("#videolink").parent().serialize();
// Better if you give it an id or a class to identify it
let formAction = $("#videolink").parent().attr('action');
// If you need any additional value that's not as input in the form
// fbvideo += '&item' + value;
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
// dataType: "html",
// url optional in this case
// url: formAction,
success: function(test){
alert(test);
}
});
});
});
</script>
</head>
<body>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</body>
I'm trying to get data via ajax then send it through a form. However it doesn't seem to be working. Any ideas what im doing wrong?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<form method="get" action="test.php">
<input id="myvar" type="hidden" name="albumid" />
<button type="submit" id="btnsubmit">Submit</button>
</form>
<script type="text/javascript">
$('form').submit(function() {
$.ajax({
url: "newAlbum.php",
success: function(data){
var album = data;
$('#myvar').val(album);
}
});
});
</script>
newAlbum.php
<?PHP echo '11'; ?>
test.php
<?php echo $_GET["albumid"]; ?>
Okay try adding as follows:
$('form').submit(function() {
$.ajax({
url: "newAlbum.php",
async:false,
success: function(data){
var album = data;
$('#myvar').val(album);
}
});
});
As someone else pointed out - you need to add the data parameter. But I would also use $(this).serialize(), since that will fetch all form input elements.
<script type="text/javascript">
$('form').submit(function() {
$.ajax({
url: "newAlbum.php",
data: $(this).serialize(),
success: function(data){
var album = data;
$('#myvar').val(album);
},
error : function(data) {
console.log(data);
}
});
});
</script>
Try receiving the data as JSON
$.getJSON()
I am trying to submit a form that only has a radiobutton group with name=radiob. This is the script I am using for submitting data:
<script type="text/javascript">
$(function() {
$("#myForm").submit(function() {
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "index.php?p1=<?php echo $_GET['p1']; ?>",
data: dataString,
success: function() {
$("#ppm").fadeOut("slow");
$("#ppmPlugin").load('?p1=<?php echo $_GET['p1'];?>&result=true');
}
});
return false;
});
});
</script>
But this is what I get in my PHP script:
$_POST array - empty
Array ( )
$_GET array
Array ( [p1] => xxx [result] => true )
But if I alert(dataString); I get radiob=2, that is, the value depending on the radiobutton selected..
How do I fix this problem?
I've tested your code and it works fine. Perhaps you have some kind of redirect in index.php?p1=xxx.
P.S. Tested with this code:
<?php $_GET['p1'] = 1; ?>
<form id="myForm">
<input type="radio" name="radiob" value="1" />
<input type="radio" name="radiob" value="2" />
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
$(function() {
$("#myForm").submit(function() {
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "index.php?p1=<?php echo $_GET['p1']; ?>",
data: dataString,
success: function(data) {
alert(data);
}
});
return false;
});
});
</script>
And in index.php I have
<?php var_dump($_GET, $_POST); ?>