Welcome Guest, Not a member yet? Register   Sign In
[jQuery/AJAX] Get php function return value
#1

[eluser]Unknown[/eluser]
In my controller content.php is a function called: create_unique_slug.
with the following content:
Code:
public function create_unique_slug($string = 'test')
{
    $slug = url_title($string);
    $slug = strtolower($slug);
    $i = 0;
    $params = array ();
    $params['page_slug'] = $slug;
    if ($this->input->post('id')) {
        $params['id !='] = $this->input->post('id');
    }
    
    while ($this->db->where($params)->get('pages')->num_rows()) {
        if (!preg_match ('/-{1}[0-9]+$/', $slug )) {
            $slug .= '-' . ++$i;
        } else {
            $slug = preg_replace ('/[0-9]+$/', ++$i, $slug );
        }
        $params ['page_slug'] = $slug;
        }
    return $slug;
}

How can i get this return $slug value with jquery?
This doesnt work:
Code:
$.ajax({
  url: './content/create_unique_slug',
  success: function(data) {
    
    alert(data);
  }
});

I would appreciate your help!
#2

[eluser]InsiteFX[/eluser]
HTML head:
Code:
// Replace the $ with s in script!
<head>
<$cript type="text/javascript" charset="utf-8">
    //&lt;![CDATA[
        var base_url = "&lt;?php echo base_url(); ?&gt;";
        var site_url = "&lt;?php echo site_url(); ?&gt;";
    // ]]>
</$cript>
&lt;/head&gt;

Code:
$.ajax({
  url: base_url+'content/create_unique_slug',
  success: function(data) {
    
    alert(data);
  }
});
#3

[eluser]weboap[/eluser]
need to send some data (the slug you got from the input) to the function in your ajax call. something like.

Code:
var myslug = $('#myinput1').val();
var myvar = $('#myinput2').val();

var postData = {
  'slug' : myslug,
  'somevar' : myvar
};

$.ajax({
  type: 'POST',
  url: base_url+'content/create_unique_slug',
  data: postData,

  success: function(data) {
    
    alert(data);
  }
});


you will be using $this->input->post(); in this case.

to send them via url you can use

Code:
....
url: base_url+'content/create_unique_slug/' + slug,
....

#4

[eluser]Unknown[/eluser]
Thanks, i fixed it with the following code:
Code:
$('.page_title').change(function(){

  var myslug = $(this).val();
  //var myslug = $(this).val($(this).val.replace(' ', '-'));
  //var myslug = $(this).val(function(i, v) {return v.replace(" ","-");}).val();

  var postData = {
    'slug' : myslug
  };  
    
  $.ajax({
    type: 'POST',
    url: base_url+'content/create_unique_slug',
    data: $('#add_page').serialize(),
  
    success: function(data) {
      //alert(data);
      $('p.help-block span').empty();
      $('p.help-block').append('<span>'+data+'</span>');
      $('input#slug').val(data);    
      $('p.help-block').fadeIn();    
    }
  });

});

And in my controller function i echoed the slug




Theme © iAndrew 2016 - Forum software by © MyBB