i have a simple ajax script that sends 3 variables to an external php script, it then adds them into an array and sends the array back, and i want it to output it in the javascript console, so that i can check that the variables are being passed back successfully, however when i run the script nothing appears in the console, only that
XHR finished loading: "http://localhost/blank/scripts/ajax/profile_password_submit.php".
Here is the ajax
$("#pro_content_password").submit(function() {
var url = "scripts/ajax/profile_password_submit.php"; // the script where you handle the form input.
var js_array=new Array();
$.ajax({
type: "POST",
url: url,
data: $("#pro_content_password").serialize(), // serializes the form's elements.
success: function(data){
js_array=data;
console.log(js_array);
},
dataType: 'json'
});
return false; // avoid to execute the actual submit of the form.
});
Here is the external php script
session_start();
include '../../connect.php';
$user_id = "";
$user_id = $_SESSION['userId'];
echo $user_id;
if(empty($_SESSION['userId'])){
echo "user id session not set";
exit;
}
$old_password = $_POST['pro_content_password_old'];
$new_password = $_POST['pro_content_password_new'];
$new_password1 = $_POST['pro_content_password_verify'];
$password_array = array("old"=>$old_password,"new"=>$new_password, "new1"=>$new_password1);
echo json_encode($password_array);
Any ideas? Also i am using Google Chrome console
It looks like you're not outputting a proper JSON object. I don't know for a fact, since you haven't shared what your PHP script is outputting, but I have a feeling that this line in that is what's causing your problem:
echo $user_id;
You're not just outputting a JSON encoded PHP array, you're also outputting the $user_id variable.
jQuery's ajax success callback only fires if it receives a properly formatted JSON object, which yours is not. It probably looks something more like this:
1234{"old": "oldpass", "new": "newpass", "new1": "newpass1"}
You need JSON.stringify :
$("#pro_content_password").submit(function() {
var url = "scripts/ajax/profile_password_submit.php"; // the script where you handle the form input.
var js_array=new Array();
$.ajax({
type: "POST",
url: url,
data: $("#pro_content_password").serialize(), // serializes the form's elements.
success: function(data){
js_array=JSON.stringify(data);
console.log(js_array);
},
dataType: 'json'
});
return false; // avoid to execute the actual submit of the form.
});
Here is the final working version now, its a lot different to my original but it works a lot better
<script type="text/javascript">
function submit_profile_password(){
//var results = document.getElementById("results");
var result_error = document.getElementById("pro_content_error_password");
var old_error = document.getElementById("pro_password_old_comment");
var new_error = document.getElementById("pro_password_new_comment");
var new1_error = document.getElementById("pro_password_new1_comment");
var oldPass = document.getElementsByName("pro_content_password_old")[0].value;
var newPass = document.getElementsByName("pro_content_password_new")[0].value;
var new1Pass = document.getElementsByName("pro_content_password_verify")[0].value;
var vars = "oldPass="+oldPass+"&newPass="+newPass+"&new1Pass="+new1Pass;
var hr = new XMLHttpRequest();
hr.open("POST", "scripts/ajax/profile_password_submit.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
//results.innerHTML = "";
for(var obj in data){
if(obj == "old"){
old_error.innerHTML = "";
old_error.innerHTML = data[obj];
}else if(obj == "new"){
new_error.innerHTML = "";
new_error.innerHTML = data[obj];
}else if(obj == "new1"){
new1_error.innerHTML = "";
new1_error.innerHTML = data[obj];
}else if(obj == "result"){
result_error.innerHTML = "";
result_error.innerHTML = data[obj];
}
//alert("Key = "+obj+"value = "+data[obj]+"");
}
}
}
hr.send(vars);
//results.innerHTML = "requesting...";
return false;
}
</script>
Thanks all for the help
Related
Now I have two javascript, one is I called auto_refresh.js which I use ajax to continuously get new data from mysql database (This part is done).
auto_refresh.js
var mainDisplayCacheData;
var mainDisplayData = $('.aside').html();
var auto_refresh = setInterval(
function()
{
$.ajax({
url: 'main_display.php',
type: 'POST',
data: mainDisplayData,
dataType: 'html',
success: function(mainDisplayData){
if(mainDisplayData !== mainDisplayCacheData){
mainDisplayCacheData = mainDisplayData;
$('.aside').html(mainDisplayData);
}
}
})
}, 1000);
display.php
<div class="aside">
<?php
$tm = TicketManager::getInstance();
$tm->displayMainTicket();
$ticket = $tm->mainTicketSound();
?>
</div>
ticketmanaget.inc
public function mainTicketSound()
{
$conn = DBManager::getConnection();
$query = "SELECT queue_id, ticket_name FROM queue
WHERE DATE(response_time) = DATE(NOW())
ORDER BY response_time DESC
LIMIT 1
";
$results = #$conn->query($query);
if ($results === FALSE or $results === NULL)
throw new DatabaseErrorException($conn->error);
if ($results->num_rows < 1)
{
$results->close();
}
else
{
while($rows = #$results->fetch_array())
{
$ticketname = $rows['ticket_name'];
return $ticketname;
}
}
}
audio function
var input = "<?php echo $ticket; ?>";
var files = ["0.mp3", "1.mp3",
"2.mp3", "3.mp3",
"4.mp3", "5.mp3",
"6.mp3", "7.mp3",
"8.mp3", "9.mp3"];
var audio = document.createElement("audio");
var audioIdx = 0;
var playById = function (id) {
audio.src = files[input[id]];
audio.play();
};
audio.addEventListener('ended', function () {
audioIdx++;
if (audioIdx >= files.length) audioIdx = 0;
playById(audioIdx);
});
audio.src = files[input[audioIdx]];
audio.play();
Then I have another script which is used to play audio files. Exactly which files to play is based on the new data get by ajax from database. In my case, I want my second script run the files based on the variable $ticket.
The audio script is done and run perfectly. However, it only play the sound when I refresh the page. I need it to run automatically when the auto_refresh.js get new data. Please help, thanks.
This might help "big picture".
Note that the code in display.php only runs one time - when page initially loads. You need that code to run each time new data is received.
Therefore, you must create a new php file that accepts via POST the new data, and returns (via echo not return) the desired $ticket value. Call this page as an AJAX call inside the success function of the first AJAX call. Something like this:
auto_refresh.js
var mainDisplayCacheData;
var mainDisplayData = $('.aside').html();
var auto_refresh = setInterval(
function(){
$.ajax({
url: 'main_display.php',
type: 'POST',
data: mainDisplayData,
dataType: 'html',
success: function(mainDisplayData){
if(mainDisplayData !== mainDisplayCacheData){
mainDisplayCacheData = mainDisplayData;
$('.aside').html(mainDisplayData);
$.ajax({
url: 'new_php_file.php',
type: 'post',
data: mainDisplayData,
success: function(axData){
var files = ["0.mp3", "1.mp3",
"2.mp3", "3.mp3",
"4.mp3", "5.mp3",
"6.mp3", "7.mp3",
"8.mp3", "9.mp3"];
//below element already exists. You should update it rather than creating another
var audio = document.createElement("audio");
var audioIdx = 0;
var playById = function (id) {
audio.src = files[axData[id]]; //axData returned by AJAX
audio.play();
};
audio.addEventListener('ended', function () {
audioIdx++;
if (audioIdx >= files.length) audioIdx = 0;
playById(audioIdx);
});
audio.src = files[input[audioIdx]];
audio.play();
}
});
}
}
});
}, 1000);
new_php_file.php
<?php
$new_data = $_POST['mainDisplayData'];
//insert code required to run lines that follow, and/or modify as required
$tm = TicketManager::getInstance();
$tm->displayMainTicket();
$ticket = $tm->mainTicketSound();
echo $ticket;
Call the sound playing function in the other script in this block:
if(mainDisplayData !== mainDisplayCacheData){
// e.g. otherScriptFunction();
}
On the Server-side: You should echo the "$ticket" variable.
On the Client-side: Call your sound playing function inside the 'success' ajax callback:
if(mainDisplayData !== mainDisplayCacheData){
PLAY_SOUND(mainDisplayData);
}
I need use the changes only, not all the text, to provide server resources and service user.
see Code Mirror: Get Text Around Changes
HTML:
<textarea id="code">script.js</textarea>
JavaScript:
var id = document.getElementById("code");
var options = {mode:'javascript'};
var editor = CodeMirror.fromTextArea(id, options);
editor.on("change",function(cm,change){
$.ajax({
url:'update.php',
method:'POST',
data:{
save:true,
file:'script.js',
update:change
},
success:function(data){
console.log(data);
}
});
});
PHP:
if(isset($_POST['save']) && $_POST['save'] === true){
if(isset($POST['file']) && file_exists($POST['file'])){
$file = file_get_contents($POST['file']);
if(isset($POST['update']) && !empty($POST['update'])){
$change = #json_decode(#json_encode($_POST['update']));
//here how to use data from $change to update file script.js?
}
}
}
!!
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.
hey guys i read some of the other posts and tried alot but its still not working for me.
when i alert the array i get all the results on the first site but after sending the data to php i just get an empty result. any ideas?
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
window.location = "foo.php";
});
});
Php
$data = json_decode($_POST['data']);
THANK YOUU
my array looks something like this when i alert it house/flat,garden/nature,sports/hobbies
this are a couple of results the user might choose (from checkboxes).
but when i post it to php i get nothing. when i use request marker (chrome extension) it shows me something likethat Raw data cats=%5B%22house+themes%22%2C%22flat+items%22%5D
i also tried this way-- still no results
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
alert(cats);
$.ajax({
type: 'POST',
url: "foo.php",
data: {cats: JSON.stringify(cats)},
success: function(data){
alert(data);
}
});
});
window.location = "foo.php";
});
});
php:
$json = $_POST['cats'];
$json_string = stripslashes($json);
$data = json_decode($json_string, true);
echo "<pre>";
print_r($data);
its drives me crazy
Take this script: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
And call:
var myJsonString = JSON.stringify(yourArray);
so now your code is
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
// window.location = "foo.php"; // comment this by this page redirect to this foo.php
});
});
//and if uou want toredirect then use below code
-------------------------------------------------
$.post('foo.php',{data:st},function(data){
window.location = "foo.php";
});
---------------------------------------------------
Php
$data = json_decode($_POST['data']);
var ItemGroupMappingData = []
Or
var ItemGroupMappingData =
{
"id" : 1,
"name" : "harsh jhaveri",
"email" : "test#test.com"
}
$.ajax({
url: 'url link',
type: 'POST',
dataType: "json",
data: ItemGroupMappingData,
success: function (e) {
// When server send response then it will be comes in as object in e. you can find data //with e.field name or table name
},
error: function (response) {
//alert(' error come here ' + response);
ExceptionHandler(response);
}
});
Try this :-
$data = json_decode($_POST['data'], TRUE);
I think you should move the "window.location = " to the post callback, which means it should wait till the post finshed and then redirect the page.
$.post('foo.php', {
data : st
}, function(data) {
window.location = "foo.php";
});
I'm loading some data lively from the database and each row have some links that do some things over that.
They work flawlessly except for the last one I've implemented which seems not to be working on IE
$('.lockFile').click(function(){
var url = "functions/lock_call.php";
var unlock = 'assets/lock-unlock.png';
var lock = 'assets/lock.png';
var action = 'unlock';
var id = $(this).parent().parent().attr('id');
var image = $(this).children(0);
if (image.attr('src') == unlock)
action = 'lock';
var data = 'id='+id+'&action='+action;
$.ajax({
type: "POST",
url: url,
data: data,
cache: false,
success: function(){
alert (action);
if (action == 'lock')
image.attr('src', lock);
else
image.attr('src', unlock);
}
});
return false;
});
What could be wrong?
The alert is performer on "success" but nothing is made. That is, the script doesn't run.
IE 8 has some amazing variables reserved, try this one
$('.lockFile').click(function(){
var Aurl = "functions/lock_call.php";
var AunAlock = 'assets/lock-unlock.png';
var Alock = 'assets/lock.png';
var Aaction = 'AunAlock';
var Aid = $(this).parent().parent().attr('id');
var Aimage = $(this).children(0);
if (image.attr('src') == AunAlock)
Aaction = 'Alock';
var data = 'id='+Aid+'&action='+Aaction;
$.ajax({
type: "POST",
url: Aurl,
data: data,
cache: false,
success: function(){
alert (Aaction);
if (Aaction == 'lock')
Aimage.attr('src', Alock);
else
Aimage.attr('src', AunAlock);
}
});
return false;
});
try to declare data in JSON format
var data = {'id':id, 'action': action}