$ajax success response print HTML page - javascript

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.

Related

Sending POST parameters between PHP files using AJAX calls

I have a PHP file test.php that has a simple link, which after being clicked, calls an AJAX function to send data as POST parameters to another file testPHP.php. The second file then receives the POST parameters from the AJAX call and then alerts the contents inside the $_POST array. The issue I am facing is that in the second file, the $_POST array is empty (I checked that using print_r($_POST)), so I think that the data hasn't passed through.
These are the 2 files:
test.php
<a id="link" role="button" href="testPHP.php">Test</a>
<script type="text/javascript">
$("#link").click(function(e) {
e.preventDefault();
alert('function entered');
$.ajax({
url: "testPHP.php",
type: "POST",
data: {
parameter1: 'test',
parameter2: 'test2'},
success: function(msg) {
alert('wow' + msg);
}
});
alert('function end');
document.getElementById('#link').setAttribute('href','testPHP.php');
});
testPHP.php
if(isset($_GET))
{
echo "<script>alert('GET is there');</script>";
print_r($_GET);
}
if(isset($_POST))
{
echo "<script>alert('POST is there')</script>";
print_r($_POST);
}
if(isset($_POST['parameter1']))
{
echo "<script>alert('$_POST is set')</script>";
header('Location: HomePage.php');
}
else
{
echo "<script>alert('No post variable set')</script>";
}
What I have tried so far is to send a SUCCESS message if the AJAX call has been executed successfully, and it does alert me the Success message. I have also checked to see the contents of the $_POST array in the 2nd file to see if I am receiving data in a format other than a POST request (like a string that might have to be exploded to get the contents), but the $_POST array comes up empty.
This is the output I get when it redirects to the 2nd page:
Array() Array()
The $_POST and $_GET (for testing purpose) arrays come up empty.
I have also gone through the AJAX documentation, but can't get this simple POST data transfer to work. Can someone please help me with this issue so that I can understand how to properly send POST parameters and receive the data into $_POST['parameter1'] and $_POST['parameter2'] strings so I can process the data further.
Note: I have used the FORM's POST method using hidden form elements and that works fine, but I want to try this approach to better understand how AJAX works.
A slightly different version of the above which should help you solve your problem. For ease in debugging it is all one page but you can clearly see the script in operation once you click the button. Simply echoing javascript in the php code and hoping it will execute client side is not going to work - simply echo a message or a JSON object would be better.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
print_r( $_POST );
exit();
}
?>
<!doctype html>
<html>
<head>
<title>jQuery - ajax experiments</title>
<script src='//code.jquery.com/jquery-latest.js'></script>
</head>
<body>
<a id='link' role='button' href='#'>Test</a>
<script>
$('#link').click(function(e) {
e.preventDefault();
alert('function entered');
$.ajax({
url: location.href,
type: 'POST',
data: {
parameter1: 'test',
parameter2: 'test2'
},
success: function(msg) {
alert( 'wow' + msg );
}
});
alert('function end');
});
</script>
</body>
</html>
As 2 separate pages ( both in same directory otherwise edit page to the ajax target )
<!doctype html>
<html>
<head>
<title>jQuery - ajax experiments</title>
<script src='//code.jquery.com/jquery-latest.js'></script>
</head>
<body>
<a id='link' role='button' href='#'>Test</a>
<br /><br />
<script>
$('#link').click(function(e) {
e.preventDefault();
$.ajax({
url: 'jquery-ajax-target.php',
type: 'POST',
data: {
parameter1: 'test',
parameter2: 'test2'
},
success: function(msg) {
alert( 'wow' + msg );
}
});
});
</script>
</body>
</html>
And the ajax target, jquery-ajax-target.php
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
$parameter1=( isset( $_POST['parameter1'] ) ) ? $_POST['parameter1'] : false;
$parameter2=( isset( $_POST['parameter2'] ) ) ? $_POST['parameter2'] : false;
$_POST['modified']=array(
'p1'=>sprintf('modified %s', strrev( $parameter1 ) ),
'p2'=>sprintf('modified %s', strrev( $parameter2 ) )
);
$json=json_encode( $_POST );
echo $json;
exit();
}
?>
Here is my version. It will return a JSON response to your ajax which will be visible in your console for easy debugging.
Your main page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="link" role="button" href="#">Test</a>
<script>
$(document).ready(function(){
$("#link").click(function(e) {
e.preventDefault();
console.log('function entered');
$.ajax({
url: "testPHP.php",
type: "POST",
dataType: 'json', //This tells your ajax that you are expecting a json formatted string as a response.
data: {
parameter1: 'test',
parameter2: 'test2'
},
success: function(msg) {
console.log(msg); //This will show the results as an object in your console.
}
});
console.log('Function End');
//document.getElementById('#link').setAttribute('href','testPHP.php'); //Why are you doing this. It's not needed.
});
});
</script>
Your testPHP.php page:
$results = array();
if(isset($_GET)){
$results[] = array(
'GET' => 'TRUE',
'getData' => $_GET
);
}
if(isset($_POST)){
$results[] = array(
'POST' => 'TRUE',
'postData' => $_POST
);
}
echo json_encode($results);
Here is an explanation of what is happening:
You make an initial call to your ajax by triggering some event. In your case it is the click of the link.
The click function leads to the actual ajax call which simply sends a post request to the testPHP.php.
The testPHP.php receives the post request and performs some sort of operation with the data that was provided by the ajax call.
The testPHP.php then sends back some sort of answer back to the ajax function. The data will be available in the success function.
You then get to decide how to use the data that was passed back from the testPHP.php page to the success function.
This is all done without your original page's code being refreshed.
You are not actually redirecting your user to another page.. You are just telling your page to goto another page and do some operation, which then gets reported back to the original page for you to do something with.
Hope it helps.
It does work after removing type attribute on script tag. I am using <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> before main script tag. It is working here. Also close the script tag. I hope I can help.
Also change the
document.getElementById('#link').setAttribute('href','testPHP.php');
to
document.getElementById('link').setAttribute('href','testPHP.php');
The problem with your code is that you are using javascript to change the attribute and in javascript once you used getElementById you no longer have to use # sign. try the following and it will work fine.
<?php
if(isset($_GET))
{
echo "<script>alert('GET is there');</script>";
print_r($_GET);
}
if(isset($_POST))
{
echo "<script>alert('POST is there')</script>";
print_r($_POST);
}
if(isset($_POST['parameter1']))
{
echo "<script>alert('$_POST is set')</script>";
header('Location: HomePage.php');
}
else
{
echo "<script>alert('No post variable set')</script>";
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="link" role="button" href="index2.php">Test</a>
<script type="text/javascript">
$("#link").click(function(e) {
e.preventDefault();
alert('function entered');
$.ajax({
url: "testPHP.php",
type: "POST",
data: {
parameter1: 'test',
parameter2: 'test2'},
success: function(msg) {
alert('wow' + msg);
}
});
alert('function end');
document.getElementById('link').setAttribute('href','testPHP.php');
});
</script>
</body>
</html>
Furthermore it's a good practice to use the failed callback for the request.
error: function (xhr, status, error) {
alert(" Can't do because: " + error);
},

ajax submit form why it cannot echo $_POST

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;
}
});

Adding additional information to Simple Jquery FileUpload

I'm trying to integrate juqery fileupload with an ajax form submit. The ajax form sends the text and returns the ID of the newly created event, This is necessary to know which event to link with when uploading.
The simple upload demo uses the following code
Here's the ajax that first upload the non-file fields
$.ajax({
type: 'post',
url: '/whats-on/upload-event/',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (return_data) {
console.log(return_data)
}
});
It returns the following json
Object {status: true, id: 17162}
However the fileupload sends the files without declaring data: data,
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>jQuery File Upload Example</title>
</head>
<body>
<input id="fileupload" type="file" data-url="server/php/">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="js/vendor/jquery.ui.widget.js"></script>
<script src="js/jquery.iframe-transport.js"></script>
<script src="js/jquery.fileupload.js"></script>
<script>
$(function () {
$('#fileupload').fileupload({
dataType: 'json',
done: function (e, data) {
//Returns ID as e['id'] and 200 status also with e['status']
}
});
});
</script>
</body>
</html>
You first need to get the event Id with an ajax post:
function uploadClick(){
var eventId = getEvent();
uploadFile(eventId)
}
function getEvent(){
// make an ajax and return your id
}
One you got it, then create an URL with a query string indicating the eventId. this URL is where you want to post your file:
function uploadFile(eventId){
// attatch the id to the URL with query string
url = url + '&eventId=' + eventId;
// submit here your file
}
This way you can post in the same ajax call the file itself and the event id. In you server side action you need to get this query string and then pick the posted file.
You may have to handle callbacks for fileupload plugin like:
$('#fileupload').fileupload({
url: <url>,
type: <HTTP_VERB>,
other configurations...
}).bind('fileuploadadd', function (e, data) {
//fires when you select a file to upload
}).bind('fileuploaddone', function (e, data) {
//fires when upload completed successfully. equivalent to done call back of jQuery ajax
}).bind('fileuploadfail', function (e, data) {
//fires when upload fails
});
For complete reference please take a look at the following link .

Ajax Automatic Div Update w/out page refresh won't work

I am struggling to figure out why this is not working, but I would like it so that the information from load.php is placed in the div sample but if that code is updated (say if i was pulling information from a database), only the information included in load.php would refresh - not the entire page.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script>
<script>
$(document).ready(function(){
var callAjax = function(){
$.ajax({
method:'get',
url:'load.php',
success:function(data){
$("#sample").html(data);
}
});
}
setInterval(callAjax,5000);
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id='sample'>100 </div>
</body>
</html>
I had a similar situation with my AJAX calls. I am not sure if your syntax is actually bad but here is how my Ajax call looks for a similar partial load.
var callAjax = function(){
$.ajax({
url: "load.php"
type: "GET",
async: true,
success: function (data) {
$("#sample").html(data);
}
});
}
};
setInterval(callAjax,5000);
I found that my Ajax started working once I added the async:true and made sure my controller was handling GET requests. I had previously forgotten that it was set to HTTPPOST only.
I hope this helps out. Not sure if it will.
cheers.
setInterval('someFunc()', 1000);
function someFunc()
{
$.ajax({
async: true,
type: "GET",
url: "www.domain.com/url",
data: data,
success: function (html) {
$("#myDiv").html(html);
}
});
}

getting value of html result after ajax postback

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

Categories

Resources