tags:

views:

457

answers:

5

I am using a ajax post in my application like

 $.ajax({
  type: "POST",
 url: "http://localhost/FormBuilder/index.php/forms/saveForm/"+user_id,

 data: "formname="+formname+"&status="+status,
  success: function(msg){
  // alert( "Data Saved: " + msg);
    }//success
 });//ajax

In the above ajax post i am saving the Form with the user id

Could i able to get the Form id of the Form that i saved in the Ajax request . If so how??

I have tried with Ajax get in a separately.But here i want to mix up both post and get.. Could i do that.. EDIT:

COuld i return any value for the Ajax POST method . Since i want to return the Form id of the Form saved..

Edit:

alert("Data Saved: "+msg); gives as

 Data Saved: {"forms":[{"id":"41"},{"id":"35"},{"id":"34"},{"id":"33"},{"id":"32"},{"id":"22"},{"id":"3"},{"id":"2"},{"id":"1"}]}

THe above is what the value returned i want only th id 41 how should i get it??

EDIT:

     $.ajax({
     type: "POST",
    url: "http://localhost/FormBuilder/index.php/forms/saveForm/"+user_id,
    datatype: 'json',
    data: "formname="+formname+"&status="+status,
     success: function(json){
        alert( "id is : " + json.forms[0].id);
                            }//success
     });//ajax

Even i tried it with the above code as suggested, But i am not able to get the alert message..

My controller code is like

     function saveForm()
    {
         //$userId=$this->Session->read('userId');
        $this->data['Form']['name']=$this->params['form']['formname'];
            $this->data['Form']['created_by']=$this->Session->read('userId');
            $this->data['Form']['status']=$this->params['form']['status'];
            $this->data['Form']['access']="Private";
            $userId=$this->Form->saveForms($this->data);
            $formid = $this->Form->find('all', array('fields' => array('Form.id'),
            'order' => 'Form.id DESC'                                            ));



            $this->set('formid',$formid);

    }

And my save_form.ctp has

      <?php
     $data=array();

      ?>
     <?php foreach ($formid as $r): 


      array_push($data, array('id' => $r['Form']['id']));

    endforeach; 

     echo json_encode(array("forms" => $data));

    ?>
+5  A: 

Yes, you can do this. You can POST to any URL you please, with or without a query string.

You can access any regular query string parameters in the $_GET array, or in your case, parse it out of $_SERVER['REQUEST_URI']. The POSTed data will be in $_POST as expected.

Edited Q.#1 "Could i return any value for the Ajax POST method?"

Yes, you can return whatever you want as your Ajax response. What you do with that response is up to your Javascript.

Edited Q.#2 "How do I read the value in the response"

You're getting a JSON response, if you tell jQuery you expect that, it can parse it into an object for you. For example, try something like this:

$.ajax({
         type: "POST",
        url: "http://localhost/FormBuilder/index.php/forms/saveForm/"+user_id,
        datatype: 'json',
        data: "formname="+formname+"&status="+status,
         success: function(json){
            alert( "id is : " + json.forms[0].id);
                                }//success
 });//ajax
Paul Dixon
You can access POST data using `$_POST` array and GET data using `$_GET`.
RaYell
how to get that returned value.. see i have added one more edit..i tried it msg.forms[0]["id"] but nothing works
Aruna
i am not able to get the alert message why so???
Aruna
I have added one more edit , please check it out..
Aruna
A: 

I'm assuming that as a result of the ajax request, the form is saved by the PHP script and you want to get the id of the form which is saved.

If so, set your php script to echo the id of the form which is saved, as its only output. Then you can use:

 success: function(id{
         // alert( "Data Saved: " + id);
                                }//id is the id
 });//ajax
Click Upvote
A: 

You can't mix POST and GET in the same AJAX request because an AJAX request is an HTTP request, and a single HTTP request has one and only one Method (GET, HEAD, POST, PUT, DELETE, TRACE or CONNECT, though I've never seen the latter two used, and PUT and DELETE aren't all that common).

Apart from that, it's not clear what you mean by "Form id" -- is the URL you're POSTing to returning some unique identifier when the POST succeeds?

Meredith L. Patterson
I think what he meant was, "can I POST to a URL with a query string?"
Paul Dixon
That does make more sense, especially after the edit. This *could* be a gotcha if the URI with a query-string refers to a different resource than the URI without one, but I'm unsure whether that's even possible. (RFC2616 punts to RFC1737 and RFC1738 on that, and I'm not as conversant with those.)
Meredith L. Patterson
A: 

Even a post request will return some data to the client. If your server side script returns any data it will be passed into the success: function(data){} function. Parse it from there!

gnarf
A: 

Briefly tested but here is a solution that seems to work...

The form page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<script type="text/javascript" src="../../scripts/ajax.js"></script>
<script type="text/javascript">
function send_ajax(){
    get = '?get_text=' + document.getElementById("get_text").value;
    get = get +'&get_text2=' + document.getElementById("get_text2").value;
    post = "post_text="+document.getElementById("post_text").value;
    post = post + "&post_text2="+document.getElementById("post_text2").value;
    path = 'prosses.php'; // path to server side prossessing page.
    element = 'result'; // placeholder for the html returned from the server side prossessing page.
    ajax(path,get,post,element);
    }
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>ajax testing page</title>
</head>

<body>
GET1: <input type="text" id="get_text" onkeyup="send_ajax()" /><br />
GET2:<input type="text" id="get_text2" onkeyup="send_ajax()" />

  <br /><br />

<form action="" method="post">
POST1:<input id="post_text" type="text" /><br />
POST2:<input id="post_text2" type="text" /><br />
<input type="button" value="Button" onclick="send_ajax()" /><br />
</form>
<span id="result">Result will appear here</span>
</body>
</html>

The ajax script:

var xmlhttp;
function ajax(path,get,post,element){
    ajax_suite(path,get,post);

function ajax_suite(path,get,post){
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null){
  alert ("http requests are not supported by your browser");
  return;
  }
  if(get == ""){
    rand = "?sid="+Math.random();
  }else{
    rand = "&sid="+Math.random();
  }
var url=path + get + rand;
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("POST", url, true); 
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", post.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(post); 
}

function stateChanged(){

if (xmlhttp.readyState==3){
document.getElementById(element).innerHTML="Loading...";
}
if (xmlhttp.readyState==4){
document.getElementById(element).innerHTML=xmlhttp.responseText;
}
}

function GetXmlHttpObject(){
if (window.XMLHttpRequest){
  // code for IE7+, Firefox, Chrome, Opera, Safari
  return new XMLHttpRequest();
  }
if (window.ActiveXObject){
  // code for IE6, IE5
  return new ActiveXObject("Microsoft.XMLHTTP");
  }
return null;
}
}

The php processing page:

GET1 = <?php echo $_GET['get_text']; ?><br>
GET2 = <?php echo $_GET['get_text2']; ?><br>
POST1 = <?php echo $_POST['post_text']; ?><br>
POST2 = <?php echo $_POST['post_text2']; ?><br>

I hope this helps

Blaise.

Blaise