Debug AJAX Form - php

I have a .php file with HTML code and inside it I call another php with html file with AJAX. A form.
Apparently something with this form is wrong, or the query after it. Problem is:
When I submit it, the page reloads, and I cannot debug my form.
When I use preventDefault on my code, and prevent the form from
submitting I cannot debug because the query is not executed yet.
Cannot write an html message displaying the variable because after
reload php with the form is gone.
How can I debug my code in this situation?
File1.php
$(".edit-post").click(function(){
var postid = $(this).attr("id");
$.ajax({
type: "GET",
url: "/admin/EditProductForm.php/",
dataType: "html",
data: {
ajaxpostid: postid
},
success: function(data){
$('#post').html(data);
}
});
$("#post").show();
});
EditProductForm.php
<?php
$ID = $_GET["ajaxpostid"];
$post = GetProduct($ID);
if(!empty($_POST)){
...query
}
?>
<html>
<form>
.
.
.
</form>
</html>

The first thing to understand is that although your HTML and Javascript might have been delivered to the workstation by PHP, it is now running in a totally separate environment with no access to PHP at all.
The PHP you're running on your server is running in the server environment, and has no access to the HTML and JavaScript running in the browser.
The two parts of your application communicate either by sending data as part of a GET or POST request when the form is submitted, or by sending and receiving messages through AJAX. It would be unusual to use both methods in one page.
Thus, you can debug the two parts separately.
Turning to your code:
Your AJAX code is triggered when your button is clicked. In the absence of any other attributes, the button will also trigger a submit. This is what is causing the page to reload. Since you're using AJAX to update your page you don't want it to reload, so stop it with preventDefault();
$(".edit-post").click(function(event){ // add the event parameter here
event.preventDefault(); // Prevent the default action - the submit.
var postid = $(this).attr("id");
...
With this done you can use the browsers tools Network tab to watch the messages, see what's being sent, and look at what response is received.
The server end of things is a little more awkward, but adding echo statements at appropriate places can provide useful output while debugging. Note that you don't need your AJAX script to debug the server end - a simple HTML form with the right fields will do. If you're using GET you could even type the URL and query string on the command line by hand and watch the results.
In your code there is a basic flaw, however.
In your AJAX code you're setting the request type to GET (type: "GET",). In your PHP script you're looking for $_GET["ajaxpostid"];, which is OK, but then you start looking at the $_POST array, which will be empty because your AJAX call used GET.
Now at this point, there's not enough code to be clear about what you're trying to achieve. If your SQL query is just retrieving data to populate an edit form then GET is an appropriate method, and you shouldn't be looking at the $_POST` array.
However, the code you've posted suggests that the EditProductForm.php code is generating the HTML to perform the edit. If this is the case you don't need AJAX at all, and you can just submit the form from File1.php. On the other hand, if you want the page to transform to an editing form without a refresh then File1.php needs to create the editing form and incorporate the data sent by the server, and your EditProductForm.php should not do that job.

a button on form can have three types button|submit|reset , the default type is submit.
on your case, you are clicking on button which has the default type of submit, so its submitting form. that's why the page refreshes. but you want to apply Javascript instead.
so in these cases, either you apply event.preventDefault(); with the javascript code to stop form submission, or simply add type="button" to your button to explicitly say this button is going to run javascript
type=submit -> it means button is going to submit form date
type=reset -> it means button is going to clear form data
type=button -> it means button is going to apply javascript
<button type="button">Submit</button>

file 1(jquery):
$(".edit-post").click(function(){
var postid = $(this).attr("id");
$.ajax({
type: "GET",
url: "./EditProductForm.php",
dataType: "html",
data: {
ajaxpostid: postid
},
success: function(data){
$('#post').html(data);
}
});
$("#post").show();
});
file 2:
<?php
if($_GET["ajaxpostid"] == "test"){
?>
<!DOCTYPE html>
<html lang="fa">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type='text/css' href="../Requirement/css/bootstrap.min.css">
<link rel="stylesheet" type='text/css' href="./index.css">
<title>test</title>
</head>
<body>
<h1>hello world !</h1>
<script src="../Requirement/js/jquery-3.5.1.min.js"></script>
<script src="../Requirement/js/bootstrap.min.js"></script>
<script src="../Requirement/hls.js/dist/hls.min.js"></script>
</body>
</html>
<?php } ?>

Related

jQuery AJAX Post Error in Head Script

I have a file (lam.php) that displays a database-driven list of countries in Latin America. I would like to include it in various pages on my website as a convenient reference. But rather than simply include it, I'd like to use AJAX, so the users can decide whether or not they want to view the list.
So I'm learning how to work with AJAX. It sounds like I want to use jQuery + AJAX, using Post instead of Get.
But I immediately got hung up on an error on this line:
$.post("http://gx/2b/inc/C/Shared/DBLists/World/lam.php",data,callback);
I don't see any errors displayed when I preview the page, but the error is highlighted in Dreamweaver. Nothing happens when I click the button, so there's obviously an error somewhere. Can anyone spot the error(s) in my script?
This is the entire script:
<head>
<script>
$(document).ready(function(){
$("button#lam").click(function()
$.post("http://gx/2b/inc/C/Shared/DBLists/World/lam.php",data,callback);
)
}
)
</script>
</head>
<body>
<button id="lam">Latin America<button>
</body>
You need to add a DIV to the HTML for the result to be displayed in. Then the callback function has to fill in the DIV with the response from the AJAX call.
Since your PHP script doesn't take any parameters, you don't need the data argument.
<head>
<script>
$(document).ready(function(){
$("button#lam").click(function()
$.post("http://gx/2b/inc/C/Shared/DBLists/World/lam.php", function(response) {
$("#lam-result").html(response);
});
});
});
</script>
</head>
<body>
<button id="lam">Latin America<button>
<div id="lam-result"></div>
</body>

showing mysql_error message with jQuery dialog

Is it possible to show the mysql_error (if exists) with jQuery dialog?
$query="UPDATE user SET pass=(SELECT MD5('$pass')) WHERE userid='$userid'"
$result = mysql_query($query) OR die(mysql_error());
i mean something like a own function inside mysql_error()
i searched the whole internet before this question :o)
best regards
In short: No because as Barmar noted jQuery Dialog runs on client and mysql_* runs on server.
If you really need to display error do the following:
Have an AJAX call to your update function
$result = mysql_query($query) OR echo(mysql_error());
On your AJAX return just append returned message into JQuery Dialog's Body
Other solution would be to just log those errors somewhere in database or in files and dont display any mysql related errors to user.
TIP: get rid of mysql_* functions they are deprecated and switch to PDO or MySQLi
Yes, it is. There are a few things to note, though.
You must have a way of initiating the MySQL query from the client side. Usually, this is done via AJAX and is triggered by a browser event. In the below example I used a button click event to trigger the AJAX routine.
The AJAX routine will "call" your PHP file and initiate your DB query. Optionally, you can pass parameters to the PHP side. In this example, I am passing a userName that a user may have entered into a form field.
Any output from the PHP file (hopefully, it would be useful data) will appear in the AJAX routine's success: function. You must process it there (i.e. insert data into the DOM, etc), within in that function and no where else. As you can see, my code takes whatever is received (variable whatigot) and uses the .html() method to inject it into the <div id="err_msg">.
Finally, the jQUI dialog is the easiest bit - just run the .dialog method against that div. Note that the 2nd and 3rd references in the <head> are what make it work (the jqueryui refs).
Here is a stand-alone example using the AJAX method:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#mybutt').click(function() {
var someGuy = $('#sumuser').val();
$.ajax({
type: "POST",
url: "your_php_file.php",
data: 'userName=' + someGuy,
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
$('#err_msg').html(whatigot);
$('#err_msg').dialog({
autoOpen:true,
width:500,
title:"Your Error Message",
});
} //END success fn
}); //END $.ajax
}); //END button click event
}); //END $(document).ready()
</script>
</head>
<body>
Type a user name and then press Go:<br />
<input type="text" id="sumuser">
<br />
<input type="button" id="mybutt" value="Go">
<div id="err_msg"></div>
</body>
</html>
Note that PHP processing is done in an external file, which I reference above as your_php_file.php. This is what is inside that. On my system, it generates a MySQL error -- you may need to tweek the MySQL query to generate an error.
YOUR_PHP_FILE.PHP -- actually, must be named in same case as is referenced, so really: your_php_file.php:
//echo 'Got to the PHP side';
$phpSideUserName = $_POST['userName'];
$query="UPDATE users SET pass=(SELECT MD5('$pass')) WHERE userid='$phpSideUserName '"
$result = mysql_query($query) OR die(mysql_error());

css popup window incorporating session variables or php file

I have recently installed Simple Mailing List 2 (currently in beta) and I have got everything to work so far. The main thing that was left for me to do was to make a custom php page which the signup form redirects to once submitted. The content that the page shows is based on what the user enters in the email field and returns one of three results:
an error message if the email syntax is incorrect.
a custom message if the user has subscribed telling them to check their email.
a custom message if the user has chosen to unsubscribe.
That's the background out of the way. Now what I intend to do is show a popup window that includes the contents of the redirected php page (ie. one of the three results) instead of going to a new page. Is it possible to do this a css popup box so I don't have to open up a new window?
Thankyou
Adam
You can use JavaScript to send an ajax request to the PHP page that will do the calculations, the result will then be sent to your "window" content and then you show the window to the user
You're mixing metaphors. CSS is just a presentational technology that you use to determine the style of something. There is no such thing as a "css popup box".
What you want to do is have an HTML element (likely a div) that contains the information you intend to show, initially set to not be visible (you use CSS for this with the display:none; style). What you're describing is essentially an AJAX interaction that uses Javascript to parse the contents of the form, send data to the server to be evaluated, and return a message to be displayed (without triggering a postback/going to a new page). That Javascript would also handle the CSS part of setting the display of the HTML element to true.
This is a fairly common scenario, so you should be able to find snippets online.
...but here's a super dumb example
<html>
<head>
<title>AJAX Test</title>
</head>
<body>
<form action="#">
<input type="text" id="enterStuff" />
</form>
<div id="response" style="display:none;">
<p id="message">Put stuff in me</p>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
registerEventListeners();
});
function registerEventListeners(){
jQuery("#enterStuff").change(getData);
}
function getData(){
jQuery.ajax({
type : 'POST',
data : {
stuff : jQuery("#enterStuff").val(),
},
url : "http://localhost/myprocessor.php",
success : showCool,
complete : updateDisplay
});
}
function showCool(data, textStatus, jqXHR){
var selector = jQuery("#message");
selector.val(data)
}
function updateDisplay() {
jQuery("#response").show();
}
</script>
</body>
</html>
Then your myProcessor.php would have to read the value of the variable, do some logic, and echo a response.
You could use an <iframe> as an in-document 'pop-up', you just set the target of the form to the name/id of the iframe. (You can use some JavaScript to only show the iframe once the form is submitted.)

Form auto submit ajax not working

I'm passing some variable from one file to another php file that contains a form via jQuery ajax. On The form page where data is being passed to have the following code in it, The values are getting passed in properly and and fields are getting populated with the correct entries, i'm able to very this with firebug response, but page is not automatically submitting. Is their anything i should be looking for that is preventing form from auto submitting. If i access the form page directly, i can see auto submit works.
<?php
$title = $_POST['title'];
$wrapper = $_POST['wrapper'];?>
<form action="test.php" method="post" id="publish">
<input type="text" value="<?php echo $title ?>" name="title">
<textarea name="wrapper"><?php echo $wrapper?></textarea>
<input type="submit" value="Submit">
</form>
<script>
window.onload = function(){
document.getElementById('publish').submit();
}
</script>
ajax code that is sending the values looks like this
$.ajax({
type: "POST",
url: "process.php",
data: {
title: 'test',
wrapper: 'testing123'
},
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Spot the difference:
getElementById('publishForm')
id="publish"
From what I see the auto submit is linked to the 'publishForm'
However, your form Id is "publish"
This is probably the cause of the code not working.
Perhaps you should show us the caller code instead of the handler code. Most likely what you're dealing with is the JS not being run during the AJAX call - the PHP page processing is server side.
You could look into sending the form using PHP Curl instead of JS? That would probably address the issue where it works loaded directly, but fails when called from another page.
As far as I understood, that HTML is being loaded through AJAX, right? If so, then window.onload will not be fired since the page was already loaded (AJAX doesn't count). Just do this:
<script type="text/javascript">
document.getElementById('publish').submit();
</script>
EDIT
To break this down:
Your code on SourcePage.php(I made up this name for reference) is posting data to process.php via an AJAX request
process.php then injects "title" & "wrapper" into the html markup and returns html with some javascript to SourcePage.php
You're then expecting that displaying the resulting string (msg) of the returned html on SourcePage.php will get the javascript in that string to execute.
To get this working, you'll need to do a few things.
Parse out the incoming javascript from the html.
Inject the incoming parsed HTML into SourcePage.php's markup.
Pass the parsed out JavaScript into JavaScript's eval function.
Doing this should bring the page from the process.php and successfully execute the JavaScript code on SourcePage.php.
If you were expecting that the JavaScript would run on the server, then I'm afraid you're mistaken as the server(php runtime) will not execute the JavaScript on the server. Perhaps a redirect on the server will accomplish your goal (whatever that may be).
Original
Try this out: http://jsfiddle.net/NiceGuy4263/eJLMS/

HTML form with PHP

I'd like to have a form that executes some php code without having to open a completely new php page. Right now, I'm familiar with "POST" so that I can execute a php file and call the variables from the HTML form using $_POST[variable] but, it takes time to open a new page, and I want to have a form that does the action right then and there.
For example, can someone write html code that creates a text box and a button, and when the user presses go, it displays the text that the user entered right next to the button.
Thanks!
Here's an HTML and PHP snippet to get you started. It uses jQuery and just writes the value of textarea beneath the submit button using AJAX.
HTML Snippet [file=so.html]
<!DOCTYPE html>
<html><head><title>SO Example</title>
<script
type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js">
</script>
</head>
<body>
<form id="frm" name="frm">
<textarea id="txt" name="txt" rows="4" cols="40">
</textarea><br />
<input type="submit"><br />
<span id="result"></span>
</form>
<script type="text/javascript">
$('#frm').submit(function(e){
e.preventDefault();
$.ajax({
url:"/so.php",type:"post",dataType:"html",
data:$('#frm').serialize(),
success:function(obj){
$('#result').text(obj);
}
});
});
</script>
</body>
</html>
PHP Snippet [file=so.php]
<?php
echo $_POST['txt'];
If you want to execute php code after the page is loaded without opening a new page then you should be using a technology like AJAX. PHP is a pre-processor and is meant to be run to process a page, not for functions after that.
With AJAX you can use javascript to call a webpage that's processed by PHP. Then with that returned page/data you can do your page function.
For more info on ajax check here: http://en.wikipedia.org/wiki/Ajax_(programming)
I recommend looking at jQuery as an ajax wrapper: http://api.jquery.com/jQuery.ajax/
You can find a ton of tutorials online to get you started.
I'd look into AJAX, more specifically an AJAX call using jQuery. It looks a little bit like this for a POST request:
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
});
And if I filled that out, it might look like this:
$.ajax({
type: 'POST', // Method of submission: POST or GET
url: 'processor.php', // The script to send to.
data: { id: 1, name: 'John' }, // The data to give to PHP.
success: function(data) { // Do something with what PHP gives back.
console.log(data);
}
});
For more info on jQuery's AJAX functions, head here: http://api.jquery.com/category/ajax/
You're interested in jQuery.ajax(), jQuery.post(), and jQuery.get() probably.

Categories