How to send jquery $.post with alert - php

I have a problem with following script. It generates a list of places which are editable, deletable or you can even create a new one.
I want to send a $.post request when creating a new place to a php file which makes an entry into a database (MySQL) and then lists this entryes in html. Now why doesn't even the $.post send an alert message to notifi me that the data is been send?
The script isn't finished yet how you can see, but it would be great if you could give me a hand!
JS-Script
$(function() {
$(".edit").click(function() {
$(this).css("display","none").prevAll(".place_name").css("display","none").prevAll(".inputfield_td").css("display","block").nextAll(".cancel").css("display","block").nextAll(".save").css("display","block").prevAll(".inputfield_td").css("display","block");
});
$(".cancel").click(function() {
$(this).css("display","none").prevAll(".edit").css("display","block").prevAll(".place_name").css("display","block").prevAll(".inputfield_td").css("display","none").nextAll(".save").css("display","none");
});
$(".save").click(function() {
var myvariable1 = $(this).siblings().find("input[type=text]").val();
var myvariable2 = $(this).prevAll("td:last").attr("id");
$(this).css("display","none").prevAll(".cancel").css("display","none").prevAll(".edit").css("display","block").prevAll(".place_name").css("display","block").prevAll(".inputfield_td").css("display","none");
alert("save name: "+myvariable1+" save id: "+myvariable2);
});
$(".delete").click(function() {
var myvariable3 = $(this).prevAll("td:last").attr("id");
alert(myvariable3);
});
$(".new").click(function() {
var myvariable4 = $(this).prevAll("input[type=text]").val();
$.post("place_list.php", {action: "create", name: myvariable4}, function(data){
alert("Data Loaded: " + data);
},"html");
alert(myvariable4);
});
});
PHP-File
<?php
require_once "../../includes/constants.php";
// Connect to the database as necessary
$dbh = mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD)
or die ("Unaable to connnect to MySQL");
$selected = mysql_select_db(DB_NAME,$dbh)
or die("Could not select printerweb");
echo "<table><tbody>";
$result = mysql_query("SELECT * FROM place");
while ($row = mysql_fetch_array($result)) {
echo "<tr><td id=".$row["id"]." class=inputfield_td><input class=inputfield_place type=text value=".$row["name"]." /></td><td class=place_name>".$row["name"]."</td><td class=edit>edit</td><td class=cancel>cancel</td><td class=delete>delete</td><td class=save>SAVE</td></tr> \n";
}
echo "</tbody>";
echo "</table>";
echo "<input type=text class=inputfield_visible />";
echo "<button class=new>New</button>";
?>

Have you got firefox and firebug installed?
If so you can view the net tab and see if the post request gets made to place_list.php and also what the response is. I suspect it is 404'ing as the path maybe incorrect. You can always use the .ajax method rather than .post. This allows you to specify an error method that gets called upon a failed ajax request.
e.g
$.ajax({
url : "place_list.php",
data : {action: "create", name: myvariable4},
cache : false,
error : function(XMLHttpRequest, textStatus, errorThrown){
//console.log or alert error
alert(errorThrown);
},
success: function(html){
alert("Data Loaded: " + data);
}
});

Related

Using Ajax to generate an alert box

I want to pop up an alert box after checking whether some data is stored in the database. If stored, it will alert saved, else not saved.
This is my ajax function:
AjaxRequest.POST(
{
'url':'GroupsHandler.php'
,'onSuccess':function(creategroupajax){ alert('Saved!'); }
,'onError':function(creategroupajax){ alert('not saved');}
}
);
but now it show AjaxRequest is undefined.
How can I fix this?
This of course is possible using Ajax.
Consider the below sample code for the same.
Ajax call :
$.ajax({
url: 'ajax/example.php',
success: function(data) {
if(data == "success")
alert('Data saved.');
}
});
example.php's code
<?php
$bool_is_data_saved = false;
#Database processing logic here i.e
#$bool_is_data_saved is set here in the database processing logic
if($bool_is_data_saved) {
echo "success";
}
exit;
?>
function Ajax(data_location){
var xml;
try {
xml = new XMLHttpRequest();
} catch (err){
try {
xml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (error){
try {
xml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (error1){
//
}
}
}
xml.onreadystatechange = function(){
if(xml.readyState == 4 && xml.status == 200){
alert("data available");
}
}
xml.open("GET", data_location, true);
xml.send(null);
}
window.onload = function(){
Ajax("data_file_location");
}
You can create an addtitional table with date(time) of last update database and check if this date is later. You can use standard setInterval function for it.
This is possible using ajax. Use jQuery.ajax/pos/get to call the php script that saves the data or just checks if the data was saved previously (depends on how you need it exactly) and then use the succes/failure callbacks to handle its response and display an alert if you get the correct response.
Below code based on jQuery.
Try it
$.ajax({
type: 'POST',
url: 'http://kyleschaeffer.com/feed/',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
use the ajax to call the script and check values in the database through the script. If
data present echo success else not.lets look an example of it.
Assuming databasename = db
Assuming tablename = tb
Assuming tableColumn = data
Assuming server = localhost
Ajax:
$.ajax({
url: 'GroupsHandler.php',
success:function(data){
if(data=="saved")
{
alert("success");
}
}
});
Now in the myphpscript.php :
<?php
$Query = "select data from table";
$con = mysql_connect("localhost","user","pwd"); //connect to server
mysql_select_db("db", $con); //select the appropriate database
$data=mysql_query($Query); //process query and retrieve data
mysql_close($con); //close connection
if(!$empty(mysql_fetch_array($data))
{
echo "saved";
}
else
{
echo " not saved ";
}
?>
EDIT:
You must also include jquery file to make this type of ajax request.Include this at the top of your ajax call page.
<script src='ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>
First, decide whether to use POST or GET (I recommend POST) to pass AJAX data. Make a php file (ajax.php) such that it echos true or false after checking whether some data is stored in the database. You may test with a variable $your_variable = "some_data_to_check"; having a data inside and once you are finished, you may replace it with $your_variable = $_POST["ajaxdata"];.
Then in your page, set up AJAX using jQuery plugin like:
var your_data_variable = "data_to_send";
$.ajax({
type: "POST",
url: "ajax.php",
data: 'ajaxdata=' + your_data_variable,
success: function(result){
if(result == "true"){
alert("saved");
}else{
alert("not saved");
}
}
You may have a look at jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery.

Using Ajax to generate an alert box after checking whether some data are stored in database [duplicate]

I want to pop up an alert box after checking whether some data is stored in the database. If stored, it will alert saved, else not saved.
This is my ajax function:
AjaxRequest.POST(
{
'url':'GroupsHandler.php'
,'onSuccess':function(creategroupajax){ alert('Saved!'); }
,'onError':function(creategroupajax){ alert('not saved');}
}
);
but now it show AjaxRequest is undefined.
How can I fix this?
This of course is possible using Ajax.
Consider the below sample code for the same.
Ajax call :
$.ajax({
url: 'ajax/example.php',
success: function(data) {
if(data == "success")
alert('Data saved.');
}
});
example.php's code
<?php
$bool_is_data_saved = false;
#Database processing logic here i.e
#$bool_is_data_saved is set here in the database processing logic
if($bool_is_data_saved) {
echo "success";
}
exit;
?>
function Ajax(data_location){
var xml;
try {
xml = new XMLHttpRequest();
} catch (err){
try {
xml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (error){
try {
xml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (error1){
//
}
}
}
xml.onreadystatechange = function(){
if(xml.readyState == 4 && xml.status == 200){
alert("data available");
}
}
xml.open("GET", data_location, true);
xml.send(null);
}
window.onload = function(){
Ajax("data_file_location");
}
You can create an addtitional table with date(time) of last update database and check if this date is later. You can use standard setInterval function for it.
This is possible using ajax. Use jQuery.ajax/pos/get to call the php script that saves the data or just checks if the data was saved previously (depends on how you need it exactly) and then use the succes/failure callbacks to handle its response and display an alert if you get the correct response.
Below code based on jQuery.
Try it
$.ajax({
type: 'POST',
url: 'http://kyleschaeffer.com/feed/',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
use the ajax to call the script and check values in the database through the script. If
data present echo success else not.lets look an example of it.
Assuming databasename = db
Assuming tablename = tb
Assuming tableColumn = data
Assuming server = localhost
Ajax:
$.ajax({
url: 'GroupsHandler.php',
success:function(data){
if(data=="saved")
{
alert("success");
}
}
});
Now in the myphpscript.php :
<?php
$Query = "select data from table";
$con = mysql_connect("localhost","user","pwd"); //connect to server
mysql_select_db("db", $con); //select the appropriate database
$data=mysql_query($Query); //process query and retrieve data
mysql_close($con); //close connection
if(!$empty(mysql_fetch_array($data))
{
echo "saved";
}
else
{
echo " not saved ";
}
?>
EDIT:
You must also include jquery file to make this type of ajax request.Include this at the top of your ajax call page.
<script src='ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js' type='text/javascript'></script>
First, decide whether to use POST or GET (I recommend POST) to pass AJAX data. Make a php file (ajax.php) such that it echos true or false after checking whether some data is stored in the database. You may test with a variable $your_variable = "some_data_to_check"; having a data inside and once you are finished, you may replace it with $your_variable = $_POST["ajaxdata"];.
Then in your page, set up AJAX using jQuery plugin like:
var your_data_variable = "data_to_send";
$.ajax({
type: "POST",
url: "ajax.php",
data: 'ajaxdata=' + your_data_variable,
success: function(result){
if(result == "true"){
alert("saved");
}else{
alert("not saved");
}
}
You may have a look at jQuery AJAX Tutorial, Example: Simplify Ajax development with jQuery.

jQuery/JSON/PHP failing

I am trying to call a php script that accepts JSON data, writes it into a file and returns simple text response using jQuery/AJAX call.
jQuery code :
$("input.callphp").click(function() {
var url_file = myurl;
$.ajax({type : "POST",
url : url_file,
data : {puzzle: 'Reset!'},
success : function(data){
alert("Success");
alert(data);
},
error : function (jqXHR, textStatus, errorThrown) {
alert("Error: " + textStatus + "<" + errorThrown + ">");
},
dataType : 'text'
});
});
PHP Code :
<?php
$thefile = "new.json"; /* Our filename as defined earlier */
$towrite = $_POST["puzzle"]; /* What we'll write to the file */
$openedfile = fopen($thefile, "w");
fwrite($openedfile, $towrite);
fclose($openedfile);
echo "<br> <br>".$towrite;
?>
However, the call is never a success and always gives an error with an alert "Error : [Object object]".
NOTE
This code works fine. I was trying to perform a cross domain query - I uploaded the files to the same server and it worked.
var url_file = myurl"; // remove `"` from end
Arguments of error function is:
.error( jqXHR, textStatus, errorThrown )
not data,
You can get data (ie. response data from server) as success() function argument.
Like:
success: function(data) {
}
For more info look .ajax()
NOTE
If you're trying to get data from cross-domain (i.e from different domain), then you need jsonp request.
Your data object isn't valid; the key shouldn't be quoted:
data : { puzzle: 'Reset!' }
In addition, SO's syntax highlighting points out that you have missed out a " in your code:
var url_file = myurl";
Should be
var url_file = "myurl;

Echoed Javascript appearing in alert instead of processing

I have created a registration system that uses AJAX to process the form so that I can return false. The relevant js is the top block of code. I pass this data to join.php, which sends it to the database. I run a check in join.php to make sure that nobody with a duplicate email has already signed up. As you can see, if the email already exists, I want to insert a message using javascript. Instead of reading the script tags, it simply pastes them into my alert in plaintext...so my alert has the datastring and then actually says the code <script>...</script>. How can I get this js to process instead?
Javascript:
$(".submit").click(function() {
var dataString = {
school : $("#school").val(),
studentEmail : $("#studentEmail").val(),
studentPassword : $("#studentPassword").val(),
parentEmail : $("#parentEmail").val(),
parentPassword : $("#parentPassword").val(),
studentFirstName : $("#studentFirstName").val(),
studentLastName : $("#studentLastName").val(),
studentPhone : $("#studentPhone").val(),
parentFirstName : $("#parentFirstName").val(),
parentLastName : $("#parentLastName").val(),
parentPhone : $("#parentPhone").val()
};
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function(data) {
alert ("data sent: "+ data);
}
});
return false;
}
});
join.php
if($_POST) {
$school = mysql_real_escape_string($_POST['school']);
$studentEmail = mysql_real_escape_string($_POST['studentEmail']);
$parentEmail = mysql_real_escape_string($_POST['parentEmail']);
$studentFirstName = mysql_real_escape_string($_POST['studentFirstName']);
$studentLastName = mysql_real_escape_string($_POST['studentLastName']);
$studentPhone = mysql_real_escape_string($_POST['studentPhone']);
$parentFirstName = mysql_real_escape_string($_POST['parentFirstName']);
$parentLastName = mysql_real_escape_string($_POST['parentLastName']);
$parentPhone = mysql_real_escape_string($_POST['parentPhone']);
$check = mysql_query("SELECT studentEmail FROM clients WHERE studentEmail = '{$studentEmail}';");
$num = mysql_num_rows($check);
if (($num) == 0) {
$sql = "INSERT INTO clients ".
"(`studentEmail`, `studentPassword`, `parentEmail`, `parentPassword`, ".
"`studentFirstName`, `studentLastName`, `studentPhone`, `parentFirstName`, ".
"`parentLastName`, `parentPhone`, `school`) ".
" VALUES ('$studentEmail', '$studentPassword', '$parentEmail', ".
"'$parentPassword', '$studentFirstName', '$studentLastName', ".
"'$studentPhone', '$parentFirstName', '$parentLastName', '$parentPhone', '$school')";
$result = mysql_query($sql);
if ($result) {
echo "Database query successful!";
}
else {
die("Database query failed: " . mysql_error());
}
include "emails/signUp.php";
}
else {
echo 'FAIL
<script>
$(".formErrorMessage").html("Email already exists");
</script>';
}
}
The alert shows your script block because you've got this in your success handler:
alert ("data sent: "+ data);
Data is going to be whatever text you output in your PHP. If you want to have variable behavior based on whether your request was successful or not, I'd recommend that your PHP returns JSON containing a success flag and the message. Your JavaScript callback would then look like this:
function(data) {
if (data.success) {
alert ("data sent: "+ data.message);
} else {
$(".formErrorMessage").text(data.message);
}
}
Your PHP should then change your content-type to JSON:
header('Content-Type: application/json');
... and your echos would change to something like this:
echo '{"success": false, "message": "Email already exists."}';
Your server call shouldn't be returning raw HTML. Should return JSON that contains all the status information the server needs to handle things. i.e. in the usual case:
{'success': true}
or
{'success': false, 'emailAlreadyExists': true, 'msg': 'Email Already Exists'}
of
{'success': false, 'msg': 'Database query failed: blahblahMySqlError'}
Then your client JS should handle it...
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function(data) {
if(data.success) {
alert ("success!");
}
else{
alert("error: " + data.msg);
if(data.emailAlreadyExists){
$(".formErrorMessage").html("Email already exists");
}
}
}
});
from php, you have give formatted status responses
on success:
echo '{"status":"success", message:"Database query successful!"}';
if account already exists:
echo '{"status":"failed", message:"Email already exists"}';
So you will be able to identify this in JavaScript callback function
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function(data) {
if(status.error == "failed"){
$(".formErrorMessage").html(data.message);
}
}
});
This is the best way to do it. Or if you just want to execute a string received from php, you can use eval
success: function(data) {
eval(data);
}
In that case there is no need of script tags in response, only the Javascript statement that has to be executed.

PHP and JavaScript Change Status in MySQL

So I have a to-do list of items that are dynamically populated by user input. Each has a checkbox next to it, when checked, the status of the to-do item in MySQL database should be modified.
I thought of doing it this way:
echo "<input type='checkbox' onclick='changeState($theid);' />";
where $theid is the row id in the table.
What would the javascript/jquery changeState() function look like to be able to update the database properly?
Here is the javascript code that seems to not work at all (it is placed in the <head> of the HTML file:
<script language="javascript">
function changeState()
{
jQuery('body').delegate('input[type="checkbox"][data-state-id]', 'change', function(event){
jQuery.post('updatedata.php', {
'rowid': jQuery(this).attr('data-state-id')
//'state': jQuery(this).is(':checked')
});
});
}
</script>
any ideas why?
You should read more about AJAX calls, preferably with .post() function, and then update the data in database on the server side.
Good luck.
Based on the examples from the documentation of jQuery's .post(), you can implement something like this (in JavaScript with jQuery):
var changeStatus = function(id){
$.post("updateState.php", { 'id': id } );
};
and on the server side (eg. in updateState.php):
$id = (int)$_POST['id'];
// here make some query using $id to update the state
// in a manner you prefer
EDIT:
But I would prefer something like that:
1) on server side, displaying the checkbox (notice different quotes and (int) cast):
echo '<input type="checkbox" data-state-id="' . (int)$theid . '" />';
2) somewhere in JavaScript (see jsfiddle as a proof):
jQuery(main_container).delegate('input[type="checkbox"][data-state-id]', 'change', function(event){
jQuery.post('update_state.php', {
'id': jQuery(this).attr('data-state-id'),
'state': jQuery(this).is(':checked')
});
});
3) somewhere on server side (in update_state.php):
$id = (int)$_POST['id'];
$state = (bool)$_POST['state'];
$query = 'UPDATE `states` SET `state`="' . $state . '" WHERE `id`="' . $id . '";';
// here execute the query, obviously adjusted to your needs
You don't need to think of this as: "JavaScript will update the SQL Record", think of this as "JavaScript will tell a API to update that id."
So basically what you have to do is make an API with PHP; and then make JavaScript do the correct API Call via $.ajax, that should do the trick.
$.ajax({
url: '/path/to/api.php',
type: 'POST',
dataType: 'xml/html/script/json/jsonp',
data: {param1: 'value1'},
complete: function(xhr, textStatus) {
//called when complete
},
success: function(data, textStatus, xhr) {
//called when successful
},
error: function(xhr, textStatus, errorThrown) {
//called when there is an error
}
});

Categories