What am I doing wrong here?? Everything works fine and there are no errors in the console but there are also no console logs saying it succeeded
index file with script:
<script type="text/javascript">
function upVote(picNum)
{
var pictureNumber = parseInt($("#" + picNum).attr("id"));
$.ajax({
url: "upload/pics/changeVote.php",
data: {"picNum":pictureNumber},
type:'post',
dataType:'json',
success: function(output_string){
PictureNumber = output_string['picturenumber'];
alert(PictureNumber);
}
});
var currentVote = parseInt($("#" + picNum).attr("value"));
alert("pictureNumber is " + pictureNumber + "and currentVote is " + currentVote); //here to help me, no functionality
$newVote = currentVote + 1;
alert($newVote); //here to help me
}
</script>
/upload/pics/changeVote.php
<?php
$picNum = $_POST['picNum'];
function otherFileFunc($pic){
$final = $pic + 1;
return $final;
}
$outputnumber = function($picNum);
$array = ('picturenumber' => $outputnumber);
echo json_encode($array);
?>
Mistake in /upload/pics/changeVote.php
$outputnumber = function($picNum);
has to be:
$outputnumber = otherFileFunc($picNum);
you can't use function(), you should use the function name instead.
Related
I want to pass an array to my AJAX function within the success function of an AJAX call. This array is data from my database using a global $wpdb; because this is easy to use and I know how to. Is there a way to pass this array to the AJAX function? Or is there a way to just get the data in AJAX?
I got this in my script tag and it is working:
jQuery(document).ready(function(){
jQuery('#date-select').on('change',function(){
var seldate= jQuery(this).val();
if(seldate!=''){
var seldateEdited = seldate.replace("T", " ");
jQuery.ajax({
type:'POST',
url:'http://esr-berlin.de/wp-admin/admin.php?page=einteilung_erstellen',
data:'var='+seldate,
success:function(html){
var output = '<option value="">Wähle HSR1</option>';
jQuery.each(html.data, function(i,s){
var newOption = s;
output += '<option value="' + newOption + '">' + newOption + '</option>';
});
jQuery('#hsrPop').empty().append(output);
}
});
}
});
});
EDIT
I forgot something important. For the array or especially for the sql query I need a variable that I have in javascript. So I basically need another AJAX Call, right? How would I do that?
You can encode the array in the PHP file and return this. It will just return a string to your AJAX function
json_encode($array)
https://www.php.net/manual/en/function.json-encode.php
You can then use to convert it into a Javascript array for processing
JSON.parse(json)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Assuming Your server side code(admin.php) something like:-
$result = array();
//your code here to fetch data dynamically
$result['status'] = True; //based on your conditions optional
$result['data'] = array(0=>"option1",1=>"option2",2=>"option3") ;
echo json_encode($result);
Hope this will help.
jQuery(document).ready(function()
{
jQuery('#date-select').on('change',function()
{
var seldate= jQuery(this).val();
if(seldate!='')
{
var seldateEdited = seldate.replace("T", " ");
jQuery.ajax({
type:'POST',
dataType:'json', //added to receive json format data
url:'http://esr-berlin.de/wp-admin/admin.php?page=einteilung_erstellen',
data:'var='+seldate,
success:function(html)
{
//here you can check if html.status is True/False .. optional
var output = '<option value="">Wähle HSR1</option>';
jQuery.each(html.data, function(i,s)
{
var newOption = s;
output += '<option value="' + newOption + '">' + newOption + '</option>';
});
jQuery('#hsrPop').empty().append(output);
}
});
}
});
});
I am quite new to to ajax, just learning it, and made a simple page on localhost to test gets and posts from/to json file in the same folder.
While GET is working smoothly, I cannot figure out, why post doesn't happen if I click the button I assigned this function to.
Pls take a look into my code and help.
element = $("#mylist");
var item2 = $("#mytable");
$.ajax({
type: "GET",
url: "data.json",
success: function(response) {
$.each(response, function(i, item) {
element.append("<li>" + item.fname + " " + item.lname + "</li>");
item2.append("<tr><td>" + item.lname + "</td>" + "<td>" + item.fname + "</td></tr>");
});
},
error: function() {
alert("error");
}
});
$("#additem").on('click', function() {
var $fname = $("#fname");
var $lname = $("#lname");
var $city = $("#city");
var order = {
fname: $fname.val(),
lname: $lname.val(),
city: $city.val()
};
console.log(order);
$.ajax({
type: "POST",
url: "data.json",
data: order,
succes: function() {
console.log("succes");
},
error: function() {
console.log("no success");
}
});
});
JSFiddle
The problem is you are trying to post to a .json file, like Patrick Evans says in the comments. You need to do the post to a script, in PHP you could do something like this:
$order = $_POST['order'];
// Do something with order...
echo $order; // or echo success message
Of course for this to work you will need PHP to be running on your server (localhost).
I have following code to execute a query on the Database. it returns a list of objects, one for each row result from the query:
function getcontent()
{
var data = {
"id": "<?php echo $stournid; ?>"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php",
data: data,
success: function(response) {
//**************************** HERE!!!!
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
return false;
}
The response.php file contains this:
<?php
$id = "";
if (is_ajax()) {
if (isset($_POST["id"]) && !empty($_POST["id"])) { //Checks if action value exists
$id = $_POST["id"];
querydata($id);
}
}
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function querydata($id){
require_once('dbconfig.php');
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_error) {
die('Errore di connessione (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$myArray = array();
if ($games = $mysqli->query("my query is here.. pretty long but working correctly.")){
while($row = $games->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
}
?>
here is the returned data:
[{"id":"1435","location":"Merano","date":"2017-01-26","eventname":"Collaudo","machines":"|6|","id_tournament":"2","allowedcat":"|A||B||C||D|","category":"test 1","chartsize":"8","exclusive":"0","subscriptionsactive":"0","maxsubscriptions":"512","autoplay":"3","machinespergame":"1","id_subtournament":"14","id_gamer1":"57","id_gamer2":"55","called":"2","callreadytime":"13:08:07","starttime":"22:12:19","endtime":"22:20:03","id_winner":"57","id_loser":"55","playsequence":"00001","tabsequence":"A00010001","dest_winner":"B00010001-1","dest_loser":"C00010001-1","connectionname":"","p1name":"Calamante Lorenzo","p2name":"Badiali Maurizio"},
{"id":"1436","location":"Merano","date":"2017-01-26","eventname":"Collaudo","machines":"|4|","id_tournament":"2","allowedcat":"|A||B||C||D|","category":"test 1","chartsize":"8","exclusive":"0","subscriptionsactive":"0","maxsubscriptions":"512","autoplay":"3","machinespergame":"1","id_subtournament":"14","id_gamer1":null,"id_gamer2":null,"called":"0","callreadytime":"00:00:00","starttime":"00:00:00","endtime":"00:00:00","id_winner":"0","id_loser":"0","playsequence":"00015","tabsequence":"W00010001","dest_winner":"","dest_loser":"1","connectionname":"","p1name":null,"p2name":null}]
What I would like to do, is in the Javascript, go through all the returned lines one by one and updated some div's accordingly. I am having difficulties on how to iterate the returned lines.
Any help appreciated.
Thanks
success: function(response) {
// redponse is an array of objects (so lets loop through it using forEach)
response.forEach(function(row) {
// row is a row (object) from the array
var id = row.id;
var location = row.location;
var date = row.date;
// ... you get the idea
// do something with the current row (maybe create a div or table row ...)
});
},
Note: Array.prototype.forEach is like a loop but better. Check the docs.
Don't want to use forEach?
If you don't want to use forEach, you can use an old for like this:
success: function(response) {
// using for is not very pretty, hein?
for(var i = 0; i < response.length; i++) {
// response[i] is the i-th row of the array
var id = response[i].id;
var location = response[i].location;
var date = response[i].date;
// ... you get the idea
// do something with the current row (maybe create a div or table row ...)
});
},
I have this simple code as part of a PHP file, the purpose of this code is to execute the job1.js file on the client side (has to be done so), in this file I have a function called job1() that returns 3 variable back. The returned variables must be passed to the Server for further work.
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type = "text/javascript" >
$(document).ready(function() {
// $jobJSPath[0] holds the path to the job1.js file
var scriptPath = "<?php echo $jobJSPath[0]; ?>";
$.getScript(scriptPath, function(data, textStatus, jqxhr) {
// Call the function
job1();
window.alert( data ); // Data, actually it has only the content of the file as a string
window.alert( textStatus ); // Success
window.alert( jqxhr.status ); // 200
});
});
</script>
The function is being executed without any problems, it’s doing some internal string operations (very boring :) ) and returns 3 variables back.
My question is how do I get the 3 return variables from the job1() function with their input back. I searched a lot and even tried
var result = eval('(' + data + ')');
console.log(result);
Because the data variable holds the function as a string but still without any success, this option was suggested on some other page on this site.
EDIT: the data and the job1 have same text:
´function job1() {
var text = "";
var vocabulary = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 1; i <= 500; i++) {
text += vocabulary.charAt(Math.floor(Math.random() * vocabulary.length));
}
var subText1 = text.slice(0, Math.floor(Math.random() * text.length));
var subText2 = text.slice(subText1.length, text.length);
//test for output
alert("This is JavaScript");
var nextJob = "job2, job3";
var prevJob = "null";
return {
text_RT : text,
subText1_RT : subText1,
subText2_RT : subText2
};
}´
java script is for the client side, php is for the server side, just use ajax call and pass the data using post, after job1() is done and you got the returned array, just use an ajax call like this:
var yourdata=job1();
var postdata= [{"1": yourdata[0], "2": yourdata[1], "3": yourdata[2]}];
$.ajax({
type: POST,
data: postdata,
url: "test.php", //stands for the php file you want to send the data to
}).done(function() {
//do something.....
})
on the server side fetch the data using $_POST["1"] for example
Well that what I have until now
<script type = "text/javascript" >
$(document).ready(function() {
// $jobJSPath[0] holds the path to the job1.js file
var scriptPath = "<?php echo $jobJSPath[0]; ?>";
$.getScript(scriptPath, function(data, textStatus, jqxhr) {
// Call the function
var job = job1();
window.alert( data ); // Data, actually it has only the content of the file as a string
console.log(job); // shows all the return parameters from job1();
window.alert( textStatus ); // Success
window.alert( jqxhr.status ); // 200
// push the return parameters into result array
var result = [];
$.each(job, function(index, value) {
//window.alert(index + ": " + value);
result.push(value);
});
// post the results back to the same page
$.ajax({
type: 'POST',
data: {result : result},
url: 'executedJobs.php',
}).done(function(data) {
var redirectUrl = "executedJobs.php";
var form = $('<form action="' + redirectUrl + '" method="post">' +
'<input type="hidden" name="result" value="'+ data +'" />' +
'</form>');
$('body').append(form);
$(form).submit();
});
});
});
</script>
And after that to get the results on the the executedJobs.php page I used
<?php
$myArray = $_REQUEST['result'];
echo "myArray:<br/>";
print_r($myArray);
?>
It works that way, the only thing is I get the word myArray echoed twice every time before the print_r($myArray);.
I have a search function that is suppose to search a name from the database, and then when the user clicks add, the item choosen has to appear below the search field, in short it has to be posted back so that the user can re-select his/her second option from the search element so that all the selected options can be saved in the database. The problem im facing is that after I click add im getting undefined value back instead of the one I choose and my response is a name instead of an Id number, here is my code and a picture below.
MODEL
public function getName($id)
{
$select = $this->select()
->where('service_provider_id LIKE "' . $id . '%"')
->order('service_provider_name');
return $this->fetchAll($select);
}
CONTROLLER
{
$id = $this->getRequest()->getParam('id');
$mdlserviceprovider = new Model_ServiceProviders();
$serviceprovider = $mdlserviceprovider ->getName($id);
$arr_rtn = array();
if (count($results) > 0){
foreach($results as $result)
{
$myarr = array( 'label' => $result->service_provider_name,
'value' => $result->service_provider_name,
'id' => $result->service_provider_id
);
array_push($arr_rtn, $myarr);
}
}
echo Zend_Json::encode($arr_rtn);
}
PHTML/AJAX
$('#add1').click(function(){
var data = {};
data['sp'] = $("#search").val();
$.ajax({
url:'<?php echo $this->baseUrl()?>/ajax/postserviceprovider/id',
type:'post',
dataType: "json",
data: data,
success:function(data){
var row = '<tr><td>' + data["serviceprovider"] + '</td></tr>';
$('#t1').append(row);
//alert();
}
});
});
Thanks in advance
You can use data["value"] instead of data["serviceprovider"]:
var row = '<tr><td>' + data["value"] + '</td></tr>';
Since you've encoded the array which contains three keys: label, value and id. So there's no serviceprovider key at this moment for Zend to encode.
You are looking for a key that doesn't exist in the array you are returning try this
var row = '<tr><td>' + data['label'] + '</td></tr>';
Or this
var row = '<tr><td>' + data['value'] + '</td></tr>';
As those are the two keys you defined in your PHP page
Try
var row = '<tr><td>' + data[0].value + '</td></tr>';
Also try to put an alert() in the success function like,
alert(JSON.stringify(data));
and see what is included in it..
From what I see I think you are ruturning a multidimensional array from php so I would try something like this in javascript:
$('#add1').click(function(){
var data = {};
data['sp'] = $("#search").val();
$.ajax({
url:'<?php echo $this->baseUrl()?>/ajax/postserviceprovider/id',
type:'post',
dataType: "json",
data: data,
success:function(data){
data.each(function(index, el){
var row = '<tr><td>' + el.label + '</td></tr>';
$('#t1').append(row);
//alert();
}
}
});
});
In your controller try:
$this->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
return $this->_helper->json(array('key1' => $val1, 'key2' => $val2, ...));