preventing Ajax from sending multiple times - javascript

i am using this script:
https://jsfiddle.net/b7wjj39p/9/
it is running 12 wheels randomly, then the results are bring sent via AJAX to php, who prints them out.
the problem is that the AJAX is being sent 12 times instead of only once.
this is the relevant code who sends the data:
function sendwinnertophp(){
var winner = $("#winner").html();
var winner_two = $("#winner222").html();
var winner_three = $("#winner333").html();
var winner_four = $("#winner444").html();
var winner_five = $("#winner555").html();
var winner_six = $("#winner666").html();
var winner_seven = $("#winner777").html();
var winner_ehight = $("#winner888").html();
var winner_nine = $("#winner999").html();
var winner_ten = $("#winner10").html();
var winner_eleven = $("#winner11").html();
var winner_twelve = $("#winner12").html();
$.ajax({
type: "POST",
url: "getwinner.php",
data: {
"winner": winner,
"winner_two" : winner_two,
"winner_three" : winner_three,
"winner_four" : winner_four,
"winner_five" : winner_five,
"winner_six" : winner_six,
"winner_seven" : winner_seven,
"winner_ehight" : winner_ehight,
"winner_nine" : winner_nine,
"winner_ten" : winner_ten,
"winner_eleven" : winner_eleven,
"winner_twelve" : winner_twelve,
},
cache: false,
success: function(data){
// alert(data);
},
error: function(err){
alert(err);
}
});
}
this is the php code that print the results to an html file:
$file = fopen("log.html", "a");
$ip=$_SERVER['REMOTE_ADDR'];
$winner = $_POST['winner'];
$winner_two = $_POST['winner_two'];
$winner_three = $_POST['winner_three'];
$winner_four = $_POST['winner_four'];
$winner_five = $_POST['winner_five'];
$winner_six = $_POST['winner_six'];
$winner_seven = $_POST['winner_seven'];
$winner_ehight = $_POST['winner_ehight'];
$winner_nine = $_POST['winner_nine'];
$winner_ten = $_POST['winner_ten'];
$winner_eleven = $_POST['winner_eleven'];
$winner_twelve = $_POST['winner_twelve'];
//write the data
$time = date("H:i dS F");
fwrite($file, "<b>Time:</b> $time<br/><b>ip:</b> $ip<br/><b>first:</b> $winner<br/><b>second:</b> $winner_two<br/><b>third:</b> $winner_three<br/><b>forth:</b> $winner_four<br/><b>fifth:</b> $winner_five<br/>
<b>sixth:</b> $winner_six<br/><b>seventh:</b> $winner_seven<br/><b>ehihth:</b> $winner_ehight<br/><b>ninth:</b> $winner_nine<br/><b>tenth:</b> $winner_ten<br/><b>eleventh:</b> $winner_eleven<br/><b>twelvth:</b> $winner_twelve<br/><hr/>" );
fclose( $file )

Related

Send blob image to php

I've created a dynamic upload and I want to send each blob to server after the images are cropped.
The problem is that it's sent only the last append and I don't know why.
var g = 0;
for(var j = 1;j <= boxno;j++) //boxno = 4 pics (I can have as much as I want)
{
input = $("#input"+j);
if(input.val().length !== 0)//check if input has any values
{
pcanvas = $("#pcanvas"+j)[0];
context = pcanvas.getContext("2d");
formData = new FormData($(this)[0]);
var blob = dataURLtoBlob(pcanvas.toDataURL('image/png'));
formData.append("pcanvas_"+g+"[]", blob);
g++;
}
}
var info = {
userid:userId,
username:userName,
picNr: g
}
formData.append("info[]", info["userid"]);
formData.append("info[]", info["username"]);
formData.append("info[]", info["picNr"]);
$.ajax({
url: "/send.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log(data);
},
error: function(data) {
console.log("error");
},
complete: function(data) {}
});
function dataURLtoBlob(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], {
type: contentType
});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {
type: contentType
});
}
Now if I send using this method is sent only "pcanvas3", the last loop. But If I put $.ajax inside the loop is working, but I don't want this, because I want to add into my db and is adding 4 times the same results (also I create new folder for a specific upload, so if I add inside the loop $.ajax it creates 4 folders)
Here is my php.
$id = $_POST['info'][0];
$username = $_POST['info'][1];
$picNr = $_POST['info'][2];
$shuffledid = str_shuffle($id);
$uniqueid = $id.$shuffledid;
$path = $_SERVER['DOCUMENT_ROOT'].'/_user/_tests/en/'.$uniqueid;
if(!file_exists($path))
{
mkdir($path,0755);
}
for($g = 0; $g <= $picNr; $g++)
{
$virtualbg = imagecreatetruecolor(400,410);
$tmp_file = $_FILES['pcanvas_'.$g]['tmp_name'][0];
$pic = imagecreatefrompng($tmp_file);
list($width,$height,$type) = getimagesize($tmp_file);
imagecopyresampled($virtualbg,$pic, 0,0,0,0, 400,410,$width,$height);
imagejpeg($virtualbg,$path.'/pic_'.$g.'.jpg');
imagedestroy($pic);
imagedestroy($virtualbg);
}
As you can see I'm passing through each "pcanvas_0,1,2,3,4" but only the last one it gets the tmp_files.
What I'm doing it wrong? I think the problem is on my append. I've tried to append something else to the formData("pcanvas.. and it works but my blob is not appended.
Thank you!

display data js from datebase sql [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I would like to push my value of textbox to sql and then display it.
I read a lot topics but still nothing. I have always problem to explain my problems but I hope u will see what i want to do escpecialy when u look at db2.php
$("#send").click(function(){
var username = "<span class ='username' = >Klient: </span>";
var newMessage = $("#textbox").val();
nw = newMessage;
$.ajax({
type: "POST",
url: "db2.php",
data: {'name': nw },
success: function (json) {
jss = json.PYT;
oss = json.ODP;
console.log(jss);
}
});
$("#textbox").val("");
var prevState = $("#container").html();
if( prevState.length > 3){
prevState = prevState + "<br>";
}
$("#container").html(prevState + username + newMessage);
$("#container").scrollTop($("#container").prop("scrollHeight"));
ai(newMessage);
});
and my db2.php .
<?php
header('Content-type: application/json');
include 'connect.php';
if (isset($_POST['name'])) {
$name = $_POST['name'];
$queryResult = $connect->query("select * from Chatbot where '$name' LIKE
CONCAT('%',PYT,'%')");
$result = array();
while($pomoc = $queryResult->fetch_assoc()){
$result[] = $pomoc;
}
}
echo json_encode($result);
Now my result is {}, echo is null.
console.log(nw)
VM289:1 dsasa
undefined
I know how to get just output from ajax but if i want to push this data everything goes wrong. Best regards
UPDATE. Now I would like to get jss value out of this function to the other one.
var jss = {}; //(first line code)
$("#send").click(function(){
var username = "<span class ='username' = >Klient: </span>";
var newMessage = $("#textbox").val();
nw = newMessage;
$.ajax({
type: 'POST',
url: 'db2.php',
data: {
'name': nw,
},
success: function(data){
jss = data[0].PYT;
}
});
UPDATE 2
var jss2 = {};
var nw;
$(function(){
username();
$("#textbox").keypress(function(event){
if ( event.which == 13) {
if ( $("#enter").prop("checked") ){
$("#send").click();
event.preventDefault();
}
}
});
$("#send").click(function(){
var username = "<span class ='username' = >Klient: </span>";
var newMessage = $("#textbox").val();
$("#textbox").val("");
var prevState = $("#container").html();
if( prevState.length > 3){
prevState = prevState + "<br>";
}
$("#container").html(prevState + username + newMessage);
$("#container").scrollTop($("#container").prop("scrollHeight"));
ai(newMessage);
});
})
function send_message(message){
var prevState = $("#container").html();
if(prevState.length > 3){
prevState = prevState + "<br>";
}
$("#container").html(prevState + "<span class = 'bot'>Chatbot: </span>" + message);
}
function username(){
$("#container").html("<span class = 'bot'>Chatbot: </span>Hi!");
}
function myFunction() {
var x = document.getElementById("textbox").value;
}
function ai(message){
var jss;
message = message.toLowerCase();
nw = message;
$.ajax({
type: 'POST',
url: 'db2.php',
data: {
'name': nw,
},
success: function(data){
jss = data[0].PYT;
}
});
console.log(jss);
if ((message.indexOf(jss)>=0) || (message.indexOf("?")>=0)){
send_message(Answer);
return;
}
else{
send_message("Nope ");
}
}
I think this is what you need to do with your function so that you can use the jss variable properly, once the ajax request has completed:
function ai(message){
var jss;
message = message.toLowerCase();
nw = message;
$.ajax({
type: 'POST',
url: 'db2.php',
data: {
'name': nw,
},
success: function(data){
jss = data[0].PYT;
console.log(jss);
if ((message.indexOf(jss)>=0) || (message.indexOf("?")>=0)){
send_message(Answer);
return;
}
else{
send_message("Nope ");
}
}
});
}
Any code which relies on the jss variable must not be executed until after the ajax call has completed. Since ajax calls run asynchronously, the only way to guarantee this is for that code to be included in (or triggered from) the "success" callback function in your ajax request.

why my file upload not copied on directory? (javascript, php)

please help
This my constructor in class
$this->covername = $image['cover']['name'];
$this->coverdir = $image['cover']['tmp_name'];
$this->covertype = pathinfo($this->covername, PATHINFO_EXTENSION);
This json script
prosesSave = function(saveas) {
document.getElementById("saveas").value = saveas;
var message = $('#message');
var fields = $("#form1,#form2,#form3");
var formdata = new FormData(fields[0]);
$.ajax({
type: "POST",
url: "project/proses-new-page.php",
data: formdata,
cache: false,
contentType : false,
processData : false,
dataType: 'json',
success: function(response) {
$(message).empty();
if(response.saveas){
if (saveas == 'Draft') {
var idmsg = $("<div></div>", {
"class":"callout callout-info"}).appendTo(message);
}else{
var idmsg = $("<div></div>", {
"class":"callout callout-success"}).appendTo(message);
}
}else{
var idmsg = $("<div></div>", {
"class":"callout callout-danger"}).appendTo(message);
}
$(idmsg).empty().html(response.html);
document.getElementById("status").value = "EditPage";
document.getElementById("idpage").value = response.idpage;
}
});
return false;}
This my process copy
if ($this->covername) {
$this->filename = $id."_".$this->date.".".$this->covertype;
$this->move = $this->dirupload."cover/".$this->filename;
if(!move_uploaded_file($this->coverdir, $this->move)){
$this->response_html = '<p>Faild</p>'.$this->covername."<br>".$this->coverdir."<br>".$this->move;
}else{
$this->response_html = '<p>Succes</p>'.$this->covername;
}
chmod($this->move, 0777);
mysqli_query($this->conn, "UPDATE tb_pages SET COVER_PAGE = '".$this->filename."' WHERE ID_PAGE = '".$id."'");
}
i have problem with my code. in this code name of image, type and so on can insert into database. but on the image can't copied in directory($this->coverdir).
sory for my bad english.

update values in the textboxes using javascript

actualy im just a newbie programmer and i made my own update javascript function for my program but sadly the codes doesnt update..can anyone help me assist in order my codes work? please.
i want to do is if i change the values in the textboxes and click update it will update.
script:
<script type="text/javascript">
$(document).ready(function() {
$('#updates').click(function() {
$id1 = $('#id1').val();
$di2 = $('#id2').val();
$name1 = $('#name1').val();
$name2 = $('#name2').val();
$optA1 = $('#optA1').val();
$optA2 = $('#optA2').val();
$optB1 = $('#optB1').val();
$optB2 = $('#optB2').val();
$other_qual1 = $('#other_qual1').val();
$other_qual2 = $('#other_qual2').val();
$interview1 = $('#interview1').val();
$interview2 = $('#interview2').val();
$total1 = $('#total1').val();
$total2 = $('#total2').val();
$.ajax({
type: "POST",
cache: false,
url: "update.php",
data: "id1_text="+$name1,
data: "id2_text="+$name1,
data: "name1_text="+$name1,
data: "name2_text="+$name2,
data: "optA1_text="+$optA1,
data: "optA2_text="+$optA2,
data: "optB1_text="+$optB1,
data: "optB2_text="+$optB2,
data: "other_qual1_text="+$other_qual1,
data: "other_qual2_text="+$other_qual2,
data: "interview1_text="+$interview1,
data: "interview2_text="+$interview2,
data: "total1_text="+$total1,
data: "total2_text="+$total2,
success: function(data) {
alert('data has been updated!');
}
});
});
});
</script>
update.php code:
<?php
mysql_connect("localhost","root","") or die ("cant connect to database!");
mysql_select_db("test") or die ("cant find database!");
$id1=$_POST['id1_text'];
$id2=$_POST['id2_text'];
$name1=$_POST['name1_text'];
$name2=$_POST['name2_text'];
$optA1=$_POST['optA1_text'];
$optA2=$_POST['optA2_text'];
$optB1=$_POST['optB1_text'];
$optB2=$_POST['optB2_text'];
$other_qual1=$_POST['other_qual1_text'];
$other_qual2=$_POST['other_qual2_text'];
$interview1=$_POST['interview1_text'];
$interview2=$_POST['interview2_text'];
$total1=$_POST['total1_text'];
$total2=$_POST['total2_text'];
$query1=mysql_query("UPDATE score SET name='$name1', score1='$optA1', score2='optB1', other_qual='$other_qual1', interview='$interview1', total='$total1' WHERE id='$id1'");
$resource1 = mysql_query($query1)
or die (mysql_error());
$query2=mysql_query("UPDATE score SET name='$name2', score1='$optA2', score2='optB2', other_qual='$other_qual2', interview='$interview2', total='$total2' WHERE id='$id2'");
$resource2 = mysql_query($query2)
or die (mysql_error());
?>
You had quite a few errors in your code. For example, you had a wrong syntax when you assigned data in the JS-code. It should be in this form:
data: { val:$("#selector").val, val2:$("#selector2").val(), /* etc etc*/ }
Solution
Try this code:
JS
<script type="text/javascript">
$(document).ready(function () {
$('#updates').click(function (e) {
e.preventDefault();
var id1 = $('#id1').val();
var id2 = $('#id2').val();
var name1 = $('#name1').val();
var name2 = $('#name2').val();
var optA1 = $('#optA1').val();
var optA2 = $('#optA2').val();
var optB1 = $('#optB1').val();
var optB2 = $('#optB2').val();
var other_qual1 = $('#other_qual1').val();
var other_qual2 = $('#other_qual2').val();
var interview1 = $('#interview1').val();
var interview2 = $('#interview2').val();
var total1 = $('#total1').val();
var total2 = $('#total2').val();
$.ajax({
type: "POST",
cache: false,
url: "update.php",
data: {
id1_text: name1,
id2_text: name1,
name1_text: name1,
name2_text: name2,
optA1_text: optA1,
optA2_text: optA2,
optB1_text: optB1,
optB2_text: optB2,
other_qual1_text: other_qual1,
other_qual2_text: other_qual2,
interview1_text: interview1,
interview2_text: interview2,
total1_text: total1,
total2_text: total2
},
success: function (data) {
alert('data has been updated!');
}
});
});
});
</script>
PHP
<?php
if (isset($_POST['id1_text'])) {
mysql_connect("localhost", "root", "") or die("cant connect to database!");
mysql_select_db("test") or die("cant find database!");
$id1 = $_POST['id1_text'];
$id2 = $_POST['id2_text'];
$name1 = $_POST['name1_text'];
$name2 = $_POST['name2_text'];
$optA1 = $_POST['optA1_text'];
$optA2 = $_POST['optA2_text'];
$optB1 = $_POST['optB1_text'];
$optB2 = $_POST['optB2_text'];
$other_qual1 = $_POST['other_qual1_text'];
$other_qual2 = $_POST['other_qual2_text'];
$interview1 = $_POST['interview1_text'];
$interview2 = $_POST['interview2_text'];
$total1 = $_POST['total1_text'];
$total2 = $_POST['total2_text'];
$query1 = mysql_query("UPDATE score SET name=$name1, score1=$optA1, score2=$optB1, other_qual=$other_qual1, interview=$interview1, total=$total1 WHERE id=$id1");
$resource1 = mysql_query($query1) or die(mysql_error());
$query2 = mysql_query("UPDATE score SET name=$name2, score1=$optA2, score2=optB2, other_qual=$other_qual2, interview=$interview2, total=$total2 WHERE id=$id2");
$resource2 = mysql_query($query2) or die(mysql_error());
}
?>

Sending an array of objects to PHP function with jQuery.ajax request

There is an array of objects like this:
rectangle[0].width = w;
rectangle[0].height = h;
rectangle[1].width = w;
rectangle[2].height = h;
rectangle[3].width = w;
rectangle[3].height = h;
...
How we may to send this array to PHP function with jQuery.ajax request and vise versa, modified array from PHP function as response?
I mind that JS code may be:
request = $.ajax({
type : "POST",
url : "post.php",
data : {rec :rectangle}
});
request.done(function(msg) {
alert(msg);
});
request.fail(function(jqXHR, textStatus) {
alert("Function inaccessible: " + textStatus)
});
and PHP:
if (isset($_POST["rec"]) {
$rec = $_POST["rec"];
$arr_length = count($rec);
$response = $arr_length;
}
echo $response;
Please, demonstrate the true form of request. Thanks.
Very easy:
<script>
var myarray = new Array();
var params = { myarray: myarray };
var paramJSON = JSON.stringify(params);
$.post(
'test.php',
{ data: paramJSON },
function(data) {
var result = JSON.parse(data);
}
</script>
php side:
if(isset($_POST["data"]))
{
$data = json_decode($_POST["data"]);
$myarray = $data->myarray;
foreach($myarray as $singular)
{
// do something
}
}

Categories

Resources