I am trying to get a jQuery script to run behind the scenes with php. It basically will get the contents of a div with jQuery (works) then calls a script with ajax (works) but I need the ajax script that called the php to send the vars to php so I can save the conents.
Here is the code:
<script>
$( document ).ready(function() {
$( ".tweets" ).click(function() {
var htmlString = $( this ).html();
tweetUpdate(htmlString);
});
});
</script>
<script>
function tweetUpdate(htmlString)
{
$.ajax({
type: "POST",
url: 'saveTweets.php',
data: htmlString,
success: function (data) {
// this is executed when ajax call finished well
alert('content of the executed page: ' + data);
},
error: function (xhr, status, error) {
// executed if something went wrong during call
if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
}
});
}
</script>
and my code for saveTweets.php
<?
// SUPPOSED TO receive html conents called htmlString taken from a div
// and then I will write this code to a file with php and save it.
echo $_POST[htmlString];
?>
You have to give a name to the parameter, so that PHP can retrieve it. Change the $.ajax call to do:
data: { htmlString: htmlString },
Then in your PHP, you can reference $_POST['htmlString'] to get the parameter.
Correct your funcion.
function tweetUpdate(htmlString)
{
$.ajax({
type: "POST",
url: 'saveTweets.php',
data: "htmlString="+htmlString,
success: function (data) {
// this is executed when ajax call finished well
alert('content of the executed page: ' + data);
},
error: function (xhr, status, error) {
// executed if something went wrong during call
if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
}
});
}
then on saveTweets.php page write below line, you will get value on that page.
echo '<pre>';print_r($_REQUEST );echo '</pre>';
Using json is better for sending data:
data_htlm=[];
data_html.push({"htmlString": htmlString});
$.ajax(
{
type: "POST",
dataType: "json",
url: "saveTweets.php",
data: JSON.stringify(data_html),
success: function(html)
{
console.log(html);
}
});
now with php you can just do this:
echo $_POST['htmlString'];
You can use the $.post method to post to a PHP page and then retrieve the result from that page in a callback function.
Related
I've got a variable that I want to send to my PHP code that is on top of the code but I keep getting an error and undefined. dTotaal is the variable name and it contains a number. All this code is in the same page, so i am posting to the same page.
$('#emailVerzenden').click(function() {
$.ajax({
url: "content.php",
type: "post",
data: ({
totaal: dTotaal
}),
success: function(msg) {
alert('Data saved: ' + msg);
},
error: function(error) {
alert("couldnt be sent " + error);
}
});
On top of my page I've got this code. I'm not sure if it's correct, I am new at this.
if(isset($_POST['emailVerzenden']))
{
$totaal = $_POST['totaal'];
var_dump($totaal);
}
What I wanted was to put the value of the totaal data in $totaal but that is not working. The data is not being sent. I keep getting the error alert().
In your PHP code, you are checking the presence of a variable to use another. For me it should be:
if(isset($_POST['totaal']))
{
$totaal= $_POST['totaal'];
var_dump($totaal);
}
You are on right track but seperate PHP codes with jQuery codes then you will have full control of processing data asynchronously.
index.php
$('#emailVerzenden').click(function()
{
$.ajax
({
url: "content.php",
type: "post",
data:{totaal: dTotaal},
success: function(msg)
{
alert('Data saved: ' + msg);
},
error: function(error)
{
alert("couldnt be sent ".error);
}
});
And in your php file first check whether $_POST data is set
content.php
if(isset($_POST))
{
$totaal= $_POST['totaal'];
var_dump($totaal);
}
Mention your data which you wanna send in html & give it an ID.
<div id="total"> HERE COMES THE VARIABLE YOU WISH TO SEND </div>
Then pick up the data in that <div> by its ID document.getElementById('total').value like below:
var total=document.getElementById('total').value;
<script> var total=document.getElementById('total').value;
$.post('content.php',
{'total':total},
function(response){
if(response == 'YES'){}
});
</script>
Hope this will resolve your problem. Good Luck!
Kind of look like i didnt use preventDefault() thats why it wasnt working.
$('#emailVerzenden').click(function(e)
{
cms=$('#sCms').val();
templates= $('#templates').val();
onderdelen = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
email = $('#email').val();
e.preventDefault();
$.ajax
({
type: "POST",
url:"test.php",
data:{postEmail : email,postOnderdelen : onderdelen,postCms : cms,postTotaal : postTotaal, postTemplates : templates},
success: function(rs)
{
alert("Data saved:" + rs);
},
error: function(error)
{
alert("couldnt be sent" + error);
}
});
e.preventDefault();
});
I'm using jquery multiselect plugin and I want to perform an ajax request on a select/deselect event.
My problem: When I send the request to the php file, ISSET(VAR) returns every time false so that I can't pass variable to the php file.
But Firebug extension for Chrome/Firefox shows me that the POST value is set right POST -> "Response myvar" but GET is empty.
How do I pass the variable to the php file?
(I've searched arround the web but found nothing.)
My script, where this pointer is from the multiselect plugin and afterSelect returns if a object is selected
afterSelect: function()
{
this.qs1.cache();
this.qs2.cache();
count++;
var dataString = "count=" + count;
if ( count > 0 )
{
$.ajax
({
type: 'POST',
url: 'page-to-send-request.php',
data: dataString,
success: function()
{
$("#div-to-load").load("page.php #div-to-load").fadeIn('slow');
},
error: function (xhr, ajaxOptions, thrownError)
{
alert(xhr.status);
alert(thrownError);
}
});
}
},
The php page to load has for test only
if($_POST['count'])
{
$count = $_POST['count'];
echo "Count " .$count;
}
else{ echo "FALSE"; }
Expected result should be
Count 5
But real output is
FALSE
1st try
success: function(data)
{
console.log(data);
},
it should output "Count " .$count; if not
try to use
var dataString = {count: count};
and then you can use
$("#div-to-load").html(data).fadeIn('slow');
the reason of return false .. you used the .load to load the php page .. when you load it .. javascript know it as a separated page .. so $_POST['count'] is undefined in this case . and It will return False always
your success function should be like this
success: function(data)
{
$("#div-to-load").html(data).fadeIn('slow');
},
I have checked around, but can't seem to figure out how this is done.
I would like to send form data to PHP to have it processed and inserted into a database (this is working).
Then I would like to send a variable ($selected_moid) back from PHP to a JavaScript function (the same one if possible) so that it can be used again.
function submit_data() {
"use strict";
$.post('insert.php', $('#formName').formSerialize());
$.get('add_host.cgi?moid='.$selected_moid.');
}
Here is my latest attempt, but still getting errors:
PHP:
$get_moid = "
SELECT ID FROM nagios.view_all_monitored_objects
WHERE CoID='$company'
AND MoTypeID='$type'
AND MoName='$name'
AND DNS='$name.$selected_shortname.mon'
AND IP='$ip'
";
while($MonitoredObjectID = mysql_fetch_row($get_moid)){
//Sets MonitoredObjectID for added/edited device.
$Response = $MonitoredObjectID;
if ($logon_choice = '1') {
$Response = $Response'&'$logon_id;
$Response = $Response'&'$logon_pwd;
}
}
echo json_encode($response);
JS:
function submit_data(action, formName) {
"use strict";
$.ajax({
cache: false,
type: 'POST',
url: 'library/plugins/' + action + '.php',
data: $('#' + formName).serialize(),
success: function (response) {
// PROCESS DATA HERE
var resp = $.parseJSON(response);
$.get('/nagios/cgi-bin/add_host.cgi', {moid: resp });
alert('success!');
},
error: function (response) {
//PROCESS HERE FOR FAILURE
alert('failure 'response);
}
});
}
I am going out on a limb on this since your question is not 100% clear. First of all, Javascript AJAX calls are asynchronous, meaning both the $.get and $.post will be call almost simultaneously.
If you are trying to get the response from one and using it in a second call, then you need to nest them in the success function. Since you are using jQuery, take a look at their API to see the arguments your AJAX call can handle (http://api.jquery.com/jQuery.post/)
$.post('insert.php', $('#formName').formSerialize(),function(data){
$.get('add_host.cgi?moid='+data);
});
In your PHP script, after you have updated the database and everything, just echo the data want. Javascript will take the text and put it in the data variable in the success function.
You need to use a callback function to get the returned value.
function submit_data(action, formName) {
"use strict";
$.post('insert.php', $('#' + formName).formSerialize(), function (selected_moid) {
$.get('add_host.cgi', {moid: selected_moid });
});
}
$("ID OF THE SUBMIT BUTTON").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data: $("ID HERE OF THE FORM").serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
return false; //This stops the Button from Actually Preforming
});
Now for the Php
<?php
start_session(); <-- This will make it share the same Session Princables
//error check and soforth use $_POST[] to get everything
$Response = array('success'=>true, 'VAR'=>'DATA'); <--- Success
$Response = array('success'=>false, 'VAR'=>'DATA'); <--- fails
echo json_encode($Response);
?>
I forgot to Mention, this is using JavaScript/jQuery, and ajax to do this.
Example of this as a Function
Var Form_Data = THIS IS THE DATA OF THE FORM;
function YOUR FUNCTION HERE(VARS HERE) {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data:Form_Data.serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
}
Now you could use this as the Button Click which would also function :3
Im using the jquery .load function to query a php file that will output some data. Now sometimes the script will return nothing. In this case, can I have the load function not put any data into my specified div? (right now it clears out the div and just puts a blank white area.
Thanks!
try using $.get;
$.get('<url>',{param1:true},function(result){
if(result) {
$('selector').html(result);
}
else {
//code to handle if no results
}
});
Use $.get
http://api.jquery.com/jQuery.get/
in addition to #jerjer's post, you can also use this:
var paramData= 'param=' + param1 + '&user=<?echo $user;?>';
$.ajax({
type: "GET",
data:paramData,
url: "myUrl.php",
dataType: "json", // this line is optional
success: function(result) {
// do you code here
alert(result); // this can be an any value returned from myUrl.php
},
statusCode: {
404: function() {
alert('page not found');
}
}
});
I'm trying to implement the Jquery .ajax method to simplify the ajax in my website.
Here is the function I'm working with:
function autoComplete(q, succ)
{
$.ajax({type:"GET",
url: "search.php",
data: "q="+q,
success: succ
});
}
$('input#auto_results').live('keyup', function() {
var text = $('input#auto_results').val();
autoComplete(text,
function(data)
{
alert(data);
});
});
The response on the PHP page is simply:
echo "response";
So I figure that it should alert the response when the function is called, on 'keyup'.
Sadly, nothing occurs. I must be doing something wrong, I am just not sure what it is.
is "keyup" event firing?
do following.
$('input#auto_results').live('keyup', function() {
var text = $('input#auto_results').val();
alert("Keyup event is firing");
autoComplete(text,
function(data)
{
alert(data);
});
});
if event is firing. then see firebug console tab
or put error function callback on your code:
function autoComplete(q, succ)
{
$.ajax({type:"GET",
url: "search.php",
data: "q="+q,
error:function(request, textStatus, err){
alert(request.statusText);
},
success: succ
});
}
you may get near to error.