Before I opened this question, I searched the entire internet on a solution. Maybe it is me or my solution. Sorry for that.
The situation is, I have a web app which is build with PHP and interacting with the database through functions. Every page is a php in which html code is executed.
The problem is, when I want to implement Ajax to update data without refreshing a page, the PHP file is not being executed when the button is clicked.
The javascript has two functions:
Alert serialized data of the button (works)
Run php script with Ajax (doesn't work)
Html Header
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- JQuery -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous">
Im using bootstrap-table, one of the column is a button which has the following content:
<form id="form" class="favourite-form" method="post"><input style="display:none" type="hidden" id=5 name="subject_id" value=5 ><input type="submit" name="submit" value="Button"></form><div id="response"></div>
When clicked on the button the following alert is popping up:
The script file is included in the php file:
include("favorite_ajax.html");
The script file has the following content:
$(document).on('submit', '.favourite-form', function(e) {
e.preventDefault(); //prevent a normal postback and allow ajax to run instead
var data = $(this).serialize(); //"this" represents the form element in this context
alert(data); // this alert works
$.ajax({
method: "POST",
url: "process.php", // calling this php file doens't work
data: data,
success: function(data) {
alert("Data Save: " + data);
},
error: function(jqXHR, textStatus, errorThrown) //gracefully handle any errors in the UI
{
alert("An ajax error occurred: " + textStatus + " : " + errorThrown);
}
});
});
Finally the php file has one single simple function which inserts (dummy) data. The php file is tested and does not contain any errors.
<?php
insertDummyData(1, 123);
?>
In another topic I also read checking the logs. When I press the button, there is also no record being added in the logs.
Im cursious, what am I doing wrong? Spend like days to fix this, until now no results :(
put an error log in "process.php" to make sure that it's actually being called, if it's not being called, as others suggest, you may have path, permissions or script errors.
what does insertDummyData/process.php actually do? It must echo something as if it were writing to the page for the AJAX call to get a non-empty result. For example, in process.php
<?php
$new_data = my_function_which_does_stuff_to_posted_data($_POST['data']);
echo json_encode($new_data);
exit();
Related
I have a small requirement that needs to make REST API POST call using HTML code. I have copied the sample code below and some reason this is not working. I am unable to see any call using the below code. Please let me know If there is any change required in the code.
<html>
<head>
<title>My first API script</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<H1>Testing the API call</h1>
<form>
<label for="msg">Message</label>
<button id='submitButton'>Submit</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var API_URL = 'https://example.com/'; // this will be my API like https://example.com
$('#submitButton').on('click', function(){
$.ajax({
type: 'POST',
url: API_URL,
data: JSON.stringfly({"message": $('#msg'.val())}),
contentType: "application/json",
success: function(data){
location.reload();
}
})
})
</script>
</body>
</html>
Rewrite $('#msg'.val()) to $('#msg').val(), and implement an error(xhr, textStatus, errorThrown) function in .ajax too so you'd catch the error next time.
Several things need to be fixed in your code. Not sure if that's the one you're actually using but:
Change stringfly to stringify.
label doesn't have an id="msg" but you're trying to access it with #msg.
Add a e.preventDefault() on your click callback function. Make sure to receive e as parameter.
label-s don't have a val() function. If you're trying to get the "Message" inside the label, use $('msg').text().
Try using API placeholders like JSONPlaceholder instead of example.com so you don't get CORS errors.
Finally, add an error callback to your AJAX so you can catch and handle errors.
I have searched for this answer and it seems that it should be simple, based on DOM.
What I want to do is display a <td id="cte"> or <input id="cte"> on a page and after some action (i.e. button click OR onchange ) the getElementById('cte').value="somenewvalue" ACTUALLY changes the forementioned or element on the same page.
The technology (i.e. javascript, AJAX, DOM) says that this is doable, yet I have seen this question asked numerous ways where the answers supplied never seem to work or satisfy the question.
So my actual question is: How do I change the 'displayed' element.value on the same page without having to reload the same page?
Do you think of elements consist several values/texts? (like a table)
//emty the element really at first if the element consists several values
var forempty = document.getElementById("cte");
while( forempty.firstChild ){
forempty.removeChild(forempty.firstChild);
}
document.getElementById("cte").value = something;
//or
document.getElementById("cte").textContent = something;
You answered your own question at least in one way: "The technology (i.e. javascript, AJAX, DOM) says that this is doable. And sure enough, with AJAX, it is only a matter of replacing the DOM Node with the Data (Response) from AJAX Request...
Here is a very Basic Example. We will fetch an HTML String using AJAX from the Server and use this Contents to replace the former Contents of a DIV, which contains the HTML < strong>Hello< /strong>
The first part of this Demo is our HTML or PHP Document containing our initial Markup and this File, we'd call index.html or index.php
CONTENTS OF index.php | index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mini AJAX Demo</title>
</head>
<body>
<div class="swappable-content" id="swappable-content">
<strong>Hello!!!</strong>
</div>
<div class="other-dom-elements">
<Button id="action-trigger" data-ajax-url="/ajax.php">Click Me</Button>
</div>
<!-- ADD JQUERY LIBRARY & SETUP THE AJAX REQUEST CALLS -->
<!-- HERE WE ARE LOADING JQUERY FROM THE CDN.... CHANGE THE src ATTRIBUTE IF YOU HAVE A LOCAL COPY -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
(function($){
$(document).ready(function(e){
var actionTrigger = $("#action-trigger");
actionTrigger.on("click", function(e){
$.ajax({
url : $(this).attr('data-ajax-url'),
type : "POST",
dataType : "JSON",
data : {
// HERE YOU CAN ADD KEY VALUE PAIRS
// WHICH WILL BE SENT TO AND PROCESSED BY THE SERVER
},
success : successHandler,
error : errorHandler,
complete : completeHandler
});
});
function successHandler(data, textStatus, jqXHR){
// IF THERE IS A RESPONSE PAYLOAD FROM THE SERVER
// WE JUST REPLACE THE CONTENTS OF THE #swappable-content DIV WITH THE DATA
if(data){
if(data.html){
$("#swappable-content").html(data.html);
}
}
}
function errorHandler(jqXHR, textStatus, errorThrown){
console.log('The following error occured: ' + textStatus, errorThrown);
}
function completeHandler(jqXHR, textStatus){
}
});
})(jQuery);
</script>
</body>
</html>
CONTENTS OF AJAX PROCESSING SCRIPT: ajax.php
<?php
// YOU CAN DO PRETTY MUCH ANYTHING WITHIN THIS FILE
// HOWEVER FOR THE PURPOSES OF THIS DEMO,
// WE WOULD JUST RETURN SOME HTML STRING BUNDLED IN AN ARRAY AND SENT AS JSON DATA
$response = array(
'html' => "<div style='font-weight:900;color:#F00;'>This is the Response Data from Server!</div>",
);
die(json_encode($response));
I know there's a lot of similar questions here, but I looked up over 20 of them, and no solutions worked for me.
Here's the problem: I'm sendind an ajax post value to my index.php. When I look at Firebug, the value is there, but when I try to echo it on the page, the POST is empty. I'm really stucked on this.
Here's my full code:
<?php
if(isset($_POST['action']))
{
echo $_POST['action'];
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
<!-- JQUERY LIBRARY AND SCRIPTS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
Test
<script type="text/javascript">
$(document).ready(function()
{
$('a').on('click', function()
{
$.ajax({
url: 'index.php',
type: 'POST',
data: {action: 'clicked'},
success: function(data)
{
console.log(data);
alert('Done!');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
return false;
});
});
</script>
</body>
</html>
This code does not try to print that to the page, but simply prepends the whole HTML document with a "clicked" string, in the ajax response. If you want to show this in the browser, you need print that data to the page. If you inspect the console in FireBug, you will see that the response for the Ajax call is exactly what I described above.
Now if you want to print that value back to your page, here is my suggestion, you create a separate file, ajax.php:
<?php
if(isset($_POST['action']))
{
echo $_POST['action'];
}
?>
And fix your index.php to include some element where you are going to print that value to. I.e. add <div id="response-results"></div> just after your element. Then change your Ajax call to go to ajax.php, not index.php.
Now you need to populate that Ajax response to the rendered page, and this can be done simply with jQuery like:
$("#response-results").html(data);
Ofcourse, this goes into the success handler of the ajax call.
As Jay Blanchard said
You're using AJAX to send a a variable to a page which is already rendered on your browser. This will never work because the PHP your're getting the variable from has been run server-side and returned via AJAX, not in the page you're currently viewing.
Try this it will work :
index.php :
<?php
if(isset($_POST['action']))
{
echo $_POST['action'];
}
?>
main.html :
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
<!-- JQUERY LIBRARY AND SCRIPTS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
Test
<div id="result"></div>
<script type="text/javascript">
$(document).ready(function()
{
$('a').on('click', function()
{
$.ajax({
url: 'index.php',
type: 'POST',
data: {action: 'clicked'},
success: function(data)
{
// console.log(data);
$("#result").html(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
return false;
});
});
</script>
</body>
</html>
As R J commented, it's impossible to do what I was trying to.
That happens because once my page is loaded, the top PHP script is proccessed, but there's nothing on my POST.
After my call to Ajax, the page is rendered again but the top PHP script will get nothing cause it's SERVER SIDE. Turns out that I even could print out my Ajax data on the page, but the PHP $_POST would never get its value.
Thank you guys.
I have developed an ASP.NET MVC application that will run several prescreen functions based on user input.
The plan is to call this new mvc app from an existing HTML/JavaScript application. I would like to display the controllers's view in a new browser window outside of the calling application.
My AJAX call will look something like this
$.support.cors = true;
$.ajax( {
url: "http://mvc_url/prescreen",
data: jsonObject,
type: "POST",
processData: false,
dataType: 'html',
contentType: "application/json; charset=utf-8",
timeout: 60000,
//dataType: "json",
success: function ( msg )
{
...on success msg = html rendered from view...
},
error: function ( XMLHttpRequest, textStatus, errorThrown )
{
...error handling...
}
} );
I've tested this and on success msg does contain the fully rendered HTML from the view. My question is how do I open a new window using the rendered HTML?.
I've tried the following:
var newWindow = window.open( "", "", "" );
newWindow.document.write( msg );
and that seems to work. sort of. The new window opens and the html is displayed, but then my style sheets and included javascript files, for the view, are missing. So if using the above window.open code is correct, then how do I bring down the necessary stylesheets and javascript files?
EDIT
Utilizing the suggestion provided by AndyJ, I've modified my view to include relative paths based on my base application. Here is the returned mark up from my MVC
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Offer</title>
<link href="../css/site.css", type="text/css" rel="stylesheet" />
</head>
<body>
<div class="container body-content">
... Page Content ...
<script src="/baseapp/Scripts/jquery-1.8.2.js" type="text/javascript"></script>
<script src="/baseapp/js/someInclude.js" type="text/javascript"></script>
<script type="text/javascript">
InitializeForm();
</script>
the InitializeForm method is defined within the someInclude.js.
Based on the above and assuming the files are locates in the paths, everything should link up, correct? So what else might I be doing wrong?
In addition to the help provided by Andy J (Thank you), I also found that when the response was rendered in the new window, the JQuery library was loading AFTER my initialization script. To circumvent this, I simply added my event handlers to the inline attributes of the controls.
This may be a work around, but for now it seems to be working for me.
If you are returning raw HTML in the AJAX request you will probably need to add the CSS and JS references there. You are not really returning a view that would normally have a layout that includes the references.
I have the following html page Index.html , script.js and calculate.jsp file when i run the html page and hit submit button using tomcat server it gives error saying calculate.jsp file not found .Is their any syntax problem in the javascript file to call the jsp page .
<html>
<head>
<title>Simple jQuery and JSP example</title>
<script src="jquery-1.4.2.js" type="text/javascript"></script>
<script src="SCRIPT.js" type="text/javascript"></script>
</head>
<body>
<form id="form" action="calculate.jsp" method="post">
Enter number:
<input id="number" type="text" name="number" />
<input id="submit" type="submit" value="Calculate Square Root" name="submit"/>
</form>
<p id="result"></p>
</body>
</html>
Javascript file SCRIPT.js
$(document).ready(function() {
$('#form').submit(function() {
var number = $('#number').val();
$.ajax({
type: "post",
url: "calculate.jsp",
data: "number=" + number,
success: function(msg) {
$('#result').hide();
$("#result").html("<h3>" + msg + "</h3>")
.fadeIn("slow");
}
});
return false;
});
});
calculate.jsp
<?xml version="1.0" encoding="UTF-8" ?>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
int number = 0;
if(request.getParameter("number").matches("[\d]+")) {
number = Integer.parseInt(request.getParameter("number"));
out.println("Square root of " + number + " is " + Math.sqrt(number));
}
else {
out.println("Enter a number!");
}
%>
Here are some steps you can do to find out what is going wrong :
Add a console.log("submitting the form") at the first line in $('#form').submit function.
Add another print console.log("got message") in the "success" callback.
You can use chrome, Firefox+Firebug or IE 8 and above for this.
I usually use chrome and my following instructions refer specifically to chrome as it is easiest with it.
Click ctrl+j in chrome to open the developer's panel.
Go to 'Network'.
Reload "index.html" (your main page)
Make sure there are no errors displayed in the console below. ( if there are please post them here or handle them).
Assuming there are no errors : you should see your print "submitting the form" and a network call to "calculate.jsp" on the developers panel.
you can click on it to see the details - see the URL you are actually requesting for. is this the URL you expected?
Copy paste the URL you see and copy it on a new tab. This will give you a sufficient workspace to handle any problems on that page.
The above steps should give you sufficient clues as to what is the problem and how to resolve it.
In order to verify that your code is working properly - you should see your "got message" print and the content in the HTML from calculate.jsp.
I also recommend opening the network and verifying that the response you get from "calculate.jsp" is correct.
let me know if you experience any new problems.