.Post in jquery - php

im using the below code in jquery, but my page itself reloading, i dont know where i have made a mistake.
var newstr = $.trim($('#umail').val());
newstr holds the email address
$.post("coding/unsub.php",{email:newstr},function(result){
$("#d_result").html(result);
});
i have
<span id="d_result"></span>
to show the result
my php code is
<?php
include ("../includes/dbcon_.php");
$unsub_sql = mysql_query("Delete FROM TblNewsLetter WHERE Email = '$_GET[email]'");
if (!$unsub_sql)
{
$ds_result = "<p style='font-size:200%;color:red;'>Some Error Occurred! Try Later.</p>";
}
else
{
$ds_result = "<p style='font-size:200%;color:green;'>Successfully Unsubscribed</p>";
}
mysql_close($con);
echo $ds_result;
?>

You said in a comment that you do the Ajax call from a form submit handler. You need to prevent the default submit behaviour, either by using the event object's .preventDefault() method or by returning false from the handler:
$("#yourFormSelectorHere").submit(function(e) {
var newstr = $.trim($('#umail').val());
$.post("coding/unsub.php",{email:newstr},function(result){
$("#d_result").html(result);
});
e.preventDefault();
// and/or
return false;
});

In your sql query
$mail = $_GET['email'];
$query = "DELETE FROM TblNewsLetter WHERE Email = $mail";
$_GET should be changed to $_POST

use like this
$unsub_sql = mysql_query("Delete FROM TblNewsLetter WHERE Email = '".$_POST['email']."'");

Related

The event.preventDefault is not working

I have this codes below and I can't get the event.preventDefault() working. The thing is, I already have other form and it worked well.
I'm sure you guys can help me out.
Here are the codes:
$(document).on('dblclick','td.selecionaCodigoCliente', function(){
//event.preventDefault();
$("#mostraClienteSelecionado").html("Cliente [" + this.parentNode.children[0].innerText + "]: " + this.parentNode.children[1].innerText);
$('input[name="salvaCodigoCliente"]').attr('value',this.parentNode.children[0].innerText);
});
PS: this code above is for the dblclick in a table.
$("#botaoSalvaOS").on('submit',function(event){
$.post("salvaOS.php", $(this).serialize(),function(){
$("#sucessoOS").html("Dados inseridos com sucesso");
});
event.preventDefault();
})
PS: this cobe is for handle the submit
When I submit the form, I get the PHP response. This is the PHP code.
<?php
include_once('db.php');
$dataAberturaOS = date('d-m-Y');
$codigoCliente = $_POST['salvaCodigoCliente'];
$equipamento = $_POST['equipamento'];
$marca = $_POST['marca'];
$modelo = $_POST['modelo'];
$nserie = $_POST['nserie'];
$acessorio = $_POST['acessorio'];
$observacao = $_POST['observacao'];
$defeitos = $_POST['defeitos'];
if(mysql_query("INSERT INTO ordemdeservico VALUES('NULL', '$equipamento', '$marca', '$modelo', '$nserie', '$observacao', '$acessorio', '$defeitos', '$codigoCliente', '$dataAberturaOS', '$dataAberturaOS', 'ABERTA')"))
echo "Successfully Inserted";
else
echo "Insertion Failed";
?>
Thanks in advance.
Your code seems correct. Maybe Abhik Chakraborty comment may help. You can also try to add a event.stopPropagation(); to avoid event bubbling up to a different handler.
Try returning false instead:
$("#botaoSalvaOS").on('submit',function(event){
$.post("salvaOS.php", $(this).serialize(),function(){
$("#sucessoOS").html("Dados inseridos com sucesso");
});
return false;
})

Inserting Variables From Jquery Always Fails

i have some problem, i made some local website using php.
I have a file called functions.php which this is the code:
public function saveAll($idmt_salesarea, $thn_bln, $no_pesanan, $tgl_pesan, $idms_langganan, $idms_kodebarang, $quantity, $harga, $jumlah, $disc_cash, $disc_kredit){
$message = "Waiting input...";
try{
$con = new db();
$conn = $con->connect();
$query = "INSERT INTO mt_pesanan(idmt_salesarea,thn_bln,no_pesanan,tgl_pesan,idms_langganan, idms_kodebarang,quantity,harga,jumlah,disc_cash,disc_kredit) VALUES ($idmt_salesarea, '$thn_bln', '$no_pesanan', '$tgl_pesan', $idms_langganan, $idms_kodebarang, '$quantity', $harga, $jumlah, '$disc_cash', '$disc_kredit')";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn) . " " . mysqli_errno());
if($result == 1){
$message = "Success";
} else if($result == 0){
$message = "Failed";
}
}catch(Exception $exc){
echo $exc->getCode();
}
$con->disconnect();
return $message;
}
i Take the input parameter from file called: index.php and pass the parameter using AJAX Jquery. The parameter itself is sent and pointing to file called insert.php
here's the insert.php file:
<?php
include_once 'functions.php';
$idmt_salesarea = isset($_GET['salesarea']);
$thn_bln = isset($_GET['thn_bln']);
$no_pesanan = isset($_GET['nopes']);
$tgl_pesan = isset($_GET['tglpes']);
$idms_langganan = isset($_GET['idlangganan']);
$idms_kodebarang = isset($_GET['idbarang']);
$quantity = isset($_GET['quantity']);
$harga = isset($_GET['harga']);
$jumlah = isset($_GET['jumlah']);
$disc_cash = isset($_GET['disc_cash']);
$disc_kredit = isset($_GET['disc_kredit']);
if (($disc_cash == null) || ($disc_kredit == null)) {
$disc_cash = 0;
$disc_kredit = 0;
}
$insert = new functions();
$insert->saveAll($idmt_salesarea, $thn_bln, $no_pesanan, $tgl_pesan, $idms_langganan, $idms_kodebarang, $quantity, $harga, $jumlah, $disc_cash, $disc_kredit);
?>
but when i check the error, that is the variable that cannot get from insert.php file (using $_GET statement).
How proper way to gain the variable? because all the parameter is set.
I know this is combining object oriented style and old fashion php coding. Any ideas?
thanks in advance.
UPDATE
here's the index.php file using jquery ajax to sent the data
function sendAll(){
var tgl_pesan = $('#dpc').val();
var sales_area = $('#sales_area').val();
var nopes = $('#no_pesanan').val();
var thnbln = getTahunBulan();
var id_langganan = $('#kode_langganan').val();
var id_barang = $('#kode_barang').val();
var quantity = getQuantity();
var harga = $('#harga').val();
var jumlah = $('#jumlah').val();
var disc_cash = $('#cash').val();
var disc_kredit = $('#kredit').val();
var max = $('#max').val();
$.ajax({
type:"POST",
**url:"insert.php",**
data:{
salesarea:sales_area,
thn_bln:thnbln,
nopes:nopes,
tglpes:tgl_pesan,
idlangganan:id_langganan,
idbarang:id_barang,
quantity:quantity,
harga:harga,
jumlah:jumlah,
disc_cash:disc_cash,
disc_kredit:disc_kredit,
max:max
},
success:function(msg){
alert("Data Inserted");
},
error:function(msg){
alert("Data Failed to save" + msg);
}
});
the ajax itself is pointing to file insert.php which the insert.php is executing function from another file called functions.php
The problem is with this code:
$idmt_salesarea = isset($_GET['salesarea']);
$thn_bln = isset($_GET['thn_bln']);
$no_pesanan = isset($_GET['nopes']);
$tgl_pesan = isset($_GET['tglpes']);
$idms_langganan = isset($_GET['idlangganan']);
$idms_kodebarang = isset($_GET['idbarang']);
$quantity = isset($_GET['quantity']);
$harga = isset($_GET['harga']);
$jumlah = isset($_GET['jumlah']);
$disc_cash = isset($_GET['disc_cash']);
$disc_kredit = isset($_GET['disc_kredit']);
For each of those variables, you are assigning the result of isset(), which will evaluate to either TRUE or FALSE. If you want to bind the actual value of your $_GET input, change each line from this syntax:
$idmt_salesarea = isset($_GET['salesarea']);
To
$idmt_salesarea = isset($_GET['salesarea']) ? $_GET['salesarea'] : '';
However this code isn't really maintainable, and I would also recommend using arrays instead of passing that many arguments to your saveAll() method.
In response to your update
If you are sending an AJAX request with type: "POST", you cannot access your input data via the PHP $_GET super global, you have to use $_POST. However, what I said before is still valid, as you aren't binding values to your variables properly.
Although I do not get what you are saying completely, still based on your description the problem can be you sending the variable using ajax call. If the ajax call is async you might not get the value by the time you use it.
So you can either set async:false in the ajax call (which is not a good way) or trigger any thing that uses that variable from within the success callback handler of the ajax call.
It would be really helpful if you can share the piece of code which explains the following statement of yours.... "i Take the input parameter from file called: index.php and pass the parameter using AJAX Jquery. The parameter itself is sent and pointing to file called insert.php"

Function that checks DB, returns message, and also sends email

In this example I am using MySQL, which I know is deprecated, but this is just for learning purposes. I am also learning how to use PDO and right now just dont wanna mess up fue to my inexperience with PDO so I am using mysql right now.
Ok, so I have a jQuery AJAX function that submits a form data to a PHP function page. The PHP page then communicates with the Database and returns a result. All of this works so far.
A user fills out a form supplying their email address. The email is passed to teh PHP page and entered into the DB. If the user exists, a message is displayed telling them that they are already subscribed. If the do not exits, they are added and then a message tells them they have been successfully added. The GOOD NEWS is all of this works great!
Now, where I have an issue is that during that same callback function "dispAdd", I want to generate an automated welcome email to the user. No matter how I try to code the mail call though, I seem to get an error in the function. I am going to give you what I have right now but if someone can help that would be hugely appreciated.
Here is my callback function because all the other pieces work ok right now:
function dispAdd() // Serves as callback function to jQuery/AJAX in contact.html
{
$sql= "SELECT * FROM mailList WHERE email = '$email'";
$result= mysql_query($sql) or die(mysql_error());
$to = "rmailloux11#mail.bristol.mass.edu";
$who = "ME";
$message = "WOW";
$subject = "TESTING";
$message = $who . ', ' . $message;
$headers = "From: rmailloux11#mail.bristol.mass.edu" . "\r\n";
if(mysql_num_rows($result) > 0) // Checks to see if query returns any info for the calling function
{
mail($to,$subject,$message,$headers);
while ( $row = mysql_fetch_assoc($result))
return;
}
}
Original CALL:
$('#contForm').submit(function() {
var formData = $(this).serialize(); // Stores all form data in AJAX variable
$.post('contact.php',formData,dispAdd);
function dispAdd(result) { // Callback function requests result of RESULT
if (!result) {
$('#main').html('<div>Your have been added to the mailing list</div>');
} else {
if ($('#fail').length==0) {
$('#main').append('<div id="fail" style="color:red";>This email address is already subscribed to our mailing list</div>');
}
}
}
return false; // Stops form from loading contact.php page
});
<script>
$('#contForm').submit(function()
{
var formData = $(this).serialize(); // Stores all form data in AJAX variable
$.post('contact.php',formData, function(data)
{
console.log(data);
if(data)
{
$('#main').html('<div>You have been added to the mailing list</div>');
}
else
{
$('#main').append('<div id="fail" style="color:red";>This email address is already subscribed to our mailing list</div>');
}
console.log(data);
});
return false; // Stops form from loading contact.php page
});
</script>
Then, in contact.php you should put the below function:
function dispAdd() // Serves as callback function to jQuery/AJAX in contact.html
{
$sql= "SELECT * FROM mailList WHERE email = '$email'";
$result= mysql_query($sql) or die(mysql_error());
$to = "rmailloux11#mail.bristol.mass.edu";
$who = "ME";
$message = "WOW";
$subject = "TESTING";
$message = $who . ', ' . $message;
$headers = "From: rmailloux11#mail.bristol.mass.edu" . "\r\n";
if(mysql_num_rows($result) > 0) // Checks to see if query returns any info for the calling function
{
mail($to,$subject,$message,$headers);
while ( $row = mysql_fetch_assoc($result))
return;
}
}
After the code on contact.php runs, have it call the dispAdd function and return the result of dispAdd to your Ajax request.

strange issue with FLASH/PHP

i am having strange issue with Flash and PHP. actually i have one Forgot password form in flash in which user enters his email id and when presses submit button flash passes data to PHP and retrieves(here i am stuck) data from PHP.
The issue is Flash getting UNDEFINED from PHP.
my flash code.
var email_id:RegExp = /(\w|[_.\-])+#((\w|-)+\.)+\w{2,4}+/;
var urlRequest:URLRequest = new URLRequest("forgot_password.php");
var urlVariable:URLVariables = new URLVariables();
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete);
btn_submit.addEventListener(MouseEvent.CLICK, btn_submit_click);
function btn_submit_click(e:Event)
{
if(txt_email.text == "")
{
txt_error.text = "Email can not be blank.";
}
else if(!email_id.test(txt_email.text))
{
txt_error.text = "Enter proper email address.";
}
else
{
urlVariable.mailId = txt_email.text;
urlRequest.data = urlVariable;
urlLoader.load(urlRequest);
}
}
function urlLoader_complete(e:Event)
{
trace(e.target.data.return_var); // **it receive Undefined** i am checking in flashlog.txt :(
//txt_error.text = e.target.data.return_var;
}
my PHP code
<?php
require_once('connection.php');
$query = "select * from user_account where email='".$_REQUEST['mailId']."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
echo "return_var=success";
}
else
{
echo "return_var=failed";
}
?>
there is a space before return_var but i don't know why.. i have checked my PHP file 100 times it is perfect than what is the issue??????????????????????????????????????????
EDIT:
If i am tracing
trace(e.target.data);
it traces
%20return%5Fvar=success
Note %20 before return%5var // what is that?????????????
Obviously problem isn't in PHP, anyway you should write it something like this to prevent SQL injection...
<?php
require_once 'connection.php';
$email = $_GET['mailId'];
$email = mysql_real_escape_string($email);
$query = "SELECT email FROM user_account WHERE email = '$email' LIMIT 1";
$result = mysql_query($query);
echo (mysql_num_rows($result) > 0)? 'return_var=success': 'return_var=failed';
?>
Remove this line:
urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
and change your urlLoader_complete() function to:
function urlLoader_complete(e:Event)
{
var loader:URLLoader = URLLoader(e.target);
var vars:URLVariables = new URLVariables(loader.data);
trace(vars.return_var);
}
does that help?
First of all thank you all for your contributions.
Now the issue was not related with Flash or PHP but it was related with our server. if i am creating PHP file and directly saving on our server than that PHP file gives response with adding one space before variable name. and if i am creating PHP file and saving it in my local drive and than pasting it on my server it works perfectly!!!!!!!!!!!!!!!!!
see the response difference between two files..............
return_var=success
return_var=success // adding space before response.
may be its issue related with memory but now its working fine so cheers!!!!!!!!!
Again many Thanx.

Ajax calling PHP Function

So thanks to the response to my previous question, I've tried to make a code to e-mail me if the code is on another site.
Here is my javascript which is intended for a potential code theif to take with them to their website:
<script type="text/javascript">
var mypostrequest=new ajaxRequest()
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("result").innerHTML=mypostrequest.responseText
}
else{
alert("An error has occured making the request")
}
}
}
var url = document.domain;
var joel="www.joelhoskin.net76.net";
if (url!=joel)
{
mypostrequest.open("POST", "http://www.joelhoskin.net76.net/email.php", true)
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
mypostrequest.send(url)
}
</script>
and here is the php at joelhoskin.net76.net/email.php
`<?php
$url=$_POST['url'];
if(isset($url))
{
$to = 'FlexDevs#gmail.com';
$from = 'Errors#FlexDevs.com';
$subject = 'Stolen Page';
$content = $url."Site Stolen";
$result = mail($to,$subject,$content,'From: '.$from."\r\n");
die($result);
}
?>`
It isn't emailing me like it should
mypostrequest.send(url)
You do send data, but without key. Do it this way:
mypostrequest.send('url='+url)
It should make it work.

Categories