I need to get the html result of the ajax postback after changing the select option. The new-result-item is part of the new result div html which has a value generated from server side after ajax postback. The problem i am having here is if i call new-result-item is empty value although after ajax postback the value for new-result-item is actually display. So how can i get the new-result-item value after postback using javascript or jquery?
Note: new-result-item value is empty by default, it is generated by server side after ajax postback
<div id ="new-result">
<span id="new-result-value">#Model.NewResult</span>
</div>
$('select#select-option').change(function(){
$.ajax({
url: ...,
type: "POST",
cache: false,
success: function (result) {
$('#new-result').html(result);
},
complete: function (result) {
alert($('#new-result-item').val());
}
});
});
you can use the below sample code POST FORM DATA VIA ajax TO THE PHP PAGE it will work
<html>
<head>
<meta name="viewport" content="width=device-width">
<meta charset="utf-8">
<title>ajax test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#restaurant').change(function()
{
if ($(this).val() == "") {
document.getElementById("txtHint").innerHTML = "";
}
else
{
$.ajax({
url: "test.php",
data : "q="+$(this).val(), //if you want to pass one variable
//data : "name="+name+"&natives="+natives, //if you want to pass more than 1 variable
type : "POST", // if you want to pass data via get method put "GET"
success :function(text){
alert(text);
document.getElementById('txtHint').innerHTML=text;
}
});
}
});
});
</script>
</head>
<body>
<table>
<form>
<td>
<select name="restaurant" id="restaurant">
<option value="">selection</optoin>
<option value="101">DA</option>
<option value="102">FV</option>
<option value="103">CS</option>
<option value="104">TO</option>
</select>
</td>
</form>
</table>
<b>Select restaurant</b> <div id="txtHint"></div>
</body>
</html>
test.php code
<?php
echo $_POST['q'];
?>
The construct $('#new-result') parses the current document for an element with ID new_result. Same with new_result_item
You want to parse the HTML returned by the ajax call which is currently NOT in the dom of the current document. You may look at this stackoverflow:
....
success: function (result) {
alert($(result).find('#new-result-item').html());
}
....
may give you the inner content of the returned HTML snippet
Related
In the below Javascipt code I am sending data to a page named "book.php".It is succesfully sending the data through post method(because I am getting the alert) but when I open book.php to display the recieved data,It is not showing anything.
<script type="text/javascript">
$(document).on("click", ".open-AddBookDialog2", function (f){
var train_date=$(this).data('id');
$.ajax({
type: 'post', // the method (could be GET btw)
url: 'book.php', // The file where my php code is
data: {
'train_date': train_date // all variables i want to pass. In this case, only one.
},
success: function(data) { // in case of success get the output, i named data
alert("success"); // do something with the output, like an alert
}
});
});
</script>
Book.php is showing output as nothing.
Is there any way I can open the same page while sending post data to it?I want to use that $_POST variable to sql.
book.php-
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<style>
body {
background-image: url("rail.jpg");
background-color: #cccccc;
background-size: 100% auto;
background-repeat: no-repeat;
}
</style>
</head>
<body>
<p>
<?php
if(isset($_POST['train_date'])) { //if i have this post
// print it
echo $_POST['train_date']; }
else{
$var="nothing";
echo "nothing";
}
?>
</p>
</body>
</html>
Don't use XHR/Ajax. A simple solution is to create a hidden <form method="post"> element, create likewise hidden input fields for your data (in this case just train_date) fill it with values and then trigger the form submission using javascript. The browser will then be redirected as you request.
Example:
JS:
$(document).on("click", ".open-AddBookDialog2", function (f){
var train_date=$(this).data('id');
var hidden_form=$("#hidden-form");
var hidden_input=$("#hidden-form-input");
hidden_input.val(train_date)
hidden_form.submit()
});
HTML:
<form method="post" id="hidden-form" style="display:none" action="book.php">
<input id="hidden-form-input" name="train_date" />
</form>
Use ajax to send variable to php. In php stock that variable in a session (search around, is simple) then in your ajax success do a redirect: How to redirect to another webpage? . In php you will have now your var stocked in $_SESSION. Do what you need with it, manipulate the flow of execution with some if(isset()).
code lovers!
i want to send a value of input box to PHP and check the value on the PHP file. when the page is loaded. but i keep failing no matter what i try in various ways.
basically i want to send the value of this input box to PHP.
Current Counte : <input type="text" name="currentCount" id="currentCount" value="6">
<span> result </span>
and these are what i have tried so far but nothing really worked.
<script>
$( document ).ready(function() {
var currentCount = $("#currentCount").val();
console.log(currentCount);
$.post("counteSever.php", {currentCount2: currentCount},
function(result){
$("span").html(result);
});
});
</script>
Second One
<script>
$( document ).ready(function() {
var currentCount = $("#currentCount").val();
console.log(currentCount);
$.ajax({
url: 'counteSever.php',
type: 'POST',
data: {"currentCount2": currentCount},
dataType: 'JSON',
})
.done(function() {
console.log(currentCount + " Done");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
</script>
and Third one
$.ajax({
type: 'POST',
url: 'counteSever.php',
data : { "currentCount2" : currentCount},
dataType: 'JSON',
success: function(response){
$('span').text(name);
alert(response.data);
}
});
and my simple PHP file to check if the value is sent or not.
<?php
$current = $_POST['currentCount2'];
echo $current;
?>
Seriously don't know what's the problem, i don't have any problem to check the value on client-side, but it doesn't seem to send the value to PHP cos i keep having "Undefined index: currentCount2 " error.
if i don't have any problem with the ajax function? Thanks!
As i understood your question you want to send the value of input field to PHP file and receive it back and display in <span> tag.
So here are few minor changes you need to make. see my example below.
IN AJAX SUCCESS FUNCTION ,you can use these 3 ways to bind result to the <span> tag
1)$('span').text(response);
2)$('span').append(response);
3) $('span').html(response);
You will know the difference between them when to use those in these example
This is HTML file
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
Current Counte : <input type="text" name="currentCount" id="currentCount" value="6">
<br>
<span> result </span>
<script>
$(document).ready(function(){
var currentCount = $("#currentCount").val();
$.ajax({
type: 'POST',
url: 'counteSever.php',
dataType:'json',
data : {currentCount2 : currentCount},
success: function(response){
console.log(response);
$('span').append(response);
}
});
});
</script>
</body>
</html>
This is php File counteSever.php
<?php
$current = $_POST['currentCount2'];
echo $current;
?>
And here is the result image :
#james, Put the ajax code in bottom of your html file. You r using document.ready(). It will work:)
I'm test using ajax submit form (submit to myself page "new1.php")
The thing that I want is, after click submit button, it will echo firstname and lastname. But I don't know why I do not see the firstname and lastname after submit.
here is new1.php page
<?php
echo $_POST['firstname']."<br>";
echo $_POST['lastname']."<br>";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form id="myform" action="new1.php" method="post">
Firstname : <input type="text" name="firstname"> <br>
Lastname : <input type="text" name="lastname"> <br>
<input type="submit" value="Submit">
</form>
<script>
// this is the id of the form
$("#myform").submit(function(e) {
$.ajax({
type: "POST",
url: 'new1.php',
data: $("#myform").serialize(), // serializes the form's elements.
success: function(data)
{
alert('yeah'); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
</body>
</html>
In your case the best option to retrieve values as JSON format using json_encode in your PHP code and then accessing these values through data object.
Example:
PHP code:
if($_POST)
{
$result['firstname'] = $_POST['firstname'];
$result['lastname'] = $_POST['lastname'];
echo json_encode($result);
die(); // Use die here to stop processing the code further
}
JS code:
$("#myform").submit(function (e) {
$.ajax({
type : "POST",
url : 'new1.php',
dataType : 'json', // Notice json here
data : $("#myform").serialize(), // serializes the form's elements.
success : function (data) {
alert('yeah'); // show response from the php script.
// make changed here
$('input[name="firstname"]').text(data.firstname);
$('input[name="lastname"]').text(data.lastname);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
When you use form as a serialize you have to retrieve like this.
Edit your ajax like this :
data: { formData: $("#myform").serialize()},
Then you can retrieve like this in your controller:
parse_str($_POST['formData'], $var);
echo "<pre>";
print_r($var);
exit;
Make some changes in javascript here:
success: function(data)
{
$('#response').html(data); // show response from the php script.
}
And in html code make a div with id response
<div id="response"></div>
Change from
alert('yeah'); // show response from the php script.
to
alert(data); // show response from the php script.
the value firstname, lastname will not display because you called the new1.php via ajax and the data (firstname, lastname and the page code) is returned to java script variable (data) you need to inject the data to your document
Try this
$.ajax({
type: "POST",
url: 'new1.php',
data: $("#myform").serialize(), // serializes the form's elements.
success: function(data) {
document.documentElement.innerHTML = data;
}
});
I have this code in my JS function, I need to call a PHP file "valiadte-attrib-form.php" this PHP script returns a variable.
This is my HTML page:
<form method="post" id="form1" name="form1" action="<?php echo $editFormAction; ?>">
<script>
$(function() {
$('#form1').submit(function() {
return validateForm();
});
});
</script>
This is my JS code:
function validateForm() {
var form = $("#form1");
$.ajax({
context: form,
type: 'GET',
url: 'validate-attrib-form.php',
data: params,
success: function(response){
alert(response);
result=response;
return result;
}.bind(form)
});
This is my PHP code:
<?php
echo "false";
But my problem is when a I see alert(response); I see full HTML codelike this:
<!doctype html>
<html lang="es">
<head>
<meta charset="iso-8859-1"/>
<meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1"/>
.....
.....
What's wrong in my code? I need that alert(response) shows false not HTML code.
Thanks for your help!
You're getting a server error like a 400 or 500-series error ... Sometimes, depending on how the server is configured, this may look like a re-direct, at which point you may see a full HTML page without any error codes, like the main page of the site if the redirects are being done to suppress errors to end-users.
I'm also a little confused at the structure of your $.ajax call. You may want to change it to the following:
function validateForm() {
var form = $("#form1");
$.ajax({
/* context: form, //not sure you need that */
type: 'GET',
url: 'validate-attrib-form.php',
data: form.serializeArray(), /* turn the form data into an array */
dataType: "text",
success: function(response){
alert(response);
/* do other stuff... */
}
});
}
$("#form1").on("submit", function(ev) {
ev.preventDefault();
validateForm();
};
You don't need to specify a form action attribute if you are attempting to make an AJAX call to an endpoint.
I want to use an onclick event with PHP in order to accomplish the following. I would like to use ajax to avoid the page being refreshed. I want to create buttons on event click.
I don't know how to join the div buttons with the ajax result.
Here is my PHP file: Button.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dymanic Buttons</title>
<script type= "text/javascript" src ="jquery-2.1.4.min.js"></script>
<script type= "text/javascript" src ="test.js"></script>
</head>
<body>
<div>
<input type="submit" class="button" name="Add_Button" value="Add Button"</>
<input type="submit" class="button" name="Modify_Button" value="Modify Button"</>
<input type="submit" class="button" name="Delete_Button" value="Delete Button"</>
</div>
test.js contains this:
$(document).ready(function () {
$('.button').click(function () {
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {
'action': clickBtnValue
};
$.post(ajaxurl, data, function (response) {
alert("action performed successfully");
});
});
});
And the other php that is ajax.php
<?php
if (isset($_POST['action'])){
switch($_POST['action']){
case 'Add_Button':
Add_Button();
break;
}
}
function Add_Button(){
echo '<input type="submit" class="button" name="Test_Button" value ="Test Button"</>';
exit;
}
?>
You're calling the <input>'s value, instead of it's name which you set it as.
Change your clickBtnValue to this:
var clickBtnValue = $(this).attr('name');
Since it has Add_Button/Modify_Button/etc.
To append the new button to your div, start by giving it an id, so that we can continue to call it:
<div id="my-buttons">
Now in your ajax request, simply jQuery.append() the html to the div:
$.post(ajaxurl, data, function (response) {
$('div#my-buttons').append(response);
});
You can add the result of request to your div with this:
$.post(ajaxurl, data, function (response) {
$("div").append(response);
alert("action performed successfully");
});
Note the value of your button is "Add Button", not "Add_Button"
You probably want to make sure that each component of your code is working first. The problem may be in your AJAX call, it should be similar to the following:
/** AJAX Call Start **/
// AJAX call to dict.php
$.ajax({
/** Call parameters **/
url: "ajax.php", // URL for processing
type: "POST", // POST method
data: {'action': clickBtnValue}, // Data payload
// Upon retrieving data successfully...
success: function(data) {}
});
Also, make sure you are using the correct routing to your PHP file and that your PHP file is returning a valid response.
EDIT: As per the jQuery Docs, I am fairly certain that the problem is within your AJAX call, specifically your $.post() setup. Please refer here for the proper setup is you want to keep your AJAX call structured as is instead of the way I suggested.
As per the jQuery Docs:
$.post( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
});