implode breaks Ajax call - javascript

So I'm making an Ajax call which will first check to see if that post ID has already been voted on.
Currently I'm just working on the PHP to first get the post id's, if it is empty set it or if it is not empty to append the ID.
Question here: Except when I use the implode or explode method it does not seem to make a call back to the javascript. Although if I was to refresh the page it does register the vote.
This is the PHP file. For user Id I've just set it to my admin id to start with.
function my_user_vote() {
$user_id = 1;
$pageVoted = $_REQUEST["post_id"];
$currentPosts = get_user_meta($user_id, 'pages_voted_on');
if (empty($currentPosts)) {
// Empty create single array
$postsVotedOn[] = $pageVoted;
} else {
$postsVotedOn = explode('|', $currentPosts);
$postsVotedOn[] = $pageVoted;
}
$boo = implode("|", $pageVoted);
update_user_meta( $user_id, 'pages_voted_on', $boo);
if ( !wp_verify_nonce( $_REQUEST['nonce'], "my_user_vote_nonce")) {
exit("No naughty business please");
}
$vote_count = get_post_meta($_REQUEST["post_id"], "votes", true);
$vote_count = ($vote_count == '') ? 0 : $vote_count;
$new_vote_count = $vote_count + 1;
$vote = update_post_meta($_REQUEST["post_id"], "votes", $new_vote_count);
if($vote === false) {
$result['type'] = "error";
$result['vote_count'] = $vote_count;
}
else {
$result['type'] = "success";
$result['vote_count'] = $new_vote_count;
}
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
die();
}
This is the javascript.
jQuery(document).ready( function() {
jQuery(".user_vote").click( function() {
post_id = jQuery(this).attr("data-post_id")
nonce = jQuery(this).attr("data-nonce")
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
success: function(response) {
if(response.type == "success") {
jQuery(".vote_counter").html("Votes: " + response.vote_count);
jQuery(".voteUpButton").html('<div class="button btnGreen">Thank you!</div>');
alert("Cooommmon");
console.log(response.vote_count);
}
else {
alert("Your vote could not be added")
}
}
})
})
})

I just did a quick test with your code, and found a couple of issues that throw errors:
1. This line:
$currentPosts = get_user_meta($user_id, 'pages_voted_on');
should be
$currentPosts = get_user_meta($user_id, 'pages_voted_on', true);
2. And I believe this line:
$boo = implode("|", $pageVoted);
should be
$boo = implode("|", $postsVotedOn);
Explanation:
Without the true argument get_user_meta returns an array. And you can't explode an array.
http://codex.wordpress.org/Function_Reference/get_user_meta
$pageVoted is the id of the page to add, while $postsVotedOn is the actual list you want it appended to.

Related

Magento insert data into database through ajax

I'm new to ajax so I'm not sure if i'm approaching this correctly, basically I have a variable in javascript that need to be inserted into the database, this is what I have so far...
onInit: function() {
window.fcWidget.on('widget:loaded', function() {
window.fcWidget.user.get().then(function(resp) {
var status = resp && resp.status,
data = resp && resp.data;
if (status === 200) {
if (data.restoreId) {
// Update restoreId in database
$.ajax({
type: "POST",
url: "insert.php",
data: data.restoreId,
success: function(data) { alert("Success"); },
failure: function(data) { alert("Failure"); }
})
}
}
});
});
}
I have placed the file "insert.php" in the same folder but it seem like it doesn't get called at all...
This is what insert.php looks like
<?php
if(Mage::getSingleton('customer/session')->isLoggedIn()){
if(isset($_POST['data.restoreId']){
$restoreId =$_POST['data.restoreId'];
}
$first = Mage::getSingleton('customer/session')->getCustomer()->getFirstname();
$last = Mage::getSingleton('customer/session')->getCustomer()->getLastname();
$fullName = $first . "." . $last;
//get resource model
$resource = Mage::getSingleton('core/resource');
//retrieve write connection
$writeConnection = $resource->getConnection('core_write');
//read connection
$readConnection = $resource->getConnection('core_read');
$exId = $fullName;
$resId = $restoreId;
$testQuery = "SELECT `externalId` FROM `freshchat_user` WHERE `restoreId` = '$fullName'";
$result = $readConnection->fetchAll($testQuery);
if(count($result) == '0'){
$query = "INSERT INTO `freshchat_user`(`externalId`, `restoreId`) VALUES ('$exId','$resId')";
$writeConnection->query($query);
}else{
//echo "nope";
}
}
?>
I checked the network tab but insert.php doesn't seem to be called at all, what is wrong with my code?
//Please put your insert.php file in root path(Magento installation path) and change below line in your javascript code.
url: "www.yourwebsite.com/insert.php",

$.ajax missing some data on post to php

I have a problem where some of my data is not getting through to php. I think the problem lies in ajax sending it. I send about 10 attributes, from which some are strings and some are integers. This is just simplified example of what I did. Few of the values given that it misses are integers, I think. And some values are got from cordova.Localstorage with storage.getItem("itemkeyname"); There's no problem with connection, because I get at least error message back saying "missing data" etc, etc..
I've tried PHP's isset() instead of empty(), which didn't change anything.
var_dump() returns array of send attributes, but few last attributes are cut-off or missing.
//when submitbtn is pressed
$("#submitbtn").click(function () {
// First I get data from input elements from page
$name = $("#name").val();
$name2 = $("#name2").val();
//debug to see $name's value
alert("name: " + $name + ", name2: " + $name2);
// then I check it's not empty/null
if ($name && $name2) {
//then call ajax and send data to server
$.ajax({
url: "http://localhost:1234/phpfile.php",
type: "POST",
data: {
name: $name,
name2: $name2
},
dataType: "text",
success: function (response) {
alert(response);
},
error: function (err) {
$output = JSON.stringify(err);
alert($output);
}
});
}
});
On the server side phpfile.php
<?php header('Content-Type: text/html; charset=utf-8');
//store missing data on array
$data_missing = array();
if(empty($_POST['name'])) {
$data_missing[] = "name";
} else {
$name = trim($_POST['name']);
}
if(empty($_POST['name2'])) {
$data_missing[] = "name2";
} else {
$name2 = trim($_POST['name2']);
}
//check there's no data missing
if(empty($data_missing)) {
//do stuff
} else {
echo 'missing data: ';
foreach($data_missing as $missing) {
echo '$missing , ';
}
}
?>
echo '$missing , ' won't work should be echo "$missing , "
In your JS code the dataType is defined as "text" (plain), while PHP defines its response as text/html.
Try to check the input values as:
if( !isset($_POST["name"]) || strlen(trim($_POST["name"])) == 0 ) {
$data_missing[] = "name";
}

How to use jQuery/Ajax to perform MySQL Query

I'm trying to use jQuery to check if the username that the user entered in a form is already taken. Below are the relevant codesnippets in Java, and existence.php.
*javascript*
var username = document.register.username.value;
usernameTaken = checkUserExistence(username, 'username');
function checkUserExistence(str, type){
var dataString = '?str=' + str + '&type=' + type;
if($.trim(str).length>0 && $.trim(type).length>0){
$.ajax({
type: "POST",
url: "existence.php",
data: dataString,
beforeSend: function(){ $("#submit").val('Sending...');},
success: function(data){
if(data){
$("#submit").val('Succes!');
return 1;
}else{
$("#submit").val('Failure!');
return 0;
}
}
});
}
return false;
}
*/JavaScript*
<?php
include("inc/connect.php");
$data = $_POST["str"];
$type = $_POST["type"];
switch($type){
case "username":
$resultUsers = mysql_query("SELECT * FROM users WHERE username = '$data' ") or die(mysql_error());
if( mysql_num_rows($resultUsers) == 1 ){
echo 1;
}
break;
}
?>
What am I doing wrong?
My website is supposed to show live hints to the users, like 'your username is too short' etc. All hints are working, but the ones where it should say 'your username is already taken' won't show. The form gets processed to my PHP-register function, where usernames that are already taken get rejected, so somehow the checkUserExistence-function and the existence.php page are not working.
Edit:
For a live demonstration of my code, go to:
http://beta.somentus.nl/index.php
The usernames 'Admin', 'Somentus' and 'Rik' are already taken, try them out :)
$data = $_POST["data"];
should be:
$data = $_POST["str"];

Getting multiple LIVE values into JavaScript from AJAX/PHP

I'm making a web application and I'm trying to make it so when you enter the ID of a provider it automatically outputs them into a span, this is my AJAX/JS call
<script>
function showHint(str)
{
if (str.length == 0)
{
document.getElementById("txtHint").innerHTML = "";
return;
}
else
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../include/proveedores.php?q=" + str, true);
xmlhttp.send();
console.log(telfValor);
}
}
</script>
<span id="txtHint"></span>
<input id="numa" type="text" onkeyup="showHint(this.value)">
And this is the .php it calls to make the search
<?
include('conexion.php');
$conex=conex();
// get the q parameter from URL
$q = $_REQUEST["q"];
$descrip = "";
// lookup all hints from array if $q is different from ""
if ($q !== "")
{
$sql = "SELECT * FROM SAPROV WHERE CodProv LIKE '$q'";
$stmt = sqlsrv_query($conex, $sql);
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$descrip = $row['Descrip'];
$telf = $row['Telef'];
}
// Output "no suggestion" if no hint was found or output correct values
echo $descrip === "" ? "no suggestion" : $descrip;
?>
Is there any way to accomplish this?
EDIT: This is to make an AJAX calls to return various values into spans with just 1 AJAX call
<script src="../js/jquery.js" type="text/javascript"></script>
<script>
function showHint(str)
{
// If there is nothing on the textbox, there is nothing in the spans
if (str.length === 0)
{
$('#Span Name').html("");
$('#Telephone').html("");
return;
}
$.ajax
({
//Here goes the file which contains the SQL call
url: "../include/proveedores.php",
data: {'q': str},
dataType: "json",
type: "GET",
// Here goes the data that goes into the spans
success: function (data, status, jqXhr)
{
$("#Span Name").html(data["Array Name"]);
$("#Telephone").html(data["Telephone"]);
},
error: function (jqXhr, textStatus, errorThrown)
{
console.log("Error response:", jqXhr.responseText);
}
});
}
</script>
// This is the text input that will be sent to your query file
<input type="text" onkeyup="showHint(this.value)">
<span id="Span Name"></span>
<span id="Telephone"></span>
proveedores.php:
<?
include('conexion.php');
$conex=conex();
// get the q parameter from URL, this is what you have posted
$q = isset($_REQUEST["q"]) ? $_REQUEST["q"] : "";
$descrip = "";
if (isset($q) && $q !== "")
{
// THIS IS PRONE TO SQL INJECTION! USE INTERNALLY!
$sql = "SELECT * FROM PROVIDERS WHERE CodProv LIKE '$q'";
$stmt = sqlsrv_query($conex, $sql);
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$Variable = $row['Column Name'];
$Telf = $row['Telef'];
$Direc = $row['Direc1'];
}
// This is the array to be encoded to AJAX
$values = array();
// Output "no suggestion" if no hint was found or output correct values
$values["ArrayName"] = ($Variable === "") ? "no suggestion" : $Variable;
$values["Telephone"] = ($Telf === "") ? "" : $Telf;
// Output the json data
print_r(json_encode($values));
?>
To start, you should use a javascript library like jQuery to handle all the tough AJAX lifting. It will make your life sooo much easier. If you want to use regular javascript, you can return a comma-separated string and then parse each value separated by a comma but that can get messy. With that being said, you can use jQuery AJAX and return your data in a JSON encoded data object.
.php
<?
include('conexion.php');
$conex=conex();
// get the q parameter from URL
$q = isset($_REQUEST["q"]) ? $_REQUEST["q"] : "";
$descrip = "";
// lookup all hints from array if $q is different from ""
if ($q !== "")
{
$sql = "SELECT * FROM SAPROV WHERE CodProv LIKE '$q'";
$stmt = sqlsrv_query($conex, $sql);
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$descrip = $row['Descrip'];
$telf = $row['Telef'];
}
$values = array();
// Output "no suggestion" if no hint was found or output correct values
// NOTE: we're using the same "txtHint" here for the key as we do in the javascript function
$values["txtHint"] = ($descrip === "") ? "no suggestion" : $descrip;
// Set these to something useful
$values["txtPhone"] = "";
$values["txtAddress"] = "";
// Output the json data
print_r(json_encode($values));
?>
Now, for the jQuery implementation. The first thing you'll have to do is download the jQuery library from jQuery's website. I would recommend getting the most recent version (currently jQuery 2.x).
.html
<script src="/script/jquery.js" type="text/javascript"></script>
<script>
function showHint(str) {
if (str.length === 0) {
$('#txtHint').html("");
return;
}
$.ajax({
url: "../include/proveedores.php",
data: {'q': str},
dataType: "json",
type: "GET",
success: function (data, status, jqXhr) {
$("#txtHint").html(data["txtHint"]);
// You can do this same thing for the other data returned
$("#txtPhone").html(data["txtPhone"]);
$("#txtAddress").html(data["txtAddress"]);
},
error: function (jqXhr, textStatus, errorThrown) {
console.log("Error response:", jqXhr.responseText);
}
});
// Not sure where this is defined. It might throw an error
console.log(telfValor);
}
</script>
<span id="txtHint"></span>
<span id="txtPhone"></span>
<span id="txtAddress"></span>
<input id="numa" type="text" onkeyup="showHint(this.value)">
The obvious change is the call to $.ajax() instead of using the XmlHttpRequest() object. It is in and of itself fairly self-explanatory. One thing I would like to mention is that since we set the "type" to "GET", the key-value pairs in "data" will be appended to the url as a querystring in the form: "url?key1=value1&key2=value2&etc...". So the resulting url, in our case, would be "../include/proveedores.php?q=[VALUE_OF_STR]" where [VALUE_OF_STR] is the value of the str variable.
The other change worth noting is that jQuery has a very helpful way of selecting elements. If you want to get an element by an ID you can just use the syntax: $('#txtHint').
Where the '#' symbol denotes that we're looking for an element based on the ID and 'txtHint' is the ID of the element you're looking for. You can read more about jQuery selectors in the docs.

Ajax call returns a Class 'db' not found error even if database connection already defined

I want to update my contents using ajax. By just choosing dropdown values, the contents then populate new values based on the dropdown value being selected. But everytime I choose a value from my dropdown, it returns a Class 'db' not found error and other functions I already put on my required_once seems not working also. I have been trying to solve this for 2 days now but it is still not working. Can somebody please help me with this? Thanks. Here are my codes:
Note that when my_file.php is loaded, the course_overview_functions.php is called and the else part is loaded and it returns the appropriate values. When the ajax call is executed, if part returns true, it then returns the class 'db' not found error.
my_file.php
require_once 'includes/course_overview_functions.php';
$course_array = array();
$pid_shown = array();
$course_array = ajax_request_val();
my_file.php (javascript part)
$(':input').change(function(event){
event.preventDefault();
$('.minimal_table').html('<img src="../images/loading_trans.gif" style="position:relative; margin:350px; margin-top:250px;" />');
alert($(this).val());
var val_id = $(this).val();
var postData = {val_id:val_id, ajax:1 };
$.ajax({
url: "../includes/course_overview_functions.php",
async: false,
type: "POST",
data: postData,
dataType: "html",
success: function(data){
setTimeout(function(){
$('.minimal_table').html(data);
},2000);
console.log(data);
},
});
});
course_overview_functions.php
function ajax_request_val(){
$val_id = $_POST['val_id'];
$field = "course_type";
if(isset($val_id)){
$plans = db::getTable('plan',$field,$val_id);
foreach ($plans as $plan) {
if (eventAccessLevel(null, $plan['plan_id']) != EVENT_ACCESS_NONE) {
$course_array[] = getCourseDetails(null, $plan['plan_id']);
$pid_shown[] = $plan['plan_id'];
}
}
$events = db::getTable('tbl_event',$field,$val_id);
foreach ($events as $event) {
if (!in_array($event['plan_id'], $pid_shown)) {
$event_id = $event['event_id'];
if (eventAccessLevel($event_id, null) != EVENT_ACCESS_NONE) {
$course_array[] = getCourseDetails($event_id, null);
}
}
}
return $course_array;
}
else{
$plans = db::getTable('plan');
foreach ($plans as $plan) {
if (eventAccessLevel(null, $plan['plan_id']) != EVENT_ACCESS_NONE) {
$course_array[] = getCourseDetails(null, $plan['plan_id']);
$pid_shown[] = $plan['plan_id'];
}
}
$events = db::getTable('tbl_event');
foreach ($events as $event) {
if (!in_array($event['plan_id'], $pid_shown)) {
$event_id = $event['event_id'];
if (eventAccessLevel($event_id, null) != EVENT_ACCESS_NONE) {
$course_array[] = getCourseDetails($event_id, null);
}
}
}
return $course_array;
}
}
databaseconnect.php
public static function getTable($tableName,$field='',$type_id='') {
if (!self::$db) self::connect();
if(!empty($type_id)){
$tableName = self::$db->escape_string($tableName);
return self::getObjects('SELECT * FROM `' . $tableName . '` WHERE `'. $field .'` = `'. $type_id .'`;');
}
else{
$tableName = self::$db->escape_string($tableName);
return self::getObjects('SELECT * FROM `' . $tableName . '`;');
}
}
Error:
Fatal error: Class 'db' not found in /home/cm/public_html/includes/course_overview_functions.php on line 207
Your databaseconnect... you have a function there but no class defined. You need to have a class db defined.

Categories

Resources