Simple AJAX Submit and update mysql - php

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

Related

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.

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

Render DIV using javascript

I have a page with a load of tables on that are created using SQL lookups. Obviously, all of these together take time to load, each table (<div>) is "minimised" as default (I use javascript to hide it until a button is clicked). But these tables are still rendered in the background. What I really want is a way to block all of the div's content until called. I tried using a php if loop, which worked, but the page needed refreshing, so gave that one up.
Any ideas please? I've been looking for ages now.
I agree with Andre. If your page is always loading these tables, it will always take forever to build your whole page, there is no way that hiding the tables will increase your processing time. What you need to do is use an AJAX request that returns your table when needed, and then populate your div on the return.
I would go with the jQuery load method.
Basic example:
$(document).ready(function() {
$(".data").each(function(index) {
var tableName = this.id;
window.setTimeout(function() {
LoadData(tableName);
}, index * 1500);
});
});
function LoadData(tableName) {
var url = "load.php?table=" + tableName;
var oDiv = $("#" + tableName);
oDiv.html(url + " - To load real data, have here such code: <b>oDiv.load(url);</b><br />Good luck! :)");
}
This comes with such HTML:
<div class="data" id="cats_table"></div>
<div class="data" id="dogs_table"></div>
<div class="data" id="flowers_table"></div>
Live test case: http://jsfiddle.net/4H8Fa/
As the comment above says, it sounds like what you're looking for requires AJAX. Have a look at this Jquery library:
http://www.datatables.net/
UPDATE (based on comment from OP):
Since you have a custom solution, there isn't going to be a "recipe" that will work exactly with what you wrote. Generally, you should be looking at making a call back to your server using AJAX with a library like getJSON. Then populate your table by building TR/TD DOM objects and attaching them to your table object.
I did it using $.ajax and load()
<html>
<body>
<div id="load-div" class="functions">
<span>Load</span>
<input type="submit" value="Go" id="load_basic" />
</div>
<div id="result" class="functions">
</div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
var ajax_load = "<img class='loading' src='img/load.gif' alt='loading...' />";
// load() functions
var loadUrl = "page1.html";
$("#load_basic").click(function(){
$("#result").html(ajax_load).load(loadUrl);
});
</script>
</body>
</html>

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.

jQuery AJAX call not working in Webkit

I've run into a strange issue with Webkit based browsers (both Safari and Chrome - I'm testing on a Mac) and I am not sure what is causing it. Here's a small script I've created that replicates the issue:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
function doRequest() {
document.test.submit();
$.ajax({
type: "GET",
cache: false,
url: 'ajax.php?tmp=1',
success: doSuccess
});
}
function doSuccess(t_data,t_status,req) {
alert('Data is: '+ t_data +', XMLHTTPRequest status is: '+ req.status);
}
</script>
</head>
<body>
<form name="test" method="post" action="ajax.html" enctype="multipart/form-data">
<input type="file" name="file_1">
<br><input type="button" value="upload" onclick="doRequest();">
</form>
</body>
</html>
ajax.php is:
<?php
echo $_REQUEST['tmp'];
?>
This works as is on Firefox, but the XMLHTTPRequest status is always "0" on both Safari and Chrome. If I remove this line:
document.test.submit();
then it works, but of course the form is not submitted. I've tried changing the form submit button from "button" to "submit", but that also prevents it from working on Safari or Chrome.
What I am trying to accomplish is:
submit the form
call another script to get status on the file being uploaded via the form (it's for a small upload progress meter).
Any help is really appreciated - I'm hopeful it is just a quirk I'm not familiar with.
Thanks!
Brian
Simply put: you cannot upload files using AJAX.
There are nice plugins such as jquery form that will handle this automatically (by creating a hidden iframe and performing the real file upload).
I think FireFox has a native file upload API but if you want a cross browser solution you will need to take a look at some plugins. Using a flash upload is another solution.
My experience while developing a similar upload checking tool1 is that you should use both success: .. and complete: ... They would probably do the exact same thing in your code and you can have them call the same function. complete: gets called when the request finishes, success: when a request succeeds. Thus maybe:
function doRequest() {
document.test.submit();
$.ajax({
type: "GET",
cache: false,
url: 'ajax.php?tmp=1',
complete: doSuccess,
success: doSuccess
});
}

Categories