showing mysql_error message with jQuery dialog - php

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

Related

Debug AJAX Form

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 } ?>

Save data to PHP / Mysql with inline edit in CKEditor

I want to use "inline edit" of the new CKEditor 4 (http://docs.ckeditor.com/#!/guide/dev_inline-section-2), but can not find any example of how to save the data with PHP / MySQL.
Can you help me?
You need some AJAX magic. Via JavaScript inside the page you get the edited HTML. Then you send it to the server where a PHP script gets it and can pass it onto MySQL.
Here is a simple test case which will show you the ropes.
Let's start with the editable HTML.
<div id='textToBeSaved' contenteditable='true'>
<p>Using the <strong>Terminal</strong> in OS X makes you all-powerful.</p>
</div>
We also need a "Save" button which will be used to start the POST event.
<button onclick='ClickToSave()'>Save</button>
Such a button could well we positioned in the CKEditor toolbar itself, but that would require more coding and I'll leave it to someone who's better at JavaScript than me.
Of course you want to include CKEditor. For my sample code I'll also make use of jQuery, which I'll use for AJAXing the results.
<script src='//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>
<script type='text/javascript' src='CKEditor4/ckeditor.js'></script>
Now the script which will execute when you press the "Save" button. It will use CKeditor to grab the edited HTML, then jQuery to send it.
<script type='text/javascript' language='javascript'>
// <![CDATA[
function ClickToSave () {
var data = CKEDITOR.instances.textToBeSaved.getData();
$.post('save.php', {
content : data
})
}
// ]]>
This is it, you don't need anything else clientside.
On the server, you must have the PHP code which will act when the script POSTs the updated HTML. The script must be called save.php and be positioned in the same directory where the HTML is if you use my code verbatim.
My one-liner here will just save your HTML in a temporary file inside the /tmp folder. Feel free to add your MySQL magic instead.
<?php
file_put_contents('/tmp/serverside.html', $_POST['content']);
?>
This is the way I've done it in the past:
The current_page_id relates to the table row we wish to update, otherwise we wouldn't know what record we need to update.
<div id="editable">My body text</div>
<input type="hidden" name="page_id" id="current_page_id" value="10" />
<script type="text/javascript">
CKEDITOR.disableAutoInline = true;
CKEDITOR.inline('editable', {
on: {
blur: function( event ) {
var params = {
page_id: $("#current_page_id").val(),
body_text: event.editor.getData()
};
$.ajax({
url: 'php_file_to_post_to.php',
global: false,
type: "POST",
dataType: "text json",
data: params,
success: function(result) {
console.log(result);
}
});
}
}
});
</script>
The inside of your php_file_to_post_to.php PHP file you simply catch the ajax post request and update the row based off of the page_id variable which has also been posted along with the edited content.
This is how you will get text area data
CKEDITOR.instances.editor1.getData()
CKEDITOR is nothing but the object you used to create functionality.
Thanks so much for the code. Try to improve de code with file_put_contents('page.php', stripslashes($_POST['content']));
And add to the div onBlur="ClickToSave()" and now you can to delete de save button.

jquery php insert data into mysql without refreshing the page

Hello I have the next code into my website:
<input type="text" id="name" name="name" width="25px"/>
Add User
I need that when I click "newUser" the value of the name is saved into my mysql database without refreshing the page.
Any exemple of how to do this?
If you don't want to use a <form> and a submit button which would be the absolutely correct way to do this, you will need to use javascript and AJAX:
Subscribe for the onclick event of the anchor
Send an AJAX request to the server passing the value of the name entered in the textbox
Cancel the default action of the link
Add User
and the insert function could be defined in a separate javascript file:
function insert() {
var name = document.getElementById('name').value;
// TODO: send an AJAX request to the server
return false;
}
http://api.jquery.com/jQuery.ajax/
$('#newUser').click(function(ev){
$.ajax(...);
ev.preventDefault();
});
This can be done on the client side with jquery's ajax libraries to create the refreshless submit.
Here's an example of some html and javascript
<html>
<head>
<script type="text/javascript" src="jq/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
function adduser()
{
var data=$("#adduserform").serialize();
$.ajax({
type: "POST",
url: "adduser.php",
data: data,
dataType: "html",
});
}
</script>
</head>
<body>
<form id="adduserform" name="adduserform">
<fieldset>
<input type="text" id="name" name="name" width="25px"/>
</fieldset>
</form>
Add User
</body>
</html>​
On the php side just code like you would if you were submitting a form via post.
I haven't had time to try it, but I hope it works :)
Like the others have suggested, look on the jquery site for more info.
You can do an Ajax call with JQuery that will send the name to the server. In your PHP code you will be able to create the Insert Query in your user table.
You can use JavaScript for that. Take a look at jQuery ajax: http://api.jquery.com/jQuery.ajax/
note: next time try googling, or at least provide what you have tried

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/

How to get element id into PHP variable

Is it possible to get an element id into a PHP variable?
Let's say I have a number of element with IDs:
<span id="1" class="myElement"></span>
<span id="2" class="myElement"></span>
How do I get this into a PHP variable in order to submit a query. I suppose I would have to resubmit the page, which is OK. I would like to use POST. Can I do something like:
<script language="JavaScript">
$(document).ready(function(){
$(".myElement").click(function() {
$.post("'.$_SERVER['REQUEST_URI'].'", { id: $(this).attr("id") });
});
});
</script>
I need to pass $(this).attr('id') into $newID in order to run
SELECT * from t1 WHERE id = $newID
jQuery is a very powerful tool and I would like to figure out a way to combine its power with server-side code.
Thanks.
This is like your question: ajax post with jQuery
If you want this all in one file (posting to active file) here is what you would need in general:
<?php
// Place this at the top of your file
if (isset($_POST['id'])) {
$newID = $_POST['id']; // You need to sanitize this before using in a query
// Perform some db queries, etc here
// Format a desired response (text, html, etc)
$response = 'Format a response here';
// This will return your formatted response to the $.post() call in jQuery
return print_r($response);
}
?>
<script type='text/javascript'>
$(document).ready(function() {
$('.myElement').click(function() {
$.post(location.href, { id: $(this).attr('id') }, function(response) {
// Inserts your chosen response into the page in 'response-content' DIV
$('#response-content').html(response); // Can also use .text(), .append(), etc
});
});
});
</script>
<span id="1" class="myElement"></span>
<span id="2" class="myElement"></span>
<div id='response-content'></div>
From here you can customize the queries and response and what you would like to do with the response.
You have two "good" choices in my mind.
The first is to initiate a post request every time the ordering changes. You might be changing the ordering using jQuery UI sortable. Most libraries that support dragging and dropping also allow you to put an event callback on the drop simply within the initialization function.
In this even callback, you'd initiate the $.post as you have written it in your code (although I would urge you to look up the actual documentation on the matter to make sure you're POSTing to the correct location).
The second strategy is to piggyback on a form submission action. If you're using the jQuery Form Plugin to handle your form submissions, they allow you to indicate a before serialize callback where you can simply add into your form a field that specifies the ordering of the elements.
In both cases, you'd need to write your own function that actually serializes the element IDs. Something like the following would do just fine (totally untested; may contain syntax errors):
var order = [];
$('span.myElement').each(function(){
// N.B., "this" here is a DOM element, not a jQuery container
order.push(this.id);
});
return order.join(',');
You're quite right, something along those lines would work. Here's an example:
(btw, using $.post or $.get doesn't resubmit the page but sends an AJAX request that can call a callback function once the server returns, which is pretty neat)
<script language="JavaScript">
$(document).ready(function(){
$(".myElement").click(function() {
$.post(document.location, { id: $(this).attr("id") },
function (data) {
// say data will be some new HTML the server sends our way
// update some component on the page with contents representing the element with that new id
$('div#someContentSpace').html(data);
});
});
});
</script>
Your approach looks perfectly fine to me, but jQuery does not have a $_SERVER variable like PHP does. The url you would want to provide would be window.location (I believe an empty string will also work, or you can just specify the url on your own). You seem to be sending the ID just fine, though, so this will work.
If you want the page to react to this change, you can add a callback function to $.post(). You can do a variety of things.
$.post(window.location, {id: this.id}, function (data) {
//one
location.reload();
//two
$("#responsedata").html(data);
//three
$("#responsedata").load("affected_page.php #output");
});
I think number 2 is the most elegent. It does not require a page reload. Have your server side php script echo whatever data you want back (json, html, whatever), and it will be put in data above for jQuery to handle however you wish.
By the way, on the server side running the query, don't forget to sanitize the $id and put it in quotes. You don't want someone SQL Injecting you.

Categories