jquery php insert data into mysql without refreshing the page - php

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

Related

Stop form from refreshing on submit

I've got this problem that the form refreshes on submit, i dont want it to refresh but i do want it to submit. any of you know what i could do ?
click this link to an older post about this.
<form method="post" id="radioForm">
<?
foreach($result as $radio):
printf('
<button type="submit"
href="#radio"
name="submitRadio"
value="'.$radio['id'].'">
Go!
</button>
');
endforeach;
?>
</form>
<script type="text/javascript">
$('#radioForm').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
});
});
</script>
</div>
Use submit() handler and pass the value of your button to your other script
First set the id on the form.
<form method="post" id="formId">
Then bind a listener
$( "#formId" ).submit(function( event ) {
event.preventDefault();
//This is where you put code to take the value of the radio button and pass it to your player.
});
To use this you need jQuery.
You can read more about this handler here: http://api.jquery.com/submit/
This is the default behavior of a HTML <form> on submit, it makes the browser POST data to the target location specified in the action attribute and loads the result of that processing to the user.
If you want to submit the form and POST the values behind the scenes without reloading the page, you have to disable the default behavior (the form submit) and employ the use of AJAX. This kind of functionality is available readily within various JavaScript libraries, such as a common one called jQuery.
Here is the documentation for jQuery's AJAX functionality http://api.jquery.com/jquery.ajax/
There are lots of tutorials on the interwebs that can introduce you to the basic use of jQuery (Including the library into your HTML pages) and also how to submit a form via AJAX.
You will need to create a PHP file that can pick up the values that are posted as a result of the AJAX requests (such as commit the values to a database). The file will need to return values that can be picked up within your code so that you know if the request was un/successful. Often the values returned are in the format JSON.
There are lots of key words in this answer that can lead you on your way to AJAX discovery. I hope this helps!
use ajax like this of jquery
$('form').submit(function(event) {
event.preventDefault();
$.ajax({
url:'index.php',
data:{submitRadio:[radiovalue]},
type:'POST',
success:function(response) {
/* write your code for what happens when the form submit */
}
});
});

Why does a submission form work, but my ajax doesn't?

I am trying to create a button on my chat that will allow someone to print the conversation. So I made the button that runs a PHP script that creates a new file, writes the conversation to file, and also writes the following jQuery.
jQuery AJAX Call
function OnBeforeUnLoad () {
$.ajax({
type: 'GET',
url: 'deleteFile.php',
data: {
pageName: ".$pageName."
},
dataType: 'text',
success: function(data){alert('Good bye 1!');}
});
return;
}
HTML Put into page
<br/><br/><form method="get" action="deleteFile.php"> <input type="submit" value="Close this Window"/>
<input type="text" value="'.$pageName.'" name="pageName" style="visibility:hidden"/></form>
deleteFile.php
<?php
$pageName = $_GET['pageName'];
$fullURL = 'PrintPage'.$pageName.'.php';
unlink($fullURL);
echo '<script>window.close();</script>';
?>
When the page shows up and I click the "Close this Window" button it does exactly what I want. It deletes the file and closes the window. But I do not get the same results when I close the window (aka OnBeforeUnLoad()). I even tried triggering submit by giving the form an id of deleteFiles and then doing $('#deleteFiles').submit() and it still didn't work.
How do I get the AJAX to work within the OnBeforeUnLoad function?
The form calls the data pageName but the ajax calls it url.
You probably don't want to prefix and suffix the value with . characters either.
Feel like a dummy.... After making all those changes... I found out all I needed to do was add
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
to the header.
Because I was dynamically creating the page in php, I forgot I needed to readd the jQuery.
Always the small things.. Thanks everyone for the help.

performing php post with jquery.ajax

I am trying to run this tutorial
i did not implement the validation part yet, but my problem shouldn't be based on this. Here is my code:
<script type="text/javascript">
$("#submitbutton").click(function () {
var content = $.("#contentarea").val();
$.ajax({
type: "POST",
url: "addArticle.php",
data: content,
success: $.("#addArticle").append("<p>ok</p>")
});
return false;
})
</script>
As seen in the demo, it should not refresh the page because of the return false statement and also should do a post instead of get. But neither it does. It will continue to reload the page and also append the given content to the url as an argument. How do i prevent this / where is my failure?
Here is the whole thing
The tutorial you have followed is incorrect. There are more ways to submit a form than just clicking on its submit button (for example, you can press return while in a text field). You need to bind your code to the form's submit() event instead of the button's click() event.
Once you have done this, use your in-browser debugger to check whether the code is actually being run when you submit the form.
Also, the success parameter needs to be a function:
submit: function() { $("#addArticle").append("<p>ok</p>") }
EDIT : also, you have written $.( instead of $( several times. This will cause a runtime error, which may cause the code that blocks the submission to fail.
Well well well...
A few less nerves later, it works.
I decided to use the jquery form plugin
But, and i bet you'll love that, i have no idea why it is working:
<script>
$(document).ready(function() {
$('#addForm').ajaxForm(function() {
alert("ok");
});
});
</script>
<div id="addArticle">
<form id="addForm" method="post" action="addArticle.php">
<textarea id="contentarea" required="required" name="content"> </textarea>
<br />
<input type="submit" id="submitbutton">
</form>
</div>
I guess the author has done pretty good work, just wanted to tell my solution to that future guy who is searching on google for that problem.

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.

Simple AJAX Submit and update mysql

I am stumped, I am tossing out my code and I need help with a cross browser ajax submit.
Can anyone PLEASE give me a simple working ajax submit script for updating mysql? The one I have is all bad.
Works in FF and Safarai (iphone), but in IE7, it has caching problem and in IE8 it doesn't even submit.
Your best/safest bet is to use a library which provides AJAX functionality. You can roll your own, but odds are it will not be as stable or full-featured as library code.
jQuery, for example, supports AJAX:
http://jquery.com/
If you decide you're determined to roll your own, or want to learn more about the innards of AJAX, check out the w3schools tutorial (which includes sample AJAX code):
http://www.w3schools.com/Ajax/ajax_intro.asp
ok since you want to use any script I will use my favorite one ExtJS
<?php
// Submit.php
mysql_connect();
$_POST['text'] = mysql_real_escape_string($_POST['text']);
mysql_query("INSERT INTO comment(text) VALUES('{$_POST['text']}')");
die('{sucess: true}');
========== form.html
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/ext-core/3/ext-core.js"></script>
<script type="text/javascript">
Ext.onReady(function(){
Ext.fly('form').on('submit', function(e){
e.preventDefault();
var t = Ext.fly('text').dom.value;
Ext.Ajax.request({
url: 'submit.php',
success: function(){ alert('ok!'); },
failure: function() { alert('nok!') ; },
params: { text: t }
});
return false;
});
});
</script>
</head>
<body>
<form id="form">
<input id="text" type="text" name="text">
<input type="submit">
</form>
</body>
</html>
you have to add something like this to ur request url like: ?rand=someRandomTimeGeneratedWithJavasciptGreatJob
make sure.. on your button it's like this...
<input type="button" onclick="ajax('url'); return false;"> don't ask me why this works, it just does.
also, screw jqweery USE prototype -> prototypejs.org

Categories