dimanche 19 avril 2015

Passing PHP Array to AJAX and displaying them on the screen

I would like to make my website more interactive. I have registration form, and I would like to display icons (correct/false) after the register button has been clicked so the user can see what field is not correct.


enter image description here


I know that I need to use json_encode to pass an array via ajax.


This is an example of my php code which I would like to use to control the registration form.



if(isset($_POST['register'])){
$errors = array();
$user = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];

if(empty($user)){
$errors[] = "You need to fill username.";
}
if(strlen($password) < 3){
$errors[] = "This Password is to short";
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors[] = "This e-mail is not correct ";
}

if(empty($errors)){
$db->query("INSERT INTO users (user,pass,email)VALUES ('$user','$password','$email')");
}

if(!empty($errors)){
json_encode($errors);
}
}


I don't want refresh page.


clonig google pie chart with jquery triggers XMLHttpRequest error

I have a google pie chart which displays correctly on my page. Now I want to clone that chart in another div of my website. It's unfornuately throwing a XMLHttpRequest error :



XMLHttpRequest cannot load http://ift.tt/1JWNuXN. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://foodmeup.dev' is therefore not allowed access.



How can I overcomethis ?


My view :



<div id="piechart" style="height: 220px;"></div>
<div id="profile_completion_graph" class="responsive">
//the div in which I want to clone the graph
</div>

<script type="text/javascript">
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Nom', 'Valeur'],
["Profil rempli à ", {{ completeness }}],
['Manque', {{ 100 - completeness }}]
]);

var options = {
backgroundColor: { fill:'transparent'},
pieSliceBorderColor : 'transparent',
pieHole: 0.8,
legend: {position: 'top'},
width: 220,
height: 220,
tooltip: {trigger: 'none'},
pieStartAngle: -90,
pieSliceTextStyle :{fontsize : 16, color: 'transparent'},
slices: {
0: { color: '#09b4ff'},
1: { color: '#444'}
},
chartArea : {width: '90%', height: '90%'}
};

var chart = new google.visualization.PieChart(document.getElementById('piechart'));

chart.draw(data, options);
}

google.load('visualization', '1', {callback : function(){drawChart();}, 'packages':['corechart']})


</script>

<script>
$(function(){
var $graphs = $('#chart_picture').clone();
$('#profile_completion_graph').eq(0).html($graphs);
});
</script>

AJAX Login form not working

I have the following ajax script and form to login to my website:



<legend>Log In</legend>
<div class="input-group">
<span class="input-group-addon">E-Mail</span>

<input type="email" class="form-control" name="email" value="" /><br />
</div>
<div class="input-group">
<span class="input-group-addon">Password</span>

<input type="password" class="form-control" name="password" />
</div>

</fieldset>

<input type="submit" class="btn btn-primary" value="Log In" name="submit" />

</form></div>
<script>
$.ajax({
type: "post",
url: "/doLogin",
data: $('#login').serialize(),
success: function(result) {
if(result == " success"){
window.location = "/index.php";
}else if(result == " failure"){
$("#alert").html("<div class='alert alert-warning'>Either your username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
}
});


but it doesn't preform the ajax, and brings me to the result page, which is not what I want. Is there any specific reason that the AJAX is not working? I'm kind of new to JavaScript so sorry if this is obvious.


ASP.NET MVC calling server from javascript function with ajax

I am trying to call the following action method in a controller from a javascript function in a partial view:



[HttpPost]
public JsonResult RemoveNotifications(IList<Notification> notifications)
{
Context.Notifications.RemoveRange(notifications);
return new JsonResult();
}


This is the function that should call the server from the view:



function show(message) {
message += "</ul>"
document.getElementById('notifications').innerHTML = message;
$.ajax({
url: '@Url.Action("RemoveNotifications", "Notification")',
type: 'POST',
data: { 'notifications': "@Model.Notifications" },
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
}
});
}


The first part works fine, but the $.ajax part dosen't do anything. I also have the following added at the top of my view:



<script src="http://ift.tt/1bhFrtf" type="text/javascript"></script>
<script src="http://ift.tt/1bhFrth" type="text/javascript"></script>
<script src="http://ift.tt/1bhFrtj" type="text/javascript"></script>

jQuery Submit Form (w/ file and text) without redirecting from current window

I want to build an application form where on can attach an image - it's just a couple of input elements - within a div (not an form element). The form shall be processed without an page redirect. So I use ajax. Everything works fine so far. But now I need to add an image.



$('#submit_application').click(function () {
//...
$.ajax({
url: 'submit.php',
type: 'post',
data: {
'action': 'submit',
'image': $('#image_upload').val(),
// ..
'someStringifiedJSON': JSON.stringify(foo)
},
success: function (data, status) {
// ...
},
error: function (xhr, desc, err) {
// ...
}
});
});


How can I get my file into php's $_FILES variable? Or how can I pass the file to php so that I can upload it?


success event issue

I am not so good at JavaScript nor jQuery, but I try to learn it. I am creating a contact form with ajax sending, honeypot and fancybox. I am almost done, but I have feeling, that event success in ajax does not work. Here is part of code:



$.ajax({
type: 'POST',
url: '../data/sendmessage.php',
data: $("#contactForm").serialize(),
success: function (data) {
if (data === "true") {
$("#contactForm").fadeOut("fast", function () {
$(this).before("<p><strong>Thank you for message</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
}
});


I thought, it will show the message and then close fancybox, but it doesn't. Can somebody help me to understand, what am I doing wrong? ...I hope this part of code is enough, if not, I will be glad to add whole the script, but that should work OK.


jQuery get json data, match the ids, then append the custom field value

I am trying to retrieve json data from zendesk, then compare the value of the ids in each ticket that is retrieved from the server with the id inside my table data. If the ids match, then I want to retrieve the custom field value inside the ticket with the matching id, and append it to the table data's that i have named with the product id. The idea is to target each "td/td",and automatically insert the custom field(product id) value when a new "td/td" tag is created. Please help :) The Object 99 at the top is the ticket, the id :175 is the id I am trying to match. the custom_field array[10] value is what I want to append and display. The issue I am having is that the data is not displaying after I append it. I think this has something to do with how I am accessing the data, comparing the ids, then appending the custom field. The array value is returning a -1 instead of comparing the IDs. This is the problem.



//first lets get some json data!
var getjson = $.getJSON("/api/v2/tickets.json)",function (result) {
$.each(result, function(i, field) {
console.log('data',field);

// now lets take the text id for each td and assign it as the id.
$(".sort > tr > td:nth-child(1)").each(function(){

var textid = $(this).text();
$(this).attr('id', textid);
// if the ids match, give me the value of the custom field that is inside the array of the matching id.
var arr = [field];
var arrayvalues = $.inArray('id', arr);
if ($(this).attr('id') == arrayvalues){

/* if the ids match, give me the value of the
custom field that is inside the array of the matching id. */

var returns = $.inArray('value',arr.custom_fields[i]);


// now for each td lets append the value of the custom field.
$(".sort > tr > td:nth-child(7)").each(function () {
$(this).append(returns);
$(this).attr('id','product');
})

}

})
});

Leaflet AJAX Map FitBounds

I am searching for a solution to fit a leaflet map's bounds to display the content of a loaded geoJSON file.


For loading the file I use leaflet-ajax. I tried already this, but I have no idea how I can get the layer's bounds. Any Suggestions how I can adjust the displayed map sector to display the geoJSON file? Thanks.





var geojsonLayer = new L.GeoJSON.AJAX('http://localhost:8080/test.geojson');
geojsonLayer.addTo(this.map);
this.map.fitBounds(geojsonLayer.getBounds());



Jasmine: stub an ajax success call and pass the function an argument

I am looking to write a test in Jasmine that expects a string to be displayed in the browser when a button is clicked, that triggers an AJAX call returning a JSON object from an API which then has a function run on it, to extract the required data.


Using the Jasmine Ajax documentation I have come up with the following solution, which is working, but I have noticed a weakness in this test.



beforeEach(function(){
jasmine.getFixtures().fixturesPath = '.';
loadFixtures('thermostat.html');
});

describe("displaying weather from open weather map api", function() {

it("can display current temp for London", function(){
jasmine.Ajax.install();
var weatherobject = {"main": {"temp": 12.09}}
jasmine.Ajax.stubRequest('http://ift.tt/1mGUATE').andReturn({
success: loaddata(weatherobject)
});
$("#London").click();
expect("#weatherapidata").toContainHtml("12.09");
jasmine.Ajax.uninstall();
});
});


Below is the javascript and jQuery it is testing. If the function contents, in the success response, of this code, are changed to something other than loaddata the tests will still pass, as loaddata is also called in the test, as I could not work out how to pass the success function an argument of the weatherobject in the test.



$(document).ready(function(){

$('#London').click(function(){
$.ajax({
url: "http://ift.tt/1mGUATE",
data: {
q:"London",
units:"metric",
APPID: weatherapikey
},
success: function(data){
loaddata(data);
}
});
});
});

function loaddata(data) {
$("#weatherapidata").text(data.main.temp);
};


Therefore my question is; is it possible to construct the jasmine test stub to pass the data parameter of function in the success response an argument of the weatherobject?


My thoughts were to pass the object as a string in responseText, in the following way



jasmine.Ajax.stubRequest('http://ift.tt/1mGUATE').andReturn({
responseText: weatherobject
});


(I also tried JSON.stringify(weatherobject) as the responseText callback in this format) but I could not get this to work and hence my above solution was the workaround.


Github link to this project


Making a simple form validator with AJAX and JSON but without jQuery

1.html : My goal is to make a simple form with name, password and password confirmation with AJAX and JSON but absolutely without jQuery.


2.javascript: make a XMLHttpRequest() with POST


3.JSON : make a php file for JSON.parse()


I want to check the availability of login and the equality of password


HTML:



<form>
<div>
<label>Login</label>
<input placeholder="Login" type="text" name="login" id="login"/>
</div>
<div>
<label>Password</label>
<input placeholder="password" type="password" name="password1" id="password1"/>
</div>
<div>
<label>Confirm Password</label>
<input placeholder="password" type="password" name="password2" id="password2"/>
</div>
<div>
<button type="submit" name="submit" id="submit">Send</button>
</div>


<div id="response"> <h1>Response</h1> </div>


JAVASCRIPT:



(function () {
var bouton = document.getElementById('submit');
var reponse = document.getElementById('reponse');

bouton.addEventListener('click', ajax, false);

function ajax() {
var xhr = new XMLHttpRequest();
var $$$ = document.getElementById('$$$').value;
var url = 'file.php?$$$=' + $$$;

xhr.open(
'POST',
url
);

xhr.send(null);

xhr.onreadystatechange = function () {


switch (xhr.readyState) {
case xhr.DONE:
if (xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
reponse.innerHTML += '<p>' + json + '</p>';

} else {
console.log('STATUS (' + xhr.status + ') : ' + xhr.statusText);
}

break;

default:
console.log('DEFAULT CASE');

break;
}
};
}
})();


PHP File:


I don't know ... with JSON




Thank you for your great help !


How to get photo_id to pass through on Ajax POST method - Django

I am trying to create a "like" button where each time a user likes the post, the count will increase by one and add the user's name to it. When I click my button, only the csrf token passes through. What is wrong with my code that I cannot get the photo_id to pass through?


Thank you in advance!


views.py:



def like_ajax(request):
if request.is_ajax() and request.POST:
like_item_id = request.POST.get('photo_id', '')
try:
new_like = LikeItem.objects.get(id=like_item_id)
except:
new_like = None
if new_like:
message = "success"
if request.user in new_like.likers.all():
new_like.likers.add(request.user)
new_like.save()
like_count = add_new.likers.count()
did_like = True
else:
new_like.likers.remove(request.user)
new_like.save()
vote = add_new.likers.count()
did_like = False
else:
message = 'error'
like_count = 0
did_like = False

data = {
"did_like": did_like,
"like_count": like_count,
"message": message,
}
new_data = json.dumps(data)
return HttpResponse(new_data, content_type='application/json')

else:
raise Http404


models.py:



class LikeItem(models.Model):
likers = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='Likers', null=True, blank=True)
image = models.ForeignKey(Photo)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True, default=timezone.now())


jquery:



$('.like_btn').click(function(e){
e.preventDefault();
$photo_id = $(this).attr("photo_id");
$button = $(this);
$.ajax({
type: "POST",
url: "{% url 'like_ajax' %}",
data: {
'photo_id': $photo_id,
csrfmiddlewaretoken: "{{ csrf_token }}",
},
dataType: "json",
success: function(data) {
if (data.liked) {
data.like_count;
// do something after item is liked
// can get count with data.like_count
} else {
data.like_count;
// item is no longer liked
}
},
error: function (rs, e) {
alert('Sorry, there was an error with your request. Please try again later.');
}
});

});


html button:



<button class="like_btn btn btn-info" value="photo_id" type="button">Like this</button>

Rails 4 - update value or data attribute in form from ajax and use this updated value in an if statement

I have a Rails app in which Users can belong to one or many Teams. Users can create ideas for each team. I want the form for Ideas to look and behave slightly different depending on how many teams the user is a member of. If a user isn't a member of any teams this message will be shown: You need to create a team first, before the user can create any ideas.


The issue I'm having is that I create Teams with Ajax. In the ideas form I currently have conditions like this:



- if current_user.teams.count == 0
You need to create a team first
- else
[..]


Since I create the teams using Ajax, this message is being displayed even when the user have created his / her first team. Unless he / she reloads the page of course, then it works. But I want to have a seamless experience.


So this condition:



- if current_user.teams.count == 0


Needs to be changed into something that I can access and update from a js.erb file, and I'm not quite sure how I can achieve that.


I was thinking of possibly using a hidden_field_tag, that I can update in Ajax. But I'm not sure how my if statement in the view would look then. I have tried the following without success (I use HAML):



= hidden_field_tag "team_count", current_user.teams.count, id: :team_count

:javascript
if ($("#team_count").val > 1) {
[...]
} else {
[...]
}


Any ideas on what I should do instead?


Cant detect the file in ajax

Hey guys am new to ajax I have a php file and a ajax file. I just want to detect the php file from the ajax so I have send a request in ajax like



<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
} else {
console.log('file not fetched');
}

xmlhttp.open("GET","first.php?m=babe",true);
xmlhttp.send();
}
}
loadXMLDoc();
</script>
</head>
<body>
</body>
</html>


My php file



<?php
include("ajax.html");
$p = $_REQUEST['m'];
if($p == 'babe') {
echo true;
}


When I run the ajax.html on localhost it doesn't show me any message in the window nor in the console.


Can you guys tell me why is it like this?


Thanx for the help


ajax is not completing the request

I am using ajax, php and a html form.


Ajax function:



$(document).ready(function(){
$('#set_like').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/noutati/articol',
data: $(this).serialize(),
success: function () {
alert('Succes!');
}
});
e.preventDefault();
});
});


HTML:



<form id="set_like" enctype="multipart/form-data" action="<?php echo base_url();?>noutati/articol" method="post">
<input type="submit" name="submit-like-up" data-id="<?php echo($li_position); ?>" class="like-up" value="submit_up" /> <span class="counter-like-up<?php echo($li_position); ?>"><?php echo($comment->like_up); ?></span>
<input type="submit" name="submit-like-down" data-id="<?php echo($li_position); ?>" class="like-down" value="submit_down" /> <span class="counter-like-down<?php echo($li_position); ?>"><?php echo($comment->like_down); ?></span>
</form>


It shows the Succes! alert, but is not completing the PHP request. Any ideas why?


How do i get json value


error:function(response)
{
alert("e"+typeof response+" "+Object.keys(response).length+" "+" "+response.txt);
} /*use console.log*/


This is my error callback function in ajax post method.


I am returning data from php as follows



die('{"status":0,"txt":"Email Already Exists"}');


It is valid json and i checked with jsonlint. [But i have doubt with this die statement validity too]


I am getting the alert as follows



eobject 21 undefined


Yes, It is JSON Object. 21 characters are totally in the keys[Not sure whether my assumption is correct]. But how response.txt is undefined. If i print response it says object object.


But i din't see any response in Net tab of chrome under my php file. Actually ajax callback is in my html page. die code is from my php page.


Please correct me if i am wrong.How to get my JSON values.


Ajax response getting client side html on iE 8

I have a ajax file upload code that gets back a json response from the server. The response works fine on Chrome, FF and IE 11 but on lesser versions of IE the response is getting the client side html instead of the json response. The jquery version am using is 1.5.1. I have tried setting the content type to text/html also the x-frame-option to Sameorigin but this didn't help.


Anyone who has found solution to this problem please help.


Slide new entry ajax

Hello i need to display by slide multiple entry by ajax my script work just for one entry



var newTxt = ['hello', 'hi'];
for(var i = 0; i <= newTxt.length; i++) {
$('#txt').prepend('<li class="none">' + newTxt[i] + '</li>');
$('#txt li:first-child').toggleClass("none", 2000);
}


i use css and toggleClass for animation



li { width:100px; }
li.none { width:0px; }


The animation work with 1 entry but with more not work u have solution for display by slide one by one ?


Thanks you


unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in PHP MYSQL

I get the above error when i run the code. Please tell me where i've gone wrong.


I'm trying to get the values and encode them with JSON and save them into the database. Then later on i'm gonna retrieve the data from the database, decode it, and send it to the client end. Following is my php code.



<?php

$name = $_POST['fname'];
$email = $_POST['email'];
$comment =$_POST['comment'];
$website = $_POST ['website'];
$rate = $_POST['rate'];


$conn = mysqli_connect("localhost","root","","webtech");
if(!$conn){
die("Connection Failed : ".mysqli_connect_error());
} else{
echo "Connection Succesful ";
}

$jsonDb = array
(
'name' => $name,
'email'=> $email,
'comment'=> $comment,
'website'=> $website,
'rate'=> $rate
);

$jsonArray = array
(
'name' => $name,
'email'=> $email,
'comment'=> $comment,
'website'=> $website,
'rate'=> $rate
);

$encodeDatabase = json_encode($jsonDb);


$encodeArray = json_encode($jsonArray);
mysql_query("INSERT INTO comments VALUES ("."'".$jsonDb['name']."'"."," ."'".$jsonDb['email']."'".","."'".$jsonDb['website']."'".","."'".$jsonDb['comment']."'".","."'".$jsonDb['rate']."'".")");

echo $encodeDatabase;




?>

Check Variables of different scripts to match in PHP

Hi there I have an idea and I don't know if its possible to work it out but Ive got few different methods for it and I don't know which one to pick and which one will work better but Here is what I have:





//##CHAT.php
$sqlmessages = mysql_query("SELECT * FROM chat");
$numbermessages = mysql_num_rows($sqlmessages);
session_start();
$_SESSION['chatnum'] = $numbermessages;



//##checkanynewmessages.php
$url="checkanynewmessages.php";
header("Refresh: 5; URL=$url1");
$oldmessages = $_SESSION['chatnum'];
$sql1messages = mysql_query("SELECT * FROM chat");
$newnumchat = mysql_num_rows($sql1messages);
if($oldmessages===$newnumchat) {
//do nothing
} else {
//it should refresh the chat.php because its required in the page
echo "<script>window.location = window.location.href;</script>";
}



And the other solution would be if I figure out how AJAX or Javascript or JQuery would refresh the page if It could check for the mysql table but I don't know how its done in those languages ... thanks!


JQuery Ajax not interacting with MySQL

I'm attempting to make a very basic browser MMORPG with php, ajax, and jquery. However the webpages do not seem to be interacting with the MySQL server correctly.


Here is my php class that defines some SQL functions:



<?php
class Db {
protected static $connection;

public function connect() {
if(!isset(self::$connection)) {
$config = parse_ini_file('config.ini');
self::$connection = new mysqli('localhost',$config['username'],$config['password'],$config['dbname']);
}
if(self::$connection === false) {
return false;
}
return self::$connection;
}

public function query($query) {
$connection = $this -> connect();
$result = $connection -> query($query);
return $result;
}

public function select($query) {
$rows = array();
$result = $this -> query($query);
if($result === false) {
return false;
}
while ($row = $result -> fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}

public function error() {
$connection = $this -> connect();
return $connection -> error;
}

public function quote($value) {
$connection = $this -> connect();
return "'" . $connection -> real_escape_string($value) . "'";
}
public function close()
{
mysqli_close(self::$connection);
}
}
?>


Along with the config.ini it references:



[database]
username = root
password = ***
dbname = ***


(password and database name have been omitted but I've checked that they are correct.)


Here is my validation.php file that the login uses:



<?php
include 'DbClass.php';
$db = new Db();
$name= = $db -> quote($_POST['user_name']);
$pass=md5($db -> quote($_POST['password']));
$rows = $db -> select("select * from players where name=" . $name . " and password=" . $pass);
if($rows)
{
echo json_encode("1");
}
else
{
echo json_encode("0");
}

?>


And here is the login javascript file with the functions that are called on my index page.



function login()
{
$("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000);
$.ajax({
url : 'scripts/php/validation.php',
type : 'POST',
data : { user_name:$('#username').val(),password:$('#password').val()
},
dataType:'json',
success : function(data) {
if(data == 1)
{
$("#msgbox").fadeTo(200,0.1,function()
{
$(this).html('Logging in...').addClass('alert alert-success').fadeTo(900,1,
function()
{
buildPage();
});

});
}
else
{
$("#msgbox").fadeTo(200,0.1,function()
{
$(this).html('Your login details are incorrect').addClass('alert alert-danger').fadeTo(900,1);
});
}
}
});
}

function registration()
{
document.getElementById("registerBox").innerHTML = "<form class='form-horizontal' method='post' action='' id='register_form'>" +
"<div class='row'><div class='col-md-6 column'><div class='control-group'>" +
"<label class='control-label' for='username'>Username</label><div class=''controls'>" +
"<input type='text' id='registerUsername' placeholder='Username'>" +
"</div></div>" +
"<div class='control-group'>" +
"<label class='control-label' for='password'>Password</label>" +
"<div class='controls'>" +
"<input type='password' id='registerPassword' placeholder='Password'>" +
"</div><br></div>" +
"<div class='control-group'>" +
"<label class='control-label' for='rePassword'>Retype Password</label>" +
"<div class='controls'>" +
"<input type='password' id='rePassword' placeholder='Retype Password'>" +
"</div><br></div><div id='registerMsgbox'></div></div>" +
"<div class='col-md-3 column'>" +
"<b><u>Choose a Class</b></u><br><div id='characters'></div>" +
"</div></div>" +
"<div class='control-group'>" +
"<div class='controls'>" +
"<input name='Submit' type='button' onclick='javascript:register()' value='Register' class='btn btn-success'/>" +
"</div></div></form>";
$.ajax({
url : 'scripts/php/getCharacters.php',
type : 'POST',
data : {type:'classes'
},
dataType:'json',
success : function(data) {
buildClasses(data);
}
});
}

function loginPage()
{
document.getElementById("registerBox").innerHTML = "<form class='form-horizontal' method='post' action='' id='login_form'>" +
"<div class='control-group'>" +
"<label class='control-label' for='username'>Username</label>" +
"<div class='controls'>" +
"<input type='text' id='username' placeholder='Username'></div></div>" +
"<div class='control-group'> " +
"<label class='control-label' for='password'>Password</label>" +
"<div class='controls'>" +
"<input type='password' id='password' placeholder='Password'>" +
"</div><br>" +
"<div id='msgbox'></div></div>" +
"<div class='control-group'>" +
"<div class='controls'>" +
"<input name='Submit' type='button' onclick='javascript:login()' value='Login' class='btn btn-success'/>&nbsp;&nbsp;" +
"<input name='Submit' type='button' onclick='javascript:registration()' value='Register' class='btn btn-success'/>" +
"</div>" +
"</div>" +
"</form></div><div class='modal-footer'></div>";
}

function buildClasses(data)
{
var characterDiv = "";
for(var i = 0; i < data.length; i++)
{
characterDiv += "<div class='characterBox'><input type='radio' name='radioClasses' value='" + data[i].id + "'><img src='media/characters/heroTiles/" + data[i].pic + ".png'>" + data[i].name + "</div>";
}
document.getElementById("characters").innerHTML = characterDiv;
}


I also have a registration script that doesn't do anything to the database either, but I figure for the sake of having less code covering the page that posting that probably isn't required, since I assume the issue is somewhere in my database function class or one of these other places.


$_FILES is null, $_POST is empty array

I am trying ajax file upload. I've tried the same script in another proect. It worked properly. But now its not working. On the server side I get 'Null' with var_dump($_FILES["uploadFiles"]); and var_dump($_POST["uploadFiles"]); returns an empty array: array(1) { [0]=>string(0)""}


So I suspect some issues with apache/php configuration.


One of the solution given here discusses about htaccess redirect rules. Here is my htaccess content:



# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress</code>


Is there any thing wrong with my htaccess content?


If not what else may be the reason for $_FILES to be Null?


My php.ini variables:



post_max_size = 160M
upload_max_filesize = 100M
upload_tmp_dir = "/tmp/"
file_uploads = On
max_file_uploads = 20


Thanks in Advance for your help.


update:


Response headers of in browser: enter image description here


Here is my code:



<form class="inputF" id="entry_upload_form" action="" method="post" enctype="multipart/form-data">

<div class="field_text">
Attach file:
</div>
<input type="file" name="file1[]" id="file1"> <br>

<div class="field_text">
Attach file:
</div>
<input type="file" name="file2[]" id="file2"> <br>

<div class="field_text">
Attach file:
</div>
<input type="file" name="file3[]" id="file3"> <br>

<div class="buttonRow">
<button class="submit buttons greenButton">Post</button>
<button class="reset buttons blueButton">Reset</button>
</div>
</form>


part of my jQuery:



var fileSelect = document.getElementById('file1');
files1 = fileSelect.files;

if(files1.length != 0) {
files[i] = fileSelect.files;
i++;
}

fileSelect = document.getElementById('file2');
files1 = fileSelect.files;

if(files1.length != 0) {
files[i] = fileSelect.files;
i++;
}

fileSelect = document.getElementById('file3');
files1 = fileSelect.files;

if(files1.length != 0) {
files[i] = fileSelect.files;
i++;
}

// Create a new FormData object.
var formData = new FormData();

// Loop through each of the selected files.
for (var i = 0; i < files.length; i++) {
var file = files[i];

// Add the file to the request.
formData.append('uploadFiles[]', file, file.name);
}

jQuery.ajax({
url: content_url + '/themes/Karma/entry-portal/ajax_upload.php', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = jQuery.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: function () {
//jQuery("#wpboulevard_progressBar").show();
},
success: function (response) {
//jQuery('#wpboulevard_upload_status').html(response);
},
//error: errorHandler,
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});

return false;
//On success
function completeHandler(){
jQuery().html('Files uploaded successfully');
}

//Progress handling function
function progressHandlingFunction(e){
if(e.lengthComputable){
jQuery('progress').attr({value:e.loaded,max:e.total});
}
}
});

Ajax not appending to my drop down list (C# MVC)

I'm busy with 2 drop downs. The first one is country and loads fine, then on country change I call ajax to populate the province drop down.


The code works fine and when I put an alert in my ajax call it shows the correct data being created but it doesn't append it the drop down so the values aren't available.


Drop Down



<div class="form-group">
<label class="col-md-3 col-xs-5 control-label">Country:</label>
<div class="col-md-9 col-xs-7">
@Html.DropDownListFor(x => x.CountryId, (IEnumerable<SelectListItem>)ViewBag.CountryItems, "Please Select", new { @id = "ddlCountry", @class = "form-control select" })
</div>
</div>
<div class="form-group">
<label class="col-md-3 col-xs-5 control-label">Province:</label>
<div class="col-md-9 col-xs-7">
@Html.DropDownListFor(x => x.ProvinceId, Enumerable.Empty<SelectListItem>(), "Please Select", new { @id = "ddlProvince", @class = "form-control select" })
</div>
</div>


The Ajax



<script>
$('#ddlCountry').change(function () {
var countries = document.getElementById("ddlCountry");
var countryId = countries.options[countries.selectedIndex].value;

$.ajax({
url: "/Master/GetProvinces",
data: { countryId: countryId },
dataType: "json",
type: "GET",
error: function () {
alert(" An error occurred.");
},
success: function (data) {
$.each(data, function (i) {
var optionhtml = '<option value="' + data[i].Value + '">' + data[i].Text + '</option>';
$("#ddlProvince").append(optionhtml);
});
}
});
});
</script>


The code behind



public ActionResult GetProvinces(string countryId)
{
IEnumerable<SelectListItem> ProvinceItems = null;

if (!string.IsNullOrEmpty(countryId))
{
ProvinceItems = BusinessAPI.ProvinceManager.GetAllProvincesByCountryId(Convert.ToInt32(countryId)).Select(ci => new SelectListItem
{
Value = ci.Id.ToString(),
Text = ci.Name
});
}

return Json(ProvinceItems, JsonRequestBehavior.AllowGet);
}

PHP and JSON output with and without key

I have a weird bug, and uncertain what causes it. Perhaps there is an error somewhere in my code.


This is the JSON that PHP (via Ajax) sends to the browser for JQuery to use, and this is the correct way, and how i want it.



{"response":"success","comment":"<strong>Done.<\/strong> Your details has been updated.","id":"4","images":[{"Image":"\/cache\/Products\/picture.jpg"},{"Image":"\/cache\/Products\/picture2.jpg"}]}


But the odd occasion i get the following:



{"response":"success","comment":"<strong>Done.<\/strong> Your details has been updated.","id":"4","images":{"1": {"Image":"\/cache\/Products\/picture.jpg"},"2":{"Image":"\/cache\/Products\/picture2.jpg"}}}


The Images JSON array changes! Yet they both use the same code.


This is the PHP case, that Ajax calls.



case 'removeImages':
$id = fixText($user, $_GET['id'],0,0,0);
$elm = fixText($user, $_POST['elm'],0,0,0);
$uploadTo = fullPath;
$result = mysqli_query($user, "SELECT productImages FROM hireProducts WHERE `id`='$id'");
if ($row = mysqli_fetch_assoc($result)) {
$get = (array) json_decode($row['productImages'], true);
$filename = $uploadTo.$get[$elm]['Image'];
if (file_exists($filename)) {
unlink($filename);
}
unset($get[$elm]);

$jsonImages = json_encode($get);
$update = mysqli_query($user, "UPDATE hireProducts SET `productImages` = '$jsonImages' WHERE `id`='$id'");
if ($update) {
$arr = array('response'=>'success','comment'=>A01, 'id'=>$id, 'images'=>$get);
} else {
$arr = array('response'=>'error','comment'=>A001.'AL001');
}
} else {
$arr = array('response'=>'error','comment'=>A003);
}
echo json_encode($arr);
exit;
break;


All i want is for it to always to be the same (the first one). Thanks


tagit.js fire after click

Im trying to use tagit.js from Aehlke.


so my problem is i have a "add" button and after click on that button i want to add a new row which contains the ul-element. if i append the ul-element after the user clicks on the button the function of "tag it.js" don't modify the ul.


so is there a way to fire the tagit.js after the user clicks on the button? btw: it should look like the tags section here @SO


here's a little bit of code (pls keep in mind im new @ajax)





var max_fields = 10;
var x = 1;

$(".button.addoptions").on("click", function(e) {
e.preventDefault();

if(x < max_fields){
x++;

$(".addform-optionals").append("<ul id='tagit'></ul>");
}
});

$('#tagit').tagit();



thanks for any kind of help


JQuery Ajax Json Response Does not Work

Form part :



<script type="text/javascript" src="js/aboneol.js"></script>
<h4>haberdar olun</h4>
<div class="news_letter">
<span id="aboneolhata"></span>
<form action="" method="post" onsubmit="return false;" id="abone">
<input type="text" name="email" placeholder="E-posta adresiniz" />
<input type="submit" onclick="$.aboneol();" value="abone ol" />

</form>
</div>


Jquery part :



$.aboneol = function(){
var deger = $("form#abone").serialize();
$.ajax({
url: "aboneol.php",
data: deger,
dataType: "json",
type: "post",
success: function(response){
if(response.error == 0){
$(".news_letter").html(response.message);
}else{
$("#aboneolhata").html(response.message);
}
}
});
}


And here is php part :



<?php
$email = $_POST["email"];
$email = trim($email);

if(empty($email)){
$response["error"] = 1;
$response["message"] = "Boş Bırakamazsınız..";
}else if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
$response["error"] = 1;
$response["message"] = "Hatalı E-posta..";
}else{
require "database.php";
$pdo = Database::connect();
$sql = "INSERT INTO aboneler (email) VALUES (:email)";
$q = $pdo->prepare($sql);
$q->execute(array(
':email'=>$email,
));
$response["error"] = 0;
$response["message"] = $email;
}
echo json_encode($response);
?>


Ajax sends the email to php, and http response code is 200. But success method does not work. Also i cant see any json response in success method. How to solve this problem?


Submit form using ajax like $.ajax format in Rails 3

i have a form to submit but not setting post in routes.rb but in the below way through ajax in Rails 3.


Format:



$.ajax({
type: "POST",
url: $(this).attr('action'), //sumbits it to the given url of the form
data: valuesToSubmit,
dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
}).success(function(json){
console.log("success", json);
});
return false; // prevents normal behaviour
});


I have the form which is given below.



<%= form_for :sdf do |f| %>
<% if params[:receipt_no] %>
<div class="input-group bmargindiv1 col-md-12"> <span class="input-group-addon text-left">Receipt No. Scan :</span>
<%= f.text_field :Receipt_No,:class => "form-control", :value => params[:receipt_no] %><%= f.submit "Scan Report" %>
</div>
<% else %>
<div class="input-group bmargindiv1 col-md-12"> <span class="input-group-addon text-left">Receipt No. Scan :</span>
<%= f.text_field :Receipt_No,:class => "form-control",placeholder:"Receipt No. scan",:onchange => "scan();" %>
</div>
<% end %>
<% end %>


My controller file is given below.



controller/homes_controller.rb:




class HomesController < ApplicationController
def home
@sdf=TSdf.new
respond_to do |format|
format.html
format.js
end
end
def scan_report
@sdf=TSdf.find_by_Receipt_No(params[:sdf][:Receipt_No])
if @sdf && @sdf.HCSY_Status=='YES'
@hcsy=THcsy.find_by_Sdp_Id(@sdf.Sdp_Id)
@hcsy_deatils=THcsyDetails.find_by_HCSY_ID(@hcsy.id)
@woods=THcsyFundTypeMaster.find_by_Fund_Type_Code(1)
@burn=THcsyFundTypeMaster.find_by_Fund_Type_Code(2)
@good=THcsyFundTypeMaster.find_by_Fund_Type_Code(3)
@swd=THcsyFundTypeMaster.find_by_Fund_Type_Code(5)
@photo=THcsyFundTypeMaster.find_by_Fund_Type_Code(6)

else
flash[:alert]="Scan number not found"
flash[:color]="invalid"
render 'home'
end

end
end


I need when user will submit form through onchange event in controller page "scan_report" action should execute.I tried once by calling one function in onchange event but nothing is going to submit.Please help me to resolve this issue and let me to know in this way i have to set route path or not.


Wordpress Ajax for logged in user fails

I am using wordpress 4.1.1. wp-admin and other several pages (like login, register...) use https connection. My goal is create ajax request for adding tickets to system.


So I can not call function for logged in user it calls function for not-logged in user. But when I add https for this page it`s work fine for me.


Question:


How I can keep user logged in on https and http, so is_user_logged_in() in amin-ajax.php works fine?


How send data with ajaxFileUpload and codeigniter?

I tried to upload the data with ajax file upload and CodeIgniter, I get a problem, the file is successfully uploaded but failed to get value of the data, how to find a solution



<script type="text/javascript">
$(function () {

$("#upload_file").submit(function (event) {
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajaxFileUpload({
url: '<?php echo base_url(); ?>upload/do_upload',
secureuri: false,
fileElementId: 'upload_doc',
dataType: 'json',
data: formData,
success: function (data, status)
{
if (data.status == 'success')
{
alert(data.msg);
}

}
});


return false;
});
});</script>


and source codeigniter



function do_upload() {
try {
$pesan = "";
$status = "";
$file_element_name = "upload_doc";
$id = $this->input->post('id', true); /* => failed to get data */
if ($id == 0) {

$config['upload_path'] = './files/';
$config['allowed_types'] = 'pdf|docx|doc|txt';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;

$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name)) {
$status = 'error';
$msg = $this->upload->display_errors('', '');
} else {
$file = $this->upload->data();
$isi['kd_upload'] = $this->mupload->autonumber_upload();
$isi['tgl_upload'] = $this->fungsi_bebas->InggrisTgl($this->input->post('tgl_upload', true)); /* => failed to get data */
$isi['nm_file'] = $file['file_name'];
$isi['no_registrasi'] = $this->input->post('no_registrasi', true); /* => failed to get data */
$isi['validasi'] = "validasi";


$exe = $this->mupload->tambah_upload($isi);
if ($exe > 0) {
$status = "success";
$pesan = "File successfully uploaded" ;

}
}
}
echo json_encode(array('status' => $status, 'msg' => $pesan));
} catch (Exception $exc) {

}


reference : [http://ift.tt/1oeus6x]


How Do I make It Refresh in AJAX And Not affect the PHP

I have a code that is working super ok but I don't know how it to put AJAX into it to check if there is one extra result in my table "chat" and if there is it should refresh the page and if the result hasnt changed then not to refresh page , sorry but I have no idea when it comes to ajax.


chat.php



require('checkformessages.php');
...


checkformessages.php



$sqlmessages = mysql_query("SELECT * FROM chat");
$numbermessages = mysql_num_rows($sqlmessages);


AJAX SCRIPT (No IDEA WHAT ITS SUPPOSED TO BE)

if($numbermessages===$ajaxcheck) {
//do nothing
} else {
//it should refresh the chat.php because its required in the page
echo "<script>window.location = window.location.href;</script>";
}

Why can't i see php call in Mozilla's Net tab?


$('#registerForm').submit(
function()
{
event.preventDefault();
callAjaxSubmitMethod(this);
}
);

function callAjaxSubmitMethod(form)
{
$.ajax({
type: "POST",
url: "lib/registration_validate.php",
data: $("#registerForm").serialize(),
dataType: 'json',
success: function(response)
{
console.log("cominggggg");
alert("s"+response.status);
},
error:function(response)
{
alert("e"+response.status);
},
complete:function(response)
{
console.log("Completed.");
}

});
}


This is how i am sending data to my php page.



<?php
include 'configdb.php';
session_start();
global $connection;
echo "oops";
if(isset($_POST['submit']) && $_POST['email']!='' && $_POST['password']!='')
{
$email= $_POST['email'];
$sql1 = "SELECT * FROM Users WHERE emailID = '$email'";
$result1 = mysqli_query($connection,$sql1) or die("Oops");
$response = array();
if (mysqli_num_rows($result1) > 0)
{
$response['status']='Email Already Exists';
echo json_encode($response);
exit;
}
}?>


I am just processing for duplicate email registration. If ia run this code in my chrome, i can see php in net tab. I can see completed in console and e200 in alert.


In my mozilla browser, i don't get any console strings, alerts. I din't get php page call in Net tab too.


I just cleared cache too. So it's not coming from cache too. I cleared localStorage due to out of memory error in my mozilla.


I don't even understand this behaviour. No idea to how to debug further.


Page scrollbar disappears after using jquery.remove()

I have a page with a table, where user can request to delete each row. If user decides to do so, a query is sent to the server to delete the content, and if the query is successful, I remove the row from the table using a jquery code like this:



$('#RowId' + id).remove();


Where id is the ID of the row user just deleted. This works, and I can see the row is removed, but the side-effect is that the scrollbar on the page also disappears, and I can't scroll in the whole page any more, until I refresh the page again!


I can't find any clue why this is happening. I have only tested it on Chrome 42/Ubuntu 12.04 so far. Any idea what is the problem?


Thanks


How do I set a selected value to a drop down jquery/JQM

I'm generating a dynamic drop down and trying to apply a value to it based on what's retrieved from another asynchronous call. At first I thought the value wasn't being applied because the dropdown wasn't fully created at the time I was setting the value...drop down is being created like so..and then applying the values to the form with the "GetOrderCallSucceeded" (a bunch of $('').val(value) calls, they work for everything accept for the dropdown)



function getEorder(id) {
var ReasonTypesPromise = makeAJAXcall("{}", "GetReasonTypes");
var getMedOrderPromise = makeAJAXcall("{'eMedOrderId':'" + id + "'}", "GetMedicalOrder");

$.when(ReasonTypesPromise, getMedOrderPromise).done(function (reasons, formdata) {
var items = JSON.parse(reasons.d), lr = JSON.parse(formdata.d);

for(var i in items) {
$('#ReasonForLifeVestDropdown')
.append($("<option></option>")
.attr("value", items[i].ReasonTypeID)
.text(items[i].Name));

if (items[i].ReasonTypeID == lr.ReasonTypeID) {
$('#ReasonForLifeVestDropdown').val(lr.ReasonTypeID);
}
}

GetOrderCallSucceeded(lr);
},
function (error, err) {
ajaxCallFailed(error);
});

}


However, I was testing



$('#ReasonForLifeVestDropdown').val(lr.ReasonTypeID);
$('#ReasonForLifeVestDropdown option[value=2]').attr('selected', 'selected');


simply by triggering the jquery onclick in a button. It wasn't working either.


HTML of dropdown and Button I was using for testing.



<div class="ui-block-a"><select id="ReasonForLifeVestDropdown"></select></div>
<div class="ui-block-a"><button data-role="button" onclick="$('#ReasonForLifeVestDropdown option[value=2]').attr('selected', 'selected');">click</button></div>
</div>

Codeigniter HTML Caching with Dynamic Content

I have an application where I use ajax to update the comments & Like count.


I am using Codeigniter page caching http://ift.tt/1zxNZRP


and set following code to recreate caching every 60 minutes



$this->output->cache(60);


Problem is when somebody enter a new comment, DB operation is happening (Because of Ajax call), But the Newly inserted comment disappears after the page refresh, because of the cached HTML page. How to handle caching and also dynamic content to change?


post html as string through ajax

I have a tinymce wysiwyg and i want to post the html from it to my action method:



$("#save").click(function () {
var ed = tinymce.get('wysiwyg');
var id = $("#destinationId").val();
var PostContent = JSON.stringify({ 'content': ed.getContent(), 'destinationId' : id });
console.log(PostContent);


$.ajax({
url: '@Url.Action("SaveDestinationContent", "Home")',
type: 'POST',
dataType: 'JSON',
cache: false,
data: PostContent,
success: function (data) {

},
error: function (xhr, error) {
},
});


I always get null in my action method that looks like this:



[HttpPost]
public ActionResult SaveDestinationContent(string content, string destinationId)
{
return Json("TRUE");
}


i have tried to do this in a couple of different ways:



$("#save").click(function () {
var ed = tinymce.get('wysiwyg');
var PostContent = ed.getContent();
console.log(ed.getContent());
var id = $("#destinationId").val();

$.ajax({
url: '@Url.Action("SaveDestinationContent", "Home")',
type: 'POST',
dataType: 'JSON',
cache: false,
data: {
content: PostContent.toString(), destinationId: id
},
success: function (data) {

},
error: function (xhr, error) {
},
});


but none of them work!


REST API Request should be client side or server side? [on hold]

As a example :


There is examination result validation API and there is a another web application which is use that api as a service. According to that api response(if success) user can enter the site or not


To do that I have a problem with basics,

I came with two options(There may be lot :) any good one is accepted ! )


01). Call the API using cross domain AJAX request and and according to the response. Send another request to web app, server script and create a session



$.get("http://ift.tt/1NU4JyN",
{index_no : no,subject : sub,grade : grade},function(response_msg){
obj = JSON.parse(response_msg);
if(obj.msg.valid){
// results validated marked as validated result on user cv
}
}
);


02). Instead of sending AJAX request to API send user inserted results to the server side and using server side scripts call the API using guzzle library



$client = new \GuzzleHttp\Client();
$response = $client->get('http://ift.tt/1NU4JyN'.Input::get('index_no').'/'.Input::get('subject').'/'.Input::get('grade'));
if($response->json()['msg']==='verified'){
// results validated marked as validated result on user cv
}


What is the best approach ? How About Security ? I think second one is good ! but I still thinking about there is a method to do it in client side ?


ajax octobercms passing value of id


<button
type="button"
class="btn btn-small btn-danger icon-trash"
data-request="onDeleteItem"
data-control="popup"
data-request-data="id: " <<<<<<<----
data-trigger-action="enable"
data-stripe-load-indicator>
</button>


// in Configurations.php::controller


public function onDeleteItem()


//question


how do i get the value of id in a list?


scenario: list of all configs in a table, have an custom column, Edit, Delete


i want to click delete, then it will delete the item, but how do i get the ID?


Laravel 5 and AJAX

I want to display a partial form using ajax when I select the client name. So far I have managed to fetch data from database using this:



<script>
$('#client').change(function(){
var client = $(this).val();
var host = "{{URL::to('/')}}";
var url = host + '/newinvoice/' + client;
$.ajax({
url: url,
type: 'GET',
beforeSend: function(){
$('.client_services').html('Loading...');
},
success: function(data){
$('.client_services').html(data);
}
});

return false;
});
</script>


Here is my Controller.



public function getClientServices(Client $client) {
return json_encode($client->client_service()->get());
}


So instead of $('.client_services').html(data); I want to display text inputs depending on the number of available services for that particular client.


I don't know how to do that.


The above snippet returns results like:



[{"id":1,"client_id":1,"service_id":1,"frequency":90,"deleted_at":null,"created_at":"2015-04-15 10:20:33","updated_at":"2015-04-15 12:22:48"},{"id":2,"client_id":1,"service_id":1,"frequency":0,"deleted_at":null,"created_at":"2015-04-15 13:10:41","updated_at":"2015-04-15 13:24:41"},{"id":3,"client_id":1,"service_id":1,"frequency":180,"deleted_at":null,"created_at":"2015-04-15 13:58:39","updated_at":"2015-04-15 15:34:46"}]


I'm interested on id only.


What I want to do after that is enter the charges for that particular service for that particular client.


I hope I am clear.


Why am i not getting anything from php?


$('#registerForm').submit(
function()
{
callAjaxSubmitMethod(this);
//event.preventDefault();
}
);


It is the function inside my dom ready.



function callAjaxSubmitMethod(form)
{
$.ajax({
type: "POST",
url: "lib/registration_validate.php",
data: $("#registerForm").serialize(),

success: function(response)
{
alert("s"+response.status);
},

error:function(response)
{
alert("e"+response);
}
});
}


It is actual function definition.


My php contents are



<?php
include 'configdb.php';
session_start();
global $connection;
echo "oops";
if(isset($_POST['submit']) && $_POST['email']!='' && $_POST['password']!='')
{ //use empty....
$email= $_POST['email'];
$sql1 = "SELECT * FROM Users WHERE emailID = '$email'";
$result1 = mysqli_query($connection,$sql1) or die("Oops");
if (mysqli_num_rows($result1) > 0)
{
$_SESSION['email_exist']="Email Already Exists";
//die({'status':'Email Already Exists'});
//echo var_dump($_SESSION);
//echo '{status:0}' ;
//exit;
}
}
?>


I din't get any alerts. If i enable event.preventDefault() I am getting out of memory error in mozilla and sundefined alert in chrome.


How to pass data from controller to view with ajax in rails

I posted today similar questions two times


how-to-use-local-or-instance-variable-in-ruby-code-in-coffeescript-in-haml-templ


ajax-in-rails-returns-alway-error-callback


I'm confusing about these issues please let me ask.


I'm using ajax in haml to reload a part of page with data from controller.


Please see my code.


.html.haml



= render 'layouts/partial' #This is partial. I want to reload this part

:coffee
$('input#field').change ->
$.ajax
url: '/posts/gaga'
type: "POST"
dataType: 'text'
error: (jqXHR, textStatus, errorThrown) ->
alert "error"
success: (data, textStatus, jqXHR) ->
alert "success"
$('div.kore').html('#{ j( render( 'layouts/partial' ) )} ');


posts_controller.rb



def gaga
@model = Model.new("blabla")
render :text => @model
end


_partial.html.haml



- if @model
= @model.html_safe
- else
= "No data"


First, I thought data can be get through @model instance variable from controller but it couldn't.


Second, I tryed to get data from ajax response data to view(_partial.html.haml) with jQuery.


Callback and response return correctly as text.


How do I pass data to view from ajax response data, or is there other ways?


Sorry for my sloppy English. I hope someone give me the clue.


Thanks in advance!


Submit data-remote Rails form using jQuery

I'm trying to submit a Rails form using AJAX and data-remote.


The submission is triggered programmatically from javascript ($form.submit()). If I do it like this I receive an InvalidAuthenticityToken error.


I tried to submit the same form without javascript by simply clicking on the submit button and it worked. It seems that the authentication token is not sent when I submit the form using Javascript. I did some research and I tried the following options of adding the authentication token to the data being sent



  • adding the following line in the Controller skip_before_action :verify_authenticity_token, :only => :create

  • adding the following line inside the form_for block <%= f.hidden_field :authenticity_token, value: form_authenticity_token %>

  • adding :authenticity_token => true to the form_for params

  • setting config.action_view.embed_authenticity_token_in_remote_forms to true in development.rb


I tried using all the above and each of them helped me submit the form using javascript and get rid of the InvalidAuthenticityToken error, however, even though I still had the remote: true option, the request doesn't seem to be performed using AJAX since the page reloads and renders another view template.


This being said I would like to know how can I still submit the form from javascript but without getting any errors or having the page reload.


How to send Ajax request using jQuery doubling with click button

using jquery, When user click "send button" then ajax request sent to the server and get double or two more complete the request.


How Can I do this?


http://ift.tt/1DigKCG



$(function() {
$( "#dialog:ui-dialog" ).dialog( "destroy" );
$( "#revocation" ).dialog({
autoOpen: false,
height: 200,
width: 460,
modal: true,
buttons:{
"Yes": function() {
revocation();
},
"Close" : function() {
$( this ).dialog( "close" );
}
}
});
});

$.ajax({
type: "POST",
url: "/revocation/",
data: "confirm_item=" + $("#exchange_id").val(),
error: function(){
return false;
}
}).done(function( msg ) {
if(msg != "success"){
return false;
}else{

}
});
}

function revocationdialog(the_id){
$.ajax({
type: "POST",
url: "/revocation/",
data: "exchange_id=" + the_id
}).done(function( msg ) {
$("#revocation").html();
$("#revocation").html(msg);
});
$("#revocation").dialog("open");
}

AJAX/PHP POST retrieval

I'm doing a POST using AJAX and I'm checking for the response with PHP using


if (!empty($_POST)


but it doesn't seem to be hitting the if or else.


The form is submitting and I get a 200 status in the network tab.


PHP isn't my main language so I'm wondering if I'm missing something relatively simple?


Thanks


Form:



<form id="myForm" method="post" novalidate="novalidate">
...
<button type="submit" name="contact_send">Send</button>
</form>


AJAX:



jQuery.ajax({
type: 'POST',
url: window.location.href,
data: formData,
success: function(response) {
console.log('response');
}
});


PHP:



if (!empty($_POST)) {
print_r('Data');
add_action('init', 'deliver');
} else {
print_r('No Data');
}


Neither the if or else is reached


codeigniter : getting ajax result issues

i have this simple exams system and i want to use ajax when a user answer


this is my form :



when i use action="<*?=site_url("exams/check_answer")?>" it gives 302 error




<form action="<?=site_url('exams/'.$result->id.'/check_answer');?>" method="post" id="answer-exam-frm">
<div>
<p><input type="radio" name="response" value="first"><span class="choice-exam"><?php echo $result->choice1;?></span></p>
<p><input type="radio" name="response" value="second"><span class="choice-exam"><?php echo $result->choice2;?></span></p>
<p><input type="radio" name="response" value="third"><span class="choice-exam"><?php echo $result->choice3;?></span></p>
<input type="hidden" name="examid" value="<?php echo $result->id;?>">

<input type="submit" class="btn btn-default" value="اجابة">
</div>

</form>


this is my controller :



public function check_answer(){
$user_answer = $this->input->post('response') ;
$exam_id = $this->input->post('examid') ;
$result = $this->style_model->check_answer($user_answer,$exam_id) ;
$this->output->set_content_type('application/json') ;
if($result){
$this->output->set_output(json_encode(['result' => 1 ])) ;
return false;
}
$this->output->set_output(json_encode(['result' => 0 ])) ;



}


And this is my model :



public function check_answer($user_answer,$exam_id)
{
$this->db->where('response' , $user_answer);
$this->db->where('id' , $exam_id);
$get = $this->db->get('exam') ;
return $get->result() ;

}

how to call a function if checkbox checked and remove from appended list if unchecked

This is how the flow like:


I first derive the value of checkbox and pass the value to a function to trigger ajax. That ajax function return a list of data in multiple group in select box. Each time a checkbox checked, the value will be appended into the selectbox. But I want to remove the value from selectbox when checkbox unchecked.


Now, when I click on the checkbox the value is passed to the function no matter I check or uncheck. How to control here?


first script



<script>

$("input[type=checkbox]").change(function() {
var selectedval = ($(this).val());
var selectedtext =($(this).next().text());

sendtobox(selectedval);

});
</script>


second script (function)



<script>
var xmlhttp = false;
try
{
xmlhttp = new ActiveXObject(Msxml2.XMLHTTP);
//alert("javascript version greater than 5!");
}
catch(e)
{
try
{
xmlhttp = new ActiveXObject(Microsoft.XMLHTTP);
// alert("you're using IE!");
}
catch(E)
{
xmlhttp = new XMLHttpRequest();
//alert("non IE!");
}
}

function sendtobox(param)
{
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (this.responseText !== null) {
var ajaxElm = document.getElementById('show');
ajaxElm.innerHTML = this.responseText + ajaxElm.innerHTML; // append in front
}
//document.getElementById("show").innerHTML = xmlhttp.responseText;
}
}

xmlhttp.open("GET","getuser.php?q="+param,true);
xmlhttp.send();

}
</script>


HTML



<input type="checkbox" name="level" id="level" class="level" value="1"><label>Primary</label><br/>
<input type="checkbox" name="level" id="level" class="level" value="2"><label>Upper Secondary</label><br/>
<input type="checkbox" name="level" id="level" class="level" value="3"><label>University</label><br/>
<input type="checkbox" name="level" id="level" class="level" value="4"><label>Lower Secondary</label><br/>
<input type="checkbox" name="level" id="level" class="level" value="5"><label>Pre University</label><br/>
<input type="checkbox" name="level" id="level" class="level" value="6"><label>Skills/Languages</label><br/>

Use one ajax call for different page and div?

I use this code to make ajax call to change the content of div in main page without reloading the page :



function ajaxcall()
{
$.ajax({
type: "POST",
url: "/create.php",
success: function( returnedData ) {
$( '#container' ).html( returnedData );
}
});
}


and I call it like that :



<p><a onclick="ajaxcall()" >Create</a></p>


The issue is very complicated because I have to call 4 pages in the same div :



create.hmtl ; update.html; delete.html ; read.html


Also I have 2 different forms in the same page that required the same thing, I mean I should do the same thing for the second form with another div "container-1",then I have 2 div for exmaple in create.html :


create.html :



<div id="container">
....
</div>

<div id="container-1">
....
</div>


So I call create.html everytime but different div for different form, the question is to use a minimum clean code to do all what I explained above?


Connection failed: Host 'xx.xx.xx.xx' is not allowed to connect to this MySQL server - AJAX ans AWS

I am trying to insert some data from the client browser to a MySQL database on AWS server.


The code worked on godaddy so it looks like a permissions/security issue.



$servername = "xx.xx.xx.xx";
$username = "user";
$password = "mypass";
$dbname = "dbName";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO mytable ('email')
VALUES ('" . $email . "')";

echo $sql;

if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();


I am getting the error saying "Connection failed: Host x.x.x.x is not allowed to connect to this MySQL server "


How do I allow connections to this from a client browser?


I have already commented out the line bind-address = 127.0.0.1


Javascript for google map not responding correctly to ajax request in rails

In rails I have a bunch of 'notices' in the html, each of which has latitude and longitude attributes for a corresponding marker on a google map. I send an ajax request to the notices controller when the google map boundaries change. It returns all notices with coordinates inside the map boundaries, and also an array containing all the information necessary for the map to place the corresponding markers.


javascript in the view:



var initialize, map, mapOptions;
var markers = [];

initialize = function() {
mapOptions = {
center: {lat: 51, lng: 0},
zoom: 9
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
google.maps.event.addListener(map, 'zoom_changed', dealWithNewWindow);
google.maps.event.addListener(map, 'dragend', dealWithNewWindow);
function dealWithNewWindow(event) {
var bounds = map.getBounds();
var nelat = bounds.getNorthEast().lat();
var swlat = bounds.getSouthWest().lat();
var nelng = bounds.getNorthEast().lng();
var swlng = bounds.getSouthWest().lng();
var mapBounds = {NElatitude:nelat, SWlatitude:swlat, NElongitude:nelng, SWlongitude:swlng};
$.ajax({
type : 'POST',
url : '/maprequest',
dataType : 'script',
data : { NElatitude:nelat, SWlatitude:swlat, NElongitude:nelng, SWlongitude:swlng }
});
};
dealWithNewWindow(e);
};

makeMarkers = function(markerArray) {
// alert("Alert 1.");
for (m = 0; m < markerArray.length; m++) {
// alert("Alert 2.");
(function(marka) {
var goomap = google.maps;
var marker = new goomap.Marker({
map: map,
position: new goomap.LatLng(marka.lat, marka.lng),
infowindow: marka.infowindow,
id: marka.id
});
markers.push(marker);
}(
markerArray[m]
));
}
};


notices controller show action:



def show
respond_to do |format|
format.html
format.js do
@notices = noticefeed
@markers = []
@notices.each do |notice|
marker = Marker.new(notice.latitude, notice.longitude, notice.content, notice.id)
@markers.push(marker)
end
gon.markers = @markers
end
end
end

private
def noticefeed
nelat = params[:NElatitude]
swlat = params[:SWlatitude]
nelng = params[:NElongitude]
swlng = params[:SWlongitude]
Notice.where(" latitude < ?
AND latitude > ?
AND longitude < ?
AND longitude > ? ", nelat, swlat, nelng, swlng )
end


show.js.erb:



$("#notice_list").html("<%= escape_javascript(render @notices) %>")
makeMarkers(gon.markers);


The browser console shows that the ajax is sent correctly and that the server responds without a problem. The line $("#notice_list").html("<%= escape_javascript(render @notices) %>") is providing the correct html. The problem is that the markers on the map are not created or updated. (I'm using gon to communicate between rails and jquery). When I uncomment alert("Alert 1."); the alert appears, meaning it is successfully calling the makeMarkers method, but alert("Alert 2."); never appears when it is the only one uncommented. Therefore makeMarkers is being called, but it never makes it into the for (m = 0; m < markerArray.length; m++) loop. Therefore it mustn't be happy with being passed gon.markers.


Why are neither the #notice_list nor the map markers being updated?


EDIT:


In show.js.erb, when I replace makeMarkers(gon.markers); with makeMarkers([1,2,3]) it successfully enters the for loop ("Alert 2" appears). There must be something wrong with gon.markers. gon.markers is an array that was created in the notices controller inside ruby, do I have to somehow turn it into a javascript array? I thought gon did this for you? I've checked using debugger that gon.markers and @markers are arrays or markers, and they are:


gon.markers:



[#<Mymodule::Marker:0x0000010ded1c38 @lat=51.9714995840941, @lng=-1.60000814589637, @infowindow="This is great!!", @id=904>]


So when this object is handed to makeMarkers, something goes wrong.


jquery Append don't work

I trying to update active/suspend button using ajax and jquery, after user clicked on "suspend" -> I have to change the status to "Suspended" + active button. After user clicked on "active" button -> I change the status to "Activated" + suspend button.


Here is the HTML/PHP code :



Status :
<?php
if($row['active']==2) // 2 = Suspended
{
?>
<span id="status<?php echo $row['id']; ?>">Suspended
<button type="button" class="active-button" value="<?php echo $row['id']; ?>">active</button>
</span>
<?php
}
else if($row['active']==1) // 1 = Activated
{
?>
<span id="status<?php echo $row['id']; ?>">Activated
<button type="button" class="suspend-button" value="<?php echo $row['id']; ?>">suspend</button>
</span>
<?php
}
?>


This is the jquery/ajax code :



$(function()
{
$('.active-button').click(function(){
var add_active = 1;
var add_id = $(this).val();
var status = "#status"+add_id;
$(status).text('Loading...');

$.post('active.php',{id: add_id, active: add_active}, function(){
$(status).html("").append("Suspended <button type='button' class='active-button' value="+add_id+">active</button>");
});
});

$('.suspend-button').click(function(){
var add_active = 2;
var add_id = $(this).val();
var status = "#status"+add_id;
$(status).text('Loading...');

$.post('active.php',{id: add_id, active: add_active}, function(){
$(status).html("").append("Activated <button type='button' class='suspend-button' value="+add_id+">suspend</button>");
});
});
});


But The problem is that the span "status" doesn't change(in the DB it works well). I almost sure that the problem is in this line :



$.post('active.php',{id: add_id, active: add_active}, function(){
$(status).html("").append("Activated <button type='button' class='suspend-button' value="+add_id+">suspend</button>");
});

One ajax call for more than one div content and page?

I use this code to make ajax call to change the content of div in main page without reloading the page :



function ajaxcall()
{
$.ajax({
type: "POST",
url: "/create.php",
success: function( returnedData ) {
$( '#container' ).html( returnedData );
}
});
}


and I call it like that :



<p><a onclick="ajaxcall()" >Create</a></p>


The issue is very complicated because I have to call 4 pages in the same div :



create.hmtl ; update.html; delete.html ; read.html


Also I have 2 different forms in the same page that required the same thing, I mean I should do the same thing for the second form with another div "container-1",then I have 2 div for exmaple in create.html :


create.html :



<div id="container">
....
</div>

<div id="container-1">
....
</div>


So I call create.html everytime but different div for different form, the question is to use a minimum clean code to do all what I explained above?


Google app engine Endpoint and HTTP Sessions

I'm deploying an application in Google App Engine and I'm also using the Cloud Endpoint feature for REst call.


I use a custom domain to point on my application. As you probably know, Endpoint doesn't support custom domain. So my situation is this:



  1. I open the page http://www.example.org

  2. I do an ajax request to an Endpoint like http://ift.tt/1DX3vMx


Now the problem is: Everytime I do an ajax request to an Endpoint, a new Session is created!! How can I keep the session between requests? I inspected the responses from Endpoint, and I didn't find any reference to session cookie...