here it goes;
echo "<a href='#' class='thumb'><img class='thumb-img' value = ".$row->aid." onclick='getVote(".$row->aid.", \"".$row->atitle."\")' src='images/roadies/th".$row->aid.".jpg' /> </a>";
the above function sends the "$row->aid" value to a javascript function through ajax.
in the javascript however, i want to make a function that needs the ++value of the $row->aid variable. i want the php to get the new value and then pass it again to javascript.
how do i do it without a page reload?
to make things more clear, i just need to get the next incremented value of the php variable. i want php to get the next ++ value from the DB and pass it back to JS.
please help me do this. ;))
Maybe I'm misunderstanding,
But can't you just have a PHP script that returns a string, or a JSON object containing the value(s) you need, and then have the javascript function grab it from the server and update the properties in the link/image?
Also, typically you would get $row from mysql_fetch_assoc() or a similar function -- by calling the server again, re-querying the database, and iterating over mysql_fetch_assoc the necessary number of times, you're probably wasting time. Wouldn't it be easier for the PHP script to grab all of the rows, store them in JSON objects, and then (rather than using AJAX) having the javascript iterate through the JSON object and update the properties on each click?
update:
JSON is a text-based way to represent an object in JavaScript. Think of it like a multi-demensional array. http://en.wikipedia.org/wiki/JSON
You'll have a PHP script write a JSON object to a variable, which you would echo into a <script> tag like echo "var rows = {$JSON_obj};";. In javascript you would start with rows[1] and then each time the link is clicked, move to the next rows[i] or whatever.
jQuery is your friend here. It'll make AJAX (for wherever else you use it) and changing HTML elements much easier. I moved to jQuery and have never, ever looked back to the old ways. http://jquery.com/
I don't have an example on hand right now, but it's a pretty simple concept. I'm sure you'll be able to code this up with little effort.
you can write it to the standard output in PHP via echo $value; and finish PHP script there. javascript will then fetch the value and return it in the AJAX processing function.
Related
I am working on a project where I used ajax for asynchronous DB access.
I store the value in JavaScript variable as follows..
var content=xmlhttp.responseText;
now what I wanted is to pass this value to the php module on same page..
Please suggest me..its urgent
You'll have to make a separate AJAX request to another script to achieve this. PHP is server-sided and therefore cannot directly interact with the client.
You should handle the data (which you are assigning to content) in PHP because, as the other answers here tell you, PHP is server-side and JavaScript is on the client. If you are getting this data from a page you control, instead of var content = xhr.responseText; just modify the data BEFORE you send it. For example, if you are making an AJAX call to a process.php file on your server to get the data you are otherwise assigning to content in JavaScript, be sure to handle the data in process.php PRIOR to echo()'ing the data (which you are then storing inside content on the client):
In process.php:
// below is the normal server script which you are storing in content on the client
// echo $result;
// instead, we are going to operate on the data first:
return doSomething($result);
Then on the client:
var newContent = xhr.responseText;
And the newContent variable will contain the data you previously wished to modify with PHP. If you DO NOT have control of the server script which you are calling with AJAX, then as mentioned here already, you will need to send a SECOND AJAX call to the server with your PHP, and use $_GET or $_POST to retrieve that content data and then play with it there.
Am unclear about your need to pass value from javascript to php.
But I can give you,
A non-recommended but working approach towards your problem:
You said, you are making an Ajax call at first. While processing the corresponding server side php function, Store the response value (value of xmlhttp.responseText) into a $_SESSION variable. Finally Reload the page (using location.reload()) inside the ajax response handler function.
And a recommended approach towards your problem:
You might have added some if-else control-flow structures in the php code and expecting to execute them after getting the ajax response value (sadly you cannot do that). So if you do have some logic like that, then convert those if-else conditions to corresponding Javascript code. May be a javascript function and call that function by passing the ajax response value to it. This new function will use your ajax response value and make changes in some parts of your webpage by applying necessary logic.
I am looking for a really simple way of getting all the values from all input elements (and some dividers as well) and then quickly sending them to a PHP file with an already prepared submit function.
I have came up with a very crude solution but it needs to be heavily optimized.
For now when I click submit button I call a function
function $('#submit').click(function(){
var $divValues = new Array();
$divValues[0] = $('#divName').html();
$divtValues[1] = $('#divImgName').html();
var $values;
$values = $(':input').serializeArray();
$fileName = "php.php?firstVal=\""+$divValues[0]+"\"&secondVal=\""+$divtValues[1]+"\"&thirdVal=\""+$values['firstValName']+"\"&ect..."
//then i simply call the ajax function which will send the information to the php file
fetch($fileName);
});
maybe i could use the fact that the names of values in my associative array and the names of variables retrieved in my php file match and instead of setting my filename to ..."&thirdVal=\"" ... I would instead use the name of the $values['firstValName'] which in this example would be third value (although i have no idea how to do that)
or maybe there is an even easier way to accomplish what im trying to.
Any ideas on how to implement this piece of code in a nice manner??
Update:
For now I don't have a form element in my html but I can easily add one as soon as I see a solution that requires it to make the code simpler...
I know I can use serialize() function but my questions is about a nice way of dealing with the array that gets returned. (or maybe using 2 arrays one with name other with value or a 2 dimensional array)
Either way I just wish to see what is an easy way of both getting the data and creating the $fileName with correct values for the PHP file
I would appreciate some code or pseudocode in the answer that shows a simple way of creating the fileName with all the values
If anybody doesn't understand what I am asking or needs some clarification then they should feel free post a comment below so I can try to make myself clear.
Since you're using jQuery, you could use its AJAX methods with serialize() applied to the entire form. You can read documentation about it by clicking here. Also you can read documentation about jQuery's AJAX methods by clicking here, here and here.
In response to your request, here is a really simple example:
$.post("test.php", $("#testform").serialize());
You could really get the rest of what you need on how to use $.post or $.get functions from the documentation I referenced.
Serialize also takes care of urlencoding all the variables so you don't have to worry about that.
EDIT:
It's not really necessary to have a form. You could just do what you are trying to do with serializeArray() above, except (a) $(':input') does not select anything and (b) you should use serialize() and not serializeArray(). So without a form, the code would look as follows:
$.post("test.php", $("input,select,textarea").serialize());
This will properly request the script with the data encoded correctly and you can then read it in PHP script from $_POST or $_GET depending on whether you used $.post or $.get to request the script.
Can we update a javascript array variable, with out reloading a page as well as with out refreshing?
I am having a list of data in an array. Later I am getting some more data using php and ajax.
Now I would like to append the new data got from php ajax to the old javascript variable which is already having an array in it. I do not want to reload the page. But we can overwrite the data too.
Using this javascript variable some javascript functions are getting exicuted and displayes some picture according to the data. Can we do something like that? or do we have to reload the frame to execute the javascript?
Short answer: Yes, you can add/append/concatenate/whatever new array items to an existing array.
Explanation: Assuming that you have a variable containing an array, and a response that is an array or contains an array, you can use the array.concat() method to append the new content to the old array.
//let existingArray be your array in the page
var existingArray = [];
//during AJAX success, you overwrite the existing variable with
//a concatenated array comprising the old and the new.
existingArray = existingArray.concat(newArray);
If I answer this question in terms of yes/no, then yeah, with ajax callback function returning the data will be appended/concatenated to js variable.
Just like AJAX, where you need to call a JavaScript function for something to happen, you can also call a JavaScript function in the same way and instead of doing AJAX stuff, you can do other stuff. For instance add something to an array. Or overwrite it.
Simply call your function where you want it (in an onclick, or in the return of an AJAX call (success or error callbacks)), and let that function modify your variable.
I have a Javascript variable which I am setting a PHP variable to.
function cancel(number) {
var message = "<?= $message[" + number + "]; ?>";
}
$message is an array. "number" is the element of the array I want to set message to. Basically, I want to set a Javascript variable to a PHP variable using a Javascript variable as the element picker. So if "number" was 2, it would select:
$message[2];
However, the above approach doesn't work, and I'm not even sure if this is possible.
It isn't. Use XHR to retrieve the value from the server.
It doesn't seem at all possible; PHP is evaluated server-side, and javascript is evaluated client-side. So PHP would see it as $message["+number+"], and try to find the value at the index of "+number+". You'd probably have to do something like an AJAX request to get the data you're looking for.
What you are doing isn't possible; since php is a server-side language, it's executed first, and the js is executed after; there isn't any way to control which is executed first. You must retrieve the variable using AJAX.
Something like this will work:
<script type="text/javascript">
var messages = <?= json_encode($message) ?>;
function cancel(number) {
var message = messages[number];
}
</script>
Of course this will output the entire array in the JavaScript source. If it is large, then you are better off using AJAX.
Tip: if you "view source" it should be painfully obvious why your method doesn't work.
You simply cannot do this using this methodology. PHP is server-side code, meaning that it runs on the server, while JavaScript is client-side code, meaning it runs on the client, or your browser.
Once the PHP runs, it generates an HTML document and sends that document in the response to the browser. Once that's complete, the only way you can get data back to the server is to send it via a form POST, send it via AJAX, or send it via script tag remoting.
Consider looking at some examples on the Internet of how to POST data back to the server via a form and via AJAX. It's clear you're struggling with some concepts regarding how to properly architect your program, and looking at some examples would be a great way for you to learn and master these techniques.
PHP Submit Form Example
PHP Tutorial
You need to use AJAX call to resolve your issue.
Im not sure if this is possible, but at the moment I have a form on my page where users can insert their interests, beneath that form are 3 PHP variables (Which dont currently show at first as there is no value assigned to them).
When a user enters an interest and clicks submit, my AJAX takes over, populates the table and then reloads the page so the Variable now shows as it has a value.
Is it possible to not have to refresh the page, so I can say "if success $var = 'value';"?
I hope this doesnt sound too confusing, thanks
Since you're already using AJAX, why don't you just do the logic using Javascript? If you're using jQuery, have a success callback function execute the code you want.
The problem with sending data from AJAX to PHP is that PHP is a server side language, while AJAX is a client side one. By the time your browser sees the page, the PHP has been entirely executed and returned to you as HTML / CSS / Javascript etc.
No, you can't. By the time the HTML has rendered/displayed in the browser, PHP will most likely have long since finished generating the HTML in the first place. You could round-trip the values through an AJAX handler and then populate the places in your page where the values are displayed, but when why bother round-tripping? Just have the AJAX call fill in the values right then and there.
It is absolutely possible, and quite easy to do. Just make another php script and call it from your form page's javascript (I'm going to assume you're using jQuery):
$('#mysubmit').click(function() {
$.getJSON(
'form_ajax.php', // This is the php file that will be called
{ formVar1: $('#form-var-1').val() }, // Add all your form data here
function(data) {
// This is the function that is called after the php script is
// done executing. The 'data' variable will contain the $data
// array you see in the following php file.
}
);
});
I prefer to use JSON, but other approaches are just as good. Check out the documentation for getJSON() and ajax(). Your php file would look something like this:
<?php
$data = array();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$data['formVar1'] = $_POST['formVar1'];
}
echo json_encode($data);
?>
Of course, yours would probably do a lot more with the form data. Also, theres plenty of other approaches so go explore for the one the best suits your needs.