Passing a value from JQuery .post to PHP - php

I just started picking up JQuery today, and for some reason I can't get this simple $.post to work when a form is submitted.
I want to pass the value of 2 as star to my PHP page "update_item.php".
I added an alert and saw that when I clicked submit it would give me the alert, but for some reason the value of 2 just doesn't pass to the php page.
Here's what I have with JQuery:
$('#form_edit_item').submit(
function(){
alert("submitting");
$.post(
"edititem.php",
{star: "2"},
);
});
Here's what I have in update_item.php:
$star = $_POST['star'];
echo "Star value: " .$star. "";
What am I doing wrong?
Your help would be very much appreciated! Thanks!

$.post(url, data, callback, "json");
http://docs.jquery.com/Ajax/jQuery.post

$('#form_edit_item').submit(
function() {
alert("submitting");
$.post("update_item.php", {
star : "2"
});
});
Remove the trailing comma after {star : "2"}. Try this.

You could use ajax
$.ajax({
type: "POST",
url: "update_item.php",
data: {
star: "2" // or 'star: $('#id').val()', or any other value
}
}).done(function( msg ) {
// do it when its done or do nothing
});
and in update_item.php you should use somthing like that
<?php $star=(isset($_POST['star']) ? $_POST['star'] : '');
echo $star; ?>
If this won't work, try change POST to GET so you can check passing value by url (domain.com/update_item.php?star=2)

You can Use this code,
<form action="../handler/AjaxHelper.php" method="POST">
</form>
$(document).ready(function() {
$('form').submit(function() {
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function(data)
{
var result = $.parseJSON(data);
if (result["messageCode"] == 'success')
{
alert(result["message"]);
}
else
{
alert(result["message"])
}
},
error: function()
{
alert("Please Try Again");
}
});
return false;
});
});
In AjaxHelper.php
$objLoginHelper = new LoginHelper();
$objLoginHelper = unserialize($_SESSION["LoginInformation"]);
$postDate = date("Y-m-d H:i:s", strtotime($_POST['txtTopicDate']));
$dataTopics = array($_POST['txtTopicSubject'], $postDate, $_POST['ddlCategories'], $objLoginHelper->getUserLoginId());
$result = array();
try {
$rp = new Repository();
$rp->SaveForumTopics($dataTopics);
$result["messageCode"] = "success";
$result["message"] = "Category Save Successfully";
} catch (Exception $ex) {
$result["messageCode"] = "error";
$result["message"] = $ex->getMessage();
}
echo json_encode($result);

Related

Ajax POST to Cakephp Controller always give array() result

i really struggle to get the POST value in the controller .i am really new to this..Please someone share me some light..being in the dark for long hours now.
i had a checkboxes and need to pass all the ids that had been checked to the controller and use that ids to update my database.i don't know what did i did wrong, tried everything and some examples too like here:
sending data via ajax in Cakephp
found some question about same problem too , but not much helping me( or maybe too dumb to understand) . i keep getting array();
please help me..with my codes or any link i can refer to .here my codes:
my view script :
<script type="text/javascript">
$(document).ready(function(){
$('.checkall:button').toggle(function(){
$('input:checkbox').attr('checked','checked');
$('#button').click( function (event) {
var memoData = [];
$.each($("input[name='memo']:checked"), function(){
memoData.push($(this).val());
});
var value = memoData.join(", ")
//alert("value are: " + value);
//start
$.ajax({
type:"POST",
traditional:true;
data:{value_to_send:data_to_send},
url:"../My/deleteAll/",
success : function(data) {
alert(value);// will alert "ok"
},
error : function() {
alert("false submission fail");
}
});
//end
} ); //end of button click
},function(){//uncheck
$('input:checkbox').removeAttr('checked');
});
});
my controller :
public function deleteAll(){
if( $this->request->is('POST') ) {
// echo $_POST['value_to_send'];
//echo $value = $this->request->data('value_to_send');
//or
debug($this->request->data);exit;
}
}
and result of this debug is:
\app\Controller\MyController.php (line 73)
array()
Please help me.Thank you so much
How about this:
Jquery:
$(document).ready(function() {
$('.checkall:button').toggle(function() {
$('input:checkbox').attr('checked','checked');
$('#button').click(function(event) {
var memoData = [];
$.each($("input[name='memo']:checked"), function(){
memoData.push($(this).val());
});
//start
$.ajax({
type: 'POST',
url: '../My/deleteAll/',
data: {value_to_send: memoData},
success : function(data) {
alert(data);// will alert "ok"
},
error : function() {
alert("false submission fail");
}
});//end ajax
}); //end of button click
},function(){//uncheck
$('input:checkbox').removeAttr('checked');
});
});
In controller:
public function deleteAll()
{
$this->autoRender = false;
if($this->request->is('Ajax')) { //<!-- Ajax Detection
$elements = explode(",", $_POST['value_to_send']);
foreach($elements as $element)
{
//find and delete
}
}
}
You need to set the data type as json in ajax call
JQUERY CODE:
$.ajax({
url: "../My/deleteAll/",
type: "POST",
dataType:'json',
data:{value_to_send:data_to_send},
success: function(data){
}
});

How to return a ajax error?

I want to show a ajax error after submitting a form. It ends now with 'die'
but what is the best way to handle this? Just write something in this php file in 'script' tags?
if($_POST['postForm'] == 'newsletter'){
$newsletterSubscriber = new NewsletterSubscriber();
$newsletterSubscriber->set('CMS_newsletters_id', 2);
$newsletterSubscriber->set('created', date('Y-m-d H:i:s'));
$newsletterSubscriber->set('firstName', $_POST['voornaam']);
$newsletterSubscriber->set('lastName', $_POST['achternaam']);
$newsletterSubscriber->set('companyName', $_POST['beddrijfsnaam']);
$newsletterSubscriber->set('emailAddress', $_POST['email']);
$newsletterSubscriber->set('subscribed', 1);
$saved = $newsletterSubscriber->save();
die('subscriber added');
}
I tried several solutions I found but I can't get it to work.
Thanks!
All you need to do is create a array and place any parameters you want to pass back into that array, then use json_encode() to turn it into a json string that can be easily processed by javascript
if($_POST['postForm'] == 'newsletter'){
$newsletterSubscriber = new NewsletterSubscriber();
$newsletterSubscriber->set('CMS_newsletters_id', 2);
$newsletterSubscriber->set('created', date('Y-m-d H:i:s'));
$newsletterSubscriber->set('firstName', $_POST['voornaam']);
$newsletterSubscriber->set('lastName', $_POST['achternaam']);
$newsletterSubscriber->set('companyName', $_POST['beddrijfsnaam']);
$newsletterSubscriber->set('emailAddress', $_POST['email']);
$newsletterSubscriber->set('subscribed', 1);
$saved = $newsletterSubscriber->save();
$response = array('error_code'=>0,
'message'=>'subscriber added'
);
echo json_encode($response);
exit;
}
The javascript woudl be something like
$.ajax({
type: "POST",
url: "connection.php",
data: {param1: 'aaa'},
dataType: JSON
})
.done( function(data){
if(data.error_code == 0) {
alert(data.message);
}
});
Note when you use dataType:JSON the browser automatically converts the json string returned to a javascript object so you can address data.error_code and data.message in simple javascript object notation
You can do like:
if($saved) {
die('subscriber added');
} else {
echo "error";
}
and In ajax you can check:
$.ajax({
type: "POST",
url: "savedata.php",
data: form,
cache: false,
success: function(data){
if(data == "error") {
alert("Data has not been saved successfully. Please try again.");
window.location.reload(true);
}
}
});
Did you check jQuery Ajax API? this comes directly from their example.
It says that you can use the .done() .fail and .always() functions
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
the best solution is to make you custom json and send it to ajax:
instead of die try:
$message = array('error'=>'subscriber added');
echo json_encode($message);
and in you ajax callback do:
function(success) {
if(success.error) {
//do stuff
}
//do stff
}
Use a json message followed by a error number:
if($saved) {
echo json_encode(array('message'=>'Successfully saved','erno'=>0));
} else {
echo json_encode(array('message'=>'Error on save','erno'=>1));
}
js:
success:function(data) {
if(data.erno == 1) {
alert(data.message)
//do other stuf here
} else {
alert(data.message)//if save was successful
}
}

How to run PHP with Ajax to validate results?

I'm making a Ajax script which validates results with PHP file before processing. Below is my Ajax script but I don't understand how to retrieve this DATA to validate.php and how to get results back from my PHP file.
<script>
function shake(){
if($("#pw").val()=="")
{
$("#sc1810").effect("shake");
}
else{
var image = document.getElementById('go');
image.src="images/loader.gif";
var resultado="";
$.ajax({
url: "validate.php",
type: "POST",
data: "userID=" + $("#userID").val()+"&pw=" + $("#pw").val(),
success: function(data){
resultado=data;
image.src="images/png17.png";
if(resultado==0)
{
$("#sc1810").effect("shake");
$("#pw").val("");
$("#pwID").text("Password");
$("#pw").focus();
}
else{
image.src="images/png17.png";
window.location.href = resultado;
}
}
});
}
}
</script>
How can I process this Ajax script with validate.php ?
Can it be like:
<?php
// Get values from AJAX
$userid = $_GET['userID'];
$pass = $_GET['pw'];
?>
What results is this Ajax script expecting? I see resultado==0
So my question is how can I send resultado=1 with PHP to this script?
Should it be:
<?php
// Send result to AJAX
$resultado = 1;
?>
Thank you for helping.
I think this is what you're asking for.
The php script at the bottom is missing the closing tag for a reason.
In the success function, after you parse the result into a json object, you can reference the members with a '.' E.G result.varName
<script>
function shake()
{
if($("#pw").val()=="")
{
$("#sc1810").effect("shake");
}
else
{
var image = document.getElementById('go');
image.src="images/loader.gif";
var resultado="";
$.ajax({
url: "validate.php",
type: "POST",
data: {userID: $("#userID").val(), pw: $("#pw").val()},
success: function(data){
try
{
var result = $.parseJSON(data);
// result is now a JSON object
}
catch (e)
{
alert("JSON Parsing Failed on" + data );
return 0;
}
console.log(result);
if(result.isValid === 1){
// do something
}
alert(result.Message);
resultado=data;
image.src="images/png17.png";
if(resultado==0)
{
$("#sc1810").effect("shake");
$("#pw").val("");
$("#pwID").text("Password");
$("#pw").focus();
}
else
{
image.src="images/png17.png";
window.location.href = resultado;
}
}
});
}
}
</script>
<?php
if( !isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD'] != 'POST')
{
exit;
}
if( !isset($_POST['userID']) || !isset($_POST['pw']) )
{
// need more validation than this
exit;
}
$output = array();
$output['isValid'] = '1';
$output['Message'] = 'Data transfered';
$output['moreData'] = false;
echo json_encode($output);
Change data: "userID=" + $("#userID").val()+"&pw=" + $("#pw").val(), to:
data: {userID: $("#userID").val(), pw: $("#pw").val()}
Also, I'd recommend setting userID and pw vars before passing it in as it is easier to read and easier to maintain.

AJAX: return true or false on 'success:'

I have the following AJAX script, but for some reason the var ok it's not returning true or false so the form can continue:
function ajax_call(email,title,url){
var email = document.getElementById("email").value;
var title = document.getElementById("title").value;
var url = document.getElementById("url").value;
var parametros = {"emaail":email, "tiitle":title, "uurl":url};
var ok = true;
$.ajax({
data: parametros,
url: 'validate.php',
type: 'post',
error: function () {
alert("An error has occurred! Try Again!");
},
success: function (response) {
if(response == 'bien') { ok = true; } else { $("#ajax_cal").html(response); ok = false; }
}
});
return ok;
}
HTML:
<form onsubmit="return ajax_call();">
...
</form>
PHP:
<?php
//////....
if(!empty($errors)) {
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
}
} else { echo 'bien'; }
?>
Everything works good, except for the return value.
Thanks in advance.
Prevent the submit completely, send the ajax request, then if it's good, submit the form.
HTML:
<form id="myform">
...
</form>
JavaScript:
$("#myform").submit(function(e){
// prevent submit
e.preventDefault();
var email = document.getElementById("email").value;
var title = document.getElementById("title").value;
var url = document.getElementById("url").value;
var parametros = {"emaail":email, "tiitle":title, "uurl":url};
$.ajax({
data: parametros,
url: 'validate.php',
type: 'post',
context: this,
error: function () {
alert("An error has occurred! Try Again!");
},
success: function (response) {
if($.trim(response) == 'bien') {
this.submit(); // submit, bypassing jquery bound event
}
else {
$("#ajax_call").html(response);
}
}
});
});
You are returning ok at the end of your function. This is returned before your ajax request is sent and completed.
You cannot rely on the return value of your function, you should do something inside your "success" part. It basically depends on what you want to do with your return value
I'm a complete newbie to jquery but in some of the scripts I've been working on I've had to prefix the 'response' you have.
For instance...
if(response.tiitle == 'bien') { ok = true; } else { $("#ajax_cal").html(response); ok = false; }
Also be aware you have double letters in your "parametros" but I'm sure that was intentional (i.e. tiitle and not title etc).

How to continuously update a part of the page

http://pastebin.com/dttyN3L6
The file that processes the form is called upload.php
I have never really used jquery/js so I am unsure how I would do this or where I would put the code.
It has something to do with this setInterval (loadLog, 2500);
Also, how can I make it so the user can submit a form without the page refreshing?
$.ajax({
type: "POST",
url: "upload.php",
data: dataString,
success: function() {
}
});
return false; `
and
<?php
$conn1 = mysqli_connect('xxx') or die('Error connecting to MySQL server.');
$sql = "SELECT * from text ORDER BY id DESC LIMIT 1";
$result = mysqli_query($conn1, $sql) or die('Error querying database.');
while ($row = mysqli_fetch_array($result)) {
echo '<p>' . $row['words'] . '</p>';
}
mysqli_close($conn1);
?>
</div>
<?php
if (!isset($_SESSION["user_id"])) {
} else {
require_once('form.php');
}
?>
You can submit a form without refreshing a page something like this:
form.php:
<form action='profile.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='result'>Result comes here..</div>
profile.php:
<?php
// All form data is in $_POST
// Now perform actions on form data here and
// create an result array something like this
$arr = array( 'result' => 'This is my result' );
echo json_encode( $arr );
?>
jQuery:
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
// loop to set the result(value)
// in required div(key)
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
And If you want to call an ajax request without refreshing page after a particular time, you can try something like this:
var timer, delay = 300000;
timer = setInterval(function(){
$.ajax({
type : 'POST',
url : 'profile.php',
dataType: 'json',
data : $('.ajaxform').serialize(),
success : function(data){
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
}, delay);
And you can stop the timer at any time like this:
clearInterval( timer );
Hope this will give you a direction to complete your task.
This is pretty simple.
To access elements using Jquery you use css selectors, for example, to get value of an input field with name "foo" you do the following:
var fooVal = $("input[name=foo]").val();
To send it over to the server you are to append an event listener (for example, click) to the submit button/any other element
var data = { varName : fooVal };
var url = "http://example.com";
var responseDataType = "json";
function parseResponse(JSON)
{
// your code handling server response here, it's called asynchronously, so you might want to add some indicator for the user, that your request is being processed
}
$("input[type=submit]").on('click', function(e){
e.preventDefault();
$(this).val("query processing");
$.post(url,data, parseResponse, responseDataType);
return false;
});
If you want to do constant updates, you can, of course, add timers or some other logic. But I hope you get the idea of how to proceed to such cases;
To answer part of your question, you can use ajax.
<html><head></head><body>
<div id="feed"></div>
<script type="text/javascript">
var refreshtime=10;
function tc()
{
asyncAjax("GET","upload.php",Math.random(),display,{});
setTimeout(tc,refreshtime);
}
function display(xhr,cdat)
{
if(xhr.readyState==4 && xhr.status==200)
{
document.getElementById("feed").innerHTML=xhr.responseText;
}
}
function asyncAjax(method,url,qs,callback,callbackData)
{
var xmlhttp=new XMLHttpRequest();
//xmlhttp.cdat=callbackData;
if(method=="GET")
{
url+="?"+qs;
}
var cb=callback;
callback=function()
{
var xhr=xmlhttp;
//xhr.cdat=callbackData;
var cdat2=callbackData;
cb(xhr,cdat2);
return;
}
xmlhttp.open(method,url,true);
xmlhttp.onreadystatechange=callback;
if(method=="POST"){
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xmlhttp.send(qs);
}
else
{
xmlhttp.send(null);
}
}
tc();
</script>
</body></html>

Categories